UNIT-4: Python conditional and iterative statements
Conditional Statements
• The if statement is the conditional statement in Python. There are 3 forms of if
statement:
• Simple if statement
• The if..else statement
• The If..elif..else statement
Simple if statement
• The if statement tests a condition & in case the condition is True, it carries out some
instructions and does nothing in case the condition is False.
• Syntax
if <condition>:
statement
[statements]
e.g.
if amount>1000:
disc = amount * .10
Example of if statement
Prog to find discount (10%) if amount is more than 1000.
Price = float (input(“Enter Price ? ” ))
Qty = float (input(“Enter Qty ? ” ))
Amt = Price* Qty
print(“ Amount :” , Amt)
if Amt >1000:
disc = Amt * .10
print(“Discount :”, disc)
The if-else statement
The if - else statement tests a condition and in case the condition is True, it carries out
statements indented below if and in case the condition is False, it carries out statement
below else.
Syntax
if <condition> :
statement
[statements]
else :
statement
[statements]
e.g.
if amount>1000:
disc = amount * 0.10
else:
disc = amount * 0.05
Example of if-else statement
ROFEL,Shri G.M Bilakhia College of Applied Sciences
UNIT-4: Python conditional and iterative statements
Prog to find discount (10%) if amount is more than 1000, otherwise (5%).
Price = float (input(“Enter Price ? ” ))
Qty = float (input(“Enter Qty ? ” ))
Amt = Price* Qty
print(“ Amount :” , Amt)
if Amt >1000 :
disc = Amt * .10
print(“Discount :”, disc)
else :
disc = Amt * .05
print(“Discount :”, disc)
The if..elif statement
The if - elif statement has multiple test conditions and in case the condition1 is True, it
executes statements in block1, and in case the condition1 is False, it moves to
condition2, and in case the condition2 is True, executes statements in block2, so on. In
case none of the given conditions is true, then it executes the statements under else block
Syntax
if <condition1> :
statement
[statements]
elif <condition2> :
statement
[statements]
elif <condition3> :
statement
[statements]
:
:
else :
statement
[statements]
Example of if-elif statement
Prog to find discount (20%) if amount>3000, disc(10%) if Amount <=3000 and >1000,
otherwise (5%).
Price = float (input(“Enter Price ? ” ))
Qty = float (input(“Enter Qty ? ” ))
Amt = Price* Qty
print(“ Amount :” , Amt)
if Amt >3000 :
disc = Amt * .20
print(“Discount :”, disc)
elif Amt>1000:
disc = Amt * .10
print(“Discount :”, disc)
ROFEL,Shri G.M Bilakhia College of Applied Sciences
UNIT-4: Python conditional and iterative statements
else :
disc = Amt * .05
print(“Discount :”, disc)
Example of Nested if statement
Prog to find Largest of Three Numbers (X,Y,Z)
X = int (input(“Enter Num1 ? ” ))
Y = int (input(“Enter Num2 ? ” ))
Z = int (input(“Enter Num3 ? ” ))
if X>Y:
if X > Z:
Largest = X
else:
Largest = Z
else:
if X > Z:
Largest = X
else:
Largest = Z
print(“Largest Number :”, Largest)
LOOPS
It is used when we want to execute a sequence of statements (indented to the right of
keyword for) a fixed number of times.
Syntax of for statement is as follows:
i) with range() function
ii) with sequence
The for Loop
Syntax 1:
for <Var> in range (val1, val2, Val3):
Statements to be repeated
Syntax 2:
for <Var> in <Sequence> :
Statements to repeat
The range() function
range( 1 , n):will produce a list having values starting from 1,2,3… upto n-1.The default
step size is 1
range( 1 , n, 2):will produce a list having values starting from 1,3,5… upto n-1.The step
size is 2
1) range( 1 , 7): will produce 1, 2, 3, 4, 5, 6.
2) range( 1 , 9, 2): will produce 1, 3, 5, 7.
3) range( 5, 1, -1): will produce 5, 4, 3, 2.
3) range(5): will produce 0,1,2,3,4 default start value is 0
ROFEL,Shri G.M Bilakhia College of Applied Sciences
UNIT-4: Python conditional and iterative statements
for loop implementation
Sum=0
for i in range(1, 11):
print(i)
Sum=Sum + i
print(“Sum of Series”, Sum)
Sum=0
For i in range(10, 1, -2):
print(i)
Sum=Sum + i
print(“Sum of Series”, Sum)
for loop: Prog check a number for PRIME
METHOD 1
num= int(input(“Enter Num?”))
flag=1
for i in range(2, num//2+1):
if num%i == 0:
flag = 0
break
if flag == 1:
print(“It is Prime No.”)
else:
print(“It is Not a Prime No.”)
METHOD 2: using loop else
num= int(input(“Enter Num?”))
for i in range(2, num//2+1):
if num%i == 0:
print(“It is Prime No.”)
break
else:
print(“It is Not a Prime No.”)
Note: the else clause of a loop will be executed only when the loop terminates normally
(not when break statement terminates the loop)
Nested for Loop
for i in range ( 1, 6 ):
print( )
for j in range (1, i + 1):
print(“@”, end=“ ”)
ROFEL,Shri G.M Bilakhia College of Applied Sciences
UNIT-4: Python conditional and iterative statements
Will produce following output
@
@@
@@@
@@@@
@@@@@
The while Loop
It is a conditional loop, which repeats the statements with in itself as long as condition
is true.
The general form of while loop is:
while <condition> :
Statement loop body
[Statements] (these statements repeated until
condition becomes false)
Example:
k = 1, sum=0
while k <= 4 :
print (k)
sum=sum + k
print(“Sum of series:”, sum)
Strong number
find the factorial of each of the digits in the number.
Then sum up all the factorials of the digit
if the sum of the factorials of the digits is equal to the number.
Example:145
Else clause
• In Python, the else clause can be used with a while statement.
• The else block is gets executed whenever the condition of the while statement is
evaluated to false.
• But, if the while loop is terminated with break statement then else doesn't execute.
• Else statement can also be used with the for statement in Python
ROFEL,Shri G.M Bilakhia College of Applied Sciences
UNIT-4: Python conditional and iterative statements
while loop: Implementation
Prog. To find digit sum
num = int(input(“No.?”))
ds = 0
while num>0 :
ds = ds +num % 10
num = num // 10
print(“Digit Sum :”, ds)
Prog. To find reverse
num = int(input(“No.?”))
rev = 0
while num>0 :
d = num % 10
rev = rev*10 + d
num = num // 10
print(“Reverse :”, rev)
ROFEL,Shri G.M Bilakhia College of Applied Sciences
UNIT-4: Python conditional and iterative statements
Break Statement:
The break statement is used to terminate the loop containing it, the control of the program
will come out of that loop.
Syntax:
Break
for char in ‘Python’:
if (char == ‘h’):
break
print(“Current character: “, char)
ROFEL,Shri G.M Bilakhia College of Applied Sciences
UNIT-4: Python conditional and iterative statements
Output:
Current character: P
Current character: y
Current character: t
Continue statement
When the program encounters a continue statement, it will skip the statements which are
present after the continue statement inside the loop and proceed with the next iterations.
Loop does not terminate but continues on with the next iteration.
Syntax:
Continue
Example:
for char in ‘Python’:
if (char == ‘y’):
continue
print(“Current character: “, char)
Output:
ROFEL,Shri G.M Bilakhia College of Applied Sciences
UNIT-4: Python conditional and iterative statements
Current character: P
Current character: t
Current character: h
Current character: o
Current character: n
Pass Statement:
Pass statement is python is a null operation, which is used when the statement is required
syntactically.
Syntax:
pass
Example:
for char in ‘Python’:
if (char == ‘h’):
pass
print(“Current character: “, char)
Output:
Current character: P
Current character: y
Current character: t
Current character: h
Current character: o
Current character: n
ROFEL,Shri G.M Bilakhia College of Applied Sciences
UNIT-4: Python conditional and iterative statements
Lists
• List is an ordered sequence of items. Values in the list are called elements / items.
• It can be written as a list of comma-separated items (values) between square
brackets[ ].
• Items in the lists can be of different data types.
Operations on list:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Updating
6. Membership
7. Comparison
operations examples description
create a list >>> a=[2,3,4,5,6,7,8,9,10] in this way we can create a
>>> print(a) list at compile time
[2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> Accessing the item in the
Indexing print(a[0]) position 0
2 Accessing the item in the
>>> print(a[8]) position 8
10 Accessing a last element
>>> print(a[-1]) using negative indexing.
10
>>> print(a[0:3])
Slicing [2, 3, 4]
>>> print(a[0:]) Printing a part of the list.
[2, 3, 4, 5, 6, 7, 8, 9, 10]
>>>b=[20,30] Adding and printing the
Concatenation >>> print(a+b) items of two lists.
[2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30]
ROFEL,Shri G.M Bilakhia College of Applied Sciences
UNIT-4: Python conditional and iterative statements
>>> print(b*3) Create a multiple copies of
Repetition [20, 30, 20, 30, 20, 30] the same list.
>>> print(a[2])
4 Updating the list using
Updating >>> a[2]=100 index value.
>>> print(a)
[2, 3, 100, 5, 6, 7, 8, 9, 10]
>>> a=[2,3,4,5,6,7,8,9,10]
>>> 5 in a
Membership True Returns True if element is
>>> 100 in a present in list. Otherwise
False returns false.
>>> 2 not in a
False
>>> a=[2,3,4,5,6,7,8,9,10]
>>>b=[2,3,4] Returns True if all elements
Comparison >>> a==b in both elements are same.
False Otherwise returns false
>>> a!=b
True
List slices:
List slicing is an operation that extracts a subset of elements from an list and packages
them as another list.
Syntax:
Listname[start:stop]
Listname[start:stop:steps]
default start value is 0
default stop value is n-1
[:] this will print the entire list
[2:2] this will create a empty slice
ROFEL,Shri G.M Bilakhia College of Applied Sciences
UNIT-4: Python conditional and iterative statements
slices example description
>>> a=[9,8,7,6,5,4]
a[0:3] >>> a[0:3] Printing a part of a list
from 0 to 2.
[9, 8, 7]
a[:4] >>> a[:4] [9, 8, 7, 6] Default start value is 0. so
prints from 0 to 3
a[1:] >>> a[1:] [8, 7, 6, 5, 4] default stop value will be
n-1. so prints from 1 to 5
a[:] >>> a[:] Prints the entire list.
[9, 8, 7, 6, 5, 4]
a[2:2] >>> a[2:2] print an empty slice
[]
a[0:6:2] >>> a[0:6:2] Slicing list values with
step size 2.
[9, 7, 5]
a[::-1] >>> a[::-1] [4, 5, 6, 7, 8, 9] Returns reverse of given
list values
List methods:
• Methods used in lists are used to manipulate the data quickly.
• These methods work only on lists.
• They do not work on the other sequence types that are not mutable, that is, the
values they contain cannot be changed, added, or deleted.
• Syntax:
o Listname.method(element/index/list)
ROFEL,Shri G.M Bilakhia College of Applied Sciences
UNIT-4: Python conditional and iterative statements
7 a.pop() >>> a.pop() Removes and returns
an element at the last
0
position(index)
8 a.pop(index) >>> a.pop(0) Remove the
particular element
8
and return it.
9 a.remove(element) >>> a.remove(1) Removes an item
from the list
>>> print(a)
[7, 6, 5, 4, 3, 2]
10 a.count(element) >>> a.count(6) Returns the count of
number of items
1
passed as an
argument
ROFEL,Shri G.M Bilakhia College of Applied Sciences
UNIT-4: Python conditional and iterative statements
11 a.copy() >>> b=a.copy() Returns a shallow
copy of the list
>>> print(b)
[7, 6, 5, 4, 3, 2]
12 len(list) >>> len(a) return the length of
the length
6
13 min(list) >>> min(a) return the minimum
element in a list
2
14 max(list) >>> max(a) return the maximum
element in a list.
7
15 a.clear() >>> a.clear() Removes all items
from the list.
>>> print(a)
[]
16 del(a) >>> del(a) delete the entire list.
>>> print(a)
Error: name 'a' is not
defined
List loops:
1. For loop
2. While loop
3. Infinite loop List using For Loop:
• The for loop in Python is used to iterate over a sequence (list, tuple, string) or other
iterable objects.
• Iterating over a sequence is called traversal.
• Loop continues until we reach the last item in the sequence.
• The body of for loop is separated from the rest of the code using indentation.
Syntax:
for val in sequence:
ROFEL,Shri G.M Bilakhia College of Applied Sciences
UNIT-4: Python conditional and iterative statements
Accessing element output
a=[10,20,30,40,50] 1
for i in a: 2
print(i) 3
4
5
Accessing index output
a=[10,20,30,40,50] 0
for i in range(0,len(a),1): 1
print(i) 2
3
4
Accessing element using range: output
a=[10,20,30,40,50] 10
for i in range(0,len(a),1): 20
print(a[i]) 30
40
50
List using While loop
The while loop in Python is used to iterate over a block of code as long as the test
expression (condition) is true.
When the condition is tested and the result is false, the loop body will be skipped and the
first statement after the while loop will be executed.
Syntax:
while (condition):
body of while
ROFEL,Shri G.M Bilakhia College of Applied Sciences
UNIT-4: Python conditional and iterative statements
Sum of elements in list Output:
a=[1,2,3,4,5] i=0 15
sum=0 while i<len(a):
sum=sum+a[i]
i=i+1
print(sum)
Mutability:
Lists are mutable. (can be changed)
Mutability is the ability for certain types of data to be changed without entirely recreating
it.
An item can be changed in a list by accessing it directly as part of the assignment statement.
Using the indexing operator (square brackets[ ]) on the left side of an assignment, one of
the list items can be updated.
Example description
>>> a=[1,2,3,4,5] changing single element
>>> a[0]=100
>>> print(a)
[100, 2, 3, 4, 5]
>>> a=[1,2,3,4,5] changing multiple element
>>> a[0:3]=[100,100,100]
>>> print(a)
[100, 100, 100, 4, 5]
>>> a=[1,2,3,4,5] The elements from a list can also be removed by
assigning the empty list to them.
>>> a[0:3]=[ ]
>>> print(a)
[4, 5]
ROFEL,Shri G.M Bilakhia College of Applied Sciences
UNIT-4: Python conditional and iterative statements
>>> a=[1,2,3,4,5] The elements can be inserted into a list by
squeezing them into an empty slice at the desired
>>> a[0:0]=[20,30,45]
location.
>>> print(a)
[20,30,45,1, 2, 3, 4, 5]
ROFEL,Shri G.M Bilakhia College of Applied Sciences