0% found this document useful (0 votes)
3 views64 pages

Unit - 4 Python Conditional and Iterative Statements

This document covers Python's conditional and iterative statements, including if, elif, and else statements, as well as nested if statements. It also discusses iterative statements such as while and for loops, including their control statements like break and continue, and provides an overview of list operations including creation, indexing, and methods. The document serves as a comprehensive guide for understanding decision-making and looping constructs in Python programming.

Uploaded by

jemisunagar28
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views64 pages

Unit - 4 Python Conditional and Iterative Statements

This document covers Python's conditional and iterative statements, including if, elif, and else statements, as well as nested if statements. It also discusses iterative statements such as while and for loops, including their control statements like break and continue, and provides an overview of list operations including creation, indexing, and methods. The document serves as a comprehensive guide for understanding decision-making and looping constructs in Python programming.

Uploaded by

jemisunagar28
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 64

Unit -4

Python conditional and iterative


statements

• 4.1 if statement, if..elif statement, if..elif…else statements, nested if


• 4.2 Iterative statements :
• 4.2.1 while loop, nested while loop, break , continue statements.
• 4.2.2 for loop, range, break, continue, pass and Else with for loop,
• for loop.
• 4.3 List : creating list, indexing, accessing list members, range in list,
List methods (append, clear, copy, count, index, insert, pop, remove,
• reverse, sort).
If…else
• There comes situations in real life when we need to make
some decisions and based on these decisions, we decide
what should we do next. Similar situations arises in
programming also where we need to make some decisions
and based on these decisions we will execute the next
block of code.
• Decision making statements in programming languages
decides the direction of flow of program execution.
Decision making statements available in python are:
• if statement
• if..else statements
• nested if statements
• if-elif ladder
If…Statement
• As we know, python uses indentation to
identify a block. So the block under an if
statement will be identified as shown in the
below example:
• if condition:
statements1
statement2
• i = 10
• if (i > 15):
• print ("10 is less than 15")
• print (“not in if”)
• o/p= not in if [ i value is not greater than 15]

if..else statements

• The if statement tells us that if a condition is


true it will execute first block of statements
and if the condition is false it will execute the
second block of statement which is after else
• if (condition):
Statement1 #condition is true
else:
Statement2 # condition is false
• i = 20;
• if (i < 15):
• print ("i is smaller than 15")
• print ("i'm in if Block")
• else:
• print ("i is greater than 15")
• print ("i'm in else Block")
• print ("i'm not in if and not in else Block")
• o/p= i is greater than 15
• i'm in else Block
i'm not in if and not in else Block
if..elif…else statements
• Here, a user can decide among multiple options. The if
statements are executed from the top down. As soon as one
of the conditions controlling the if is true, the statement
associated with that if is executed, and the rest of the ladder
is bypassed. If none of the conditions is true, then the final
else statement will be executed.
• if (condition):
statement1
elif (condition):
statement2 . .
else:
statement
if..elif…else statements
• i = 20
• if (i == 10):
• print ("i is 10")
• elif (i==15):
• print ("i is 15")
• elif (i == 20):
• print ("i is 20")
• else:
• print ("i is not present")
• o/p : i is 20
nested if statements

• Nested if statements means an if statement


inside another if statement.
• if (condition1):
• Statement 1 # Executes when condition1 is true
• if (condition2):
• Statement2 # Executes when condition2 is true
• # if Block is end here
• # if Block is end here
nested if statements
• i = 10
• if (i == 10):
• # First if statement
• if (i < 15):
• print ("i is smaller than 15")
• # Nested - if statement
• # Will only be executed if statement above
• # it is true
• if (i < 12):
• print ("i is smaller than 12 too")
• else:
• print ("i is greater than 15")
• o/p:i is smaller than 15
• i is smaller than 12 too
4.2 Iterative statements
While loop
• In Python, While Loops is used to execute a
block of statements repeatedly until a given
condition is satisfied. And when the condition
becomes false, the line immediately after the
loop in the program is executed.
• Syntax:
• while expression :
statement(s)
While Loop
• count = 0
• while (count < 3):
• count = count + 1
• print(count)

• o/p : 1
• 2
• 3
nested while loop
• Python programming language allows to use
one loop inside another loop.
• Syntax
• while expression:
while expression:
statement(s)
statement(s)
• i=1

• while (i<=5):
• j=1
• while(j<=i):
• print(j,end="")
• j=j+1
• print()
• i=i+1
• o/p : 1
• 12
• 123
• 1234
• 12345
In while loop break and continue
statements
• You might face a situation in which you need to exit a
loop completely when an some condition is becomes
true or there may also be a situation when you want
to skip a part of the loop and start next execution.
• Python provides break and continue statements to
handle such situations and to have good control on
your loop.
Use of break statement
• The break statement in Python terminates the
current loop and resumes execution at the
next statement after the loop.
• The most common use for break is when some
external condition is triggered requiring a
sudden exit from a loop. The break statement
can be used in both while and for loops.
• var = 10
• while var > 0:
• print ( 'Current variable value :', var)
• var = var -1
• if var == 5:
• break
• print "Good bye!“


o/p Current variable value : 10
Current variable value : 9
• Current variable value : 8
• Current variable value : 7
• Current variable value : 6
• Good bye!
Continue in while

1) The continue statement in Python returns


the control to the beginning of the while loop.
2)The continue statement rejects all the
remaining statements in the current iteration
of the loop and moves the control back to the
top of the loop.
• var = 10
• while var > 0:
var = var -1
if var == 5:
continue
print ('Current variable value :', var)
print ("Good bye!”)
o/p :
Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6
Current variable value : 4
Current variable value : 3
Current variable value :2
Current variable value : 1
Good bye!
For loop
• A for loop is used for iterating over a sequence
(that is either a list, a tuple, a dictionary, a set,
or a string).
• With the for loop we can execute a set of
statements, once for each item in a list, tuple,
set or string ..
• For loop is executed till the given range is true
Looping Through a String

• Even strings are iterable objects, they contain


a sequence of characters:
• for x in “Vivekanand":
print(x)
• The above loop is executed 10 times.. For each
character once the loop is executed..and
prints each character in separate line

The range() Function

• To loop through a set of code a specified


number of times, we can use
the range() function,
• The range() function returns a sequence of
numbers, starting from 0 by default, and
increments by 1 (by default), and ends at a
specified number.
The range function
• for x in range(6):
print(x)
• It starts from 0 but 6 is not included
• 0
• 1
• 2
• 3
• 4
• 5
The range() Function

• The range() function defaults to 0 as a starting value, however


it is possible to specify the starting value by adding a
parameter: range(2, 6), which means values from 2 to 6 (but
not including 6):
• for x in range(2, 6):
print(x)
• o/p
• 2
• 3
• 4
• 5
The range() Function
• The range() function defaults to increment the sequence by 1,
however it is possible to specify the increment value by adding a
third parameter: range(2, 30, 3):
• for x in range(2, 30, 3):
print(x)
• o/p:
• 2
• 5
• 8
• 11
• 14
• 17
• 20
• 23
• 26
• 29
Else in For Loop

• The else keyword in a for loop specifies a block of code


to be executed when the loop is finished.
• for x in range(6):
print(x)
else:
print("Finally finished!")
• o/p: 0…5
• finally finished
• If the loop is stopped by break statement then else
part will not be executed

Break statement in For
• Break statement will stop the loop abruptly when
a condition is triggered.
• for x in range(6):
• if x==3:
• break
print(x)
• o/p: 0
• 1
• 2
Continue in for
• With the continue statement we can skip the
current iteration of the loop, and continue with
the next
• Example:
• for x in "vivekanand":
• if x == "n":
• continue
• print(x)
• It will not print n in the word
Nested ..for
• If we have loop inside another loop then it is
called nested loop
for i in range(1,4,1):
• for j in range(1,i+1,1):
• print(j,end="")
• print()
• o/p:
• 1
• 12
• 123
Pass in for
• for loops cannot be empty, but if you for some reason
have a for loop with no content, put in
the pass statement to avoid getting an error.
• for letter in 'Python':
• if letter == 'h':
• pass
• print ('This is pass block')
• print ('Current Letter :', letter)
• print ("Good bye!")
o/p:
• Current Letter : P
• Current Letter : y
• Current Letter : t
• This is pass block
• Current Letter : h
• Current Letter : o
• Current Letter : n
• Good bye!
• for i in range(10):
for x in range(100000000) :
pass
print(i)
Python pass vs Python continue
statements
• The difference
between pass and continue statements is
based on the jumping of program execution
after its execution.
• pass statement passes the execution to next
statement.
• continue statement passes the execution to
next iteration (condition)of loop.
List : creating list, indexing, accessing list members, range in
list

• Lists are used to store multiple items in a single variable.


• It is used to store heterogeneous data in a single name.
• Each element has position or index
• First index is zero.
• Operations are
– Creating
– Slicing
– Deleting
– Adding
– Removing
– Inserting
– sort
Creating the list
• Creating a list is as simple as putting different
comma-separated values between square
brackets
• You can create the list in following way:
• Lst=[] ## creating empty list
• Lst1=[10,”abc”,12.34] ## creating list with different
values
print(Lst1)
o/p : [10,”abc”,12.34]
Indexing …list
• List values are stored in ordered manner.
• The index values starts from “0”
• Example:
• list1 = ['physics', 'chemistry', 1997, 2000.5];
• here physics is stored in 0th place
• chemistry in 1st place
• 1997 in 2nd place
• 2000.5 in 3rd place
• index() is an inbuilt function in Python, which searches
for a given element from the start of the list and
returns the lowest index where the element appears.
• Syntax :
• list_name.index(element, start, end)

• list1 = [1, 2, 3, 4, 1, 1, 1, 4, 5]
• print(list1.index(4)) ## prints 3
• print(list1.index(4,4)) ## prints 7
• print(list1.index(1,2,6)) ## prints 4

• print(list1.index(5,2,6))
Accessing list members
• You access the list items by referring to the index number:
• Example:
• list2 = ['cat', 'bat', 'mat', 'cat‘, 'get‘, 'pet']
• Print(list2[3]) ## o/p cat

• Negative Indexing:
• Negative indexing means beginning from the end, -1 refers to the
last item, -2 refers to the second last item etc.

• list2 = ['cat', 'bat', 'mat', 'cat‘,'get‘, 'pet']


• Print(list2[-4]) ## o/p mat

Range in List
• You can specify a range of indexes by specifying where to start
and where to end the range.
• When specifying a range, the return value will be a new list with
the specified items.
• list2 = ['cat', 'bat', 'mat', 'cat','get', 'pet']
• print(list2[2:5]) ##o/p ['mat', 'cat', 'get']
• Print(list2[-5:-3]) ## o/p ['bat', 'mat']
• Print(list2[:3]) ## o/p ['cat', 'bat', 'mat‘]
• Print(list2[3:]) ##o/p ['cat', 'get', 'pet']
Adding in the list:
• There are two methods for adding the elements
• Append
• insert
• Append():Used for appending and adding elements to
List.It is used to add elements to the last position of
List.
• Syntax: list.append (element)
• Eg:Lst = ['Mathematics', 'chemistry', 1997, 2000]
• Lst.append(“20544”)
• print(Lst)
• o/p
• ['Mathematics', 'chemistry', 1997, 2000, “20544”]
Adding in the list:
• Insert method:

• insert(): Inserts an elements at specified position.


Syntax: list.insert(position, element)
• Eg:
• Lst = ['Mathematics', 'chemistry', 1997, 2000]
• # Insert at index 2 value 1087
• Lst.insert(5,’1087’)
• print(Lst)

• o/p:
• ['Mathematics', 'chemistry', 1997, 2000, 20544,’1087’]
Clear..list
• Clear():Removes all the elements from the list
• lst = ['Hello','Python',‘c++']
• print(lst)
• lst.clear()
• print(lst)
o/p:
• ['Hello','Python',‘c++']
• []
Copy…List
• copy(): Returns a shallow copy of the list.
• lst = ['Hello', 'Python', ‘c++']
• lst1 = lst
• lst1.append('Java')
• print(lst) ## ['Hello', 'Python',
‘c++‘,’java’]
• print(lst1) ## ['Hello', 'Python', ‘c++‘,’java’]

• #With copy
• lst = ['Hello', 'Python', ‘c++']
• lst1 = lst.copy()
• lst1.append("Java")
• print(lst) ## ['Hello', 'Python', ‘c++‘]
• print(lst1) ## ['Hello', 'Python', ‘c++‘,’java’]
Count…list
• count():
• Returns the number of elements with the
specified value.
• lst = ['Hello', 'Python', ‘java','Python']
• print(lst.count("Python")) ## 2
• print(lst.count(“java")) ## 1
• print(lst.count(" ")) ## 0
Pop..List
• Pop():Removes the element at the specified position
• Syntax: list.pop() :it removes last element
• list.pop(3): it removes third index element (4th)
• lst = ['CPlusPlus', 'Hello', 'Python', 'Java', ‘java', 'Python']
• print(lst)
• #Without index lst.pop()
• print(lst)
• #With Index
• lst.pop(3)
• print(lst)
Remove…List
• Remove(): It removes the element from the
list
• Syntax: list.remove(obj)
• Eg:lst = ['CPlusPlus', 'Hello', 'Python', 'Java']
• lst.remove(“hello”)
• print(lst) ## o/p = ['CPlusPlus', 'Python', 'Java']
Reverse …list
• Reverse(): It will reverse the whole list
• Syntax: list.reverse()
• Eg:lst = ['CPlusPlus', 'Hello', 'Python', 'Java']
• lst.reverse()
• print(lst) ## [‘java’,Python’,’Hello’,'CPlusPlus‘]
Sort…List

• Sort():It sorts the elements in the list


inscending or decending order
• Syntax: list.sort(reverse=True or False)
• Eg: lst2 = ['cat', 'bat', 'mat', 'cat','get', 'pet']
• lst2.sort() ##['bat', 'cat', 'cat', 'get', 'mat', 'pet']
• lst2.sort(reverse=True) ## ['pet', 'mat', 'get',
'cat', 'cat', 'bat']
Methods..List
• Sr.No Methods Description
• 1 list.append(obj) Appends object obj to list

• 2 list.count(obj) Returns count of how many


times obj occurs in list
3 list.extend(seq) Appends the contents of seq
to list
4 list.index(obj) Returns the lowest index in list
that obj appears
5 list.insert(index, obj) Inserts object obj into list at
offset index
6 list.pop(obj=list[-1]) Removes and returns last
object or obj from list
7 list.remove(obj) Removes object obj from list

• 8 list.reverse() Reverses objects of list in place

• 9 list.sort([func]) Sorts objects of list, use


compare func if given
Python includes the following list
functions

• Sr.No Function Description


• 1 cmp(list1, list2) Compares elements of
both lists.
2 len(list) Gives the total length of
the list
3 max(list) Returns item from the
list with max value.
4 min(list) Returns item from the
list with min value.
Python Collections
Tuple

• Tuples are used to store multiple items in a single variable.

• Tuple is one of 4 built-in data types in Python used to store collections of


data, the other 3 are List, Set, and Dictionary, all with different qualities
and usage.

• A tuple is a collection which is ordered and unchangeable.

• Tuples are written with round brackets.


• Eg:
ABtuple = (“Tom", “Dick", “Harry")
print(ABtuple)
• Tuple Items:
• Tuple items are ordered, unchangeable, and allow duplicate values.
• Tuple items are indexed, the first item has index [0], the second
item has index [1] etc.
• Ordered
• When we say that tuples are ordered, it means that the items have
a defined order, and that order will not change.
• Unchangeable
• Tuples are unchangeable, meaning that we cannot change, add or
remove items after the tuple has been created.
• Allow Duplicates
• Since tuples are indexed, they can have items with the same value:
• Example
• Tuples allow duplicate values:
• thistuple = (“Tom", “Dick", “Harry“,”Tom”)
print(thistuple)
Access Tuple Items

• You can access tuple items by referring to the


index number, inside square brackets:
• Example
• Print the second item in the tuple:
• thistuple = (“Tom", “Dick", “Harry")
print(thistuple[1])
Access Tuple Items
• You can access tuple items by referring to the index number, inside
square brackets:
• Example
• Print the second item in the tuple:
• thistuple = (“Tom", “Dick", “Harry")
print(thistuple[1])
• Negative Indexing
• Negative indexing means start from the end.
• -1 refers to the last item, -2 refers to the second last item etc.
• Example
• Print the last item of the tuple:
• thistuple = (“Tom", “Dick", “Harry")
print(thistuple[-1])
Range of Indexes

• You can specify a range of indexes by specifying


where to start and where to end the range.
• When specifying a range, the return value will be
a new tuple with the specified items.
• thistuple = (“Tom", “Dick", “Harry“,”james”,”Bond”)
• Print(thistuple[2:3]) ## (“Harry“)
• Print(thistuple[2:]) ## (“Harry“,”james”,”Bond”)
• Print(thistuple[:2]) ## (“Tom", “Dick")
• print(thistuple[-4:-1]) ???
Change Tuple Values

• Once a tuple is created, you cannot change its values.


Tuples are unchangeable, or immutable as it also is
called.
• But there is a workaround. You can convert the tuple
into a list, change the list, and convert the list back into
a tuple.
• x = (“Tom", “Dick", “Harry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x) ## (“Tom", “kiwi", “Harry")
• Add Items
• Once a tuple is created, you cannot add items to it.
• Example
• thistuple = (“Tom", “Dick", “Harry")
• y = list(thistuple)
y.append("orange")
thistuple = tuple(y)

• Remove Items
• Note: You cannot remove items in a tuple.
• Tuples are unchangeable, so you cannot remove items from it, but
you can use the same workaround as we used for changing and
adding tuple items:
• Example
• Convert the tuple into a list, remove “Tom", and convert it back into
a tuple:
• Thistuple= (“Tom", “Dick", “Harry")
y = list(thistuple)
y.remove(“Tom")
thistuple = tuple(y)
• Delete tuple
• thistuple = (“Tom", “Dick", “Harry") del thistuple
print(thistuple)
• Tuple Methods
• Python has two built-in methods that you can use on
tuples.
• count() Returns the number of times a specified value
occurs in a tuple
• thistuple = ("Tom","Dick","Harry","Tom")
• print(thistuple.count('Tom'))
• index() Searches the tuple for a specified value and returns
the position of where it was found
thistuple = (“Tom", “Dick", “Harry")
• print(thistuple.index(‘Dick’) ## case sensitive
• o/p=1
Set
Sets: declaring set, access set data, set methods (add, clear, copy,
discard, pop, remove, union, update).

• Sets are used to store multiple items in a


single variable.
• Set is one of 4 built-in data types in Python
used to store collections of data, the other 3
are List, Tuple, and Dictionary, all with
different qualities and usage.
• A set is a collection which is
both unordered and unindexed.
• Sets are written with curly brackets.
• Example
• Create a Set:
• thisset = {"apple", "banana", "cherry"}
print(thisset)

• Access Set:
• You cannot access items in a set by referring to an index or a key.
• But you can loop through the set items using a for loop, or ask if a
specified value is present in a set, by using the in keyword.
• Example
• Loop through the set, and print the values:
• thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
• Add Items
• Once a set is created, you cannot change its items, but you can add new items.
• To add one item to a set use the add() method.
• Example
• Add an item to a set, using the add() method:
• thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)

• Add Sets
• To add items from another set into the current set, use the update() method.
• Example
• Add elements from tropical and thisset into newset:
• thisset = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya"}
thisset.update(tropical)
print(thisset)
• Remove Item
• To remove an item in a set, use the remove(), or
the discard() method.
• Example
• Remove "banana" by using the remove() method:
• thisset = {"apple", "banana", "cherry"}

thisset.remove("banana")
or
• thisset.discard("banana")

print(thisset)
• Union
• Two sets can be merged using union() function
or | operator.
• people = {"Jay", "Idrish", "Archil"}
• vampires = {"Karan", "Arjun"}
• dracula = {"Deepanshu", "Raju"}
• population = people.union(vampires)
• o/p {'Idrish', 'Jay', 'Karan', 'Archil', 'Arjun'}
• population = people|dracula
• o/p {'Idrish', 'Jay', 'Archil', 'Raju', 'Deepanshu'}
• Clearing sets
• Clear() method empties the whole set.

• set1 = {1,2,3,4,5,6}

• print("Initial set")
• print(set1)

• set1.clear()

• print("\nSet after using clear() function")
• print(set1)
• Output:Initial set {1, 2, 3, 4, 5, 6}
• Set after using clear() function set()
• Pop(): This method removes a random element from
the set and returns the removed element.
• people = {"Jay", "Idrish", "Archil"}
• People.pop()
• Print(people)
• Update():The update() method updates the current
set, by adding items from another set (or any other
iterable).
• x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.update(y)
print(x)
• o/p {'apple', 'banana', 'cherry', 'microsoft', 'google'}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy