Unit 2
Unit 2
var2 = 0
if var2:
print "2 - Got a true expression value"
print var2
else:
print "2 - Got a false expression value"
print var2
print "Good bye!"
The Nested if...elif...else Construct
Example:
var = 100
if var < 200:
print "Expression value is less than 200"
if var == 150:
print "Which is 150"
elif var == 100:
print "Which is 100"
elif var == 50:
print "Which is 50"
elif var < 50:
print "Expression value is less than 50"
else:
print "Could not find true expression"
• Loops
Python Programming 13
Printing Multiplication Table
5 X 1 = 5
5 X 2 = 10
5 X 3 = 15
5 X 4 = 20
5 X 5 = 25
5 X 6 = 30
5 X 7 = 35
5 X 8 = 40
5 X 9 = 45
5 X 10 = 50
n = int(input('Enter a Too
number:
much '))
print (n, 'X', 1, '=', n*1)
repetition!
print (n, 'X', 2, '=', n*2)
Can I avoid
print (n, 'X', 3, '=', n*3)it?
print (n, 'X', 4, '=', n*4)
print (n, 'X', 5, '=', n*5)
print (n, 'X', 6, '=', n*6)
….
Jan-24 15
Python Programming
Printing Multiplication Table
Loop Exit
i <=10 FALSE
TRUE
Loop
Jan-24 Python Programming
Printing Multiplication Table
Input n
i=1
TRUE
i <=10
FALSE n = int(input('n=? '))
i=1
Print n x i = ni Stop
i = i+1
while (expression):
S1 FALSE
expression
S2
TRUE
S1 S2
1. Evaluate expression
2. If TRUE then
a) execute statement1
b) goto step 1.
3. If FALSE then execute statement2.
19
Jan-24 Python Programming
While loop with List
5
a=[1,2,3,4,5]
4
while a: 3
print(a.pop()) 2
1
The Infinite Loops:
• You must use caution when using while loops because
of the possibility that this condition never resolves to
a false value. This results in a loop that never ends.
Such a loop is called an infinite loop.
•Traceback
An infinite
(most recent loop
call last): might be useful in client/server
programming
File where the server needs line
"C:/Users/SBJ/AppData/Local/Programs/Python/Python310/wh1.py", to1, in run
<module>
continuously
while var == 1 :
so that client programs can
communicate
NameError: name 'var' is with it as
not defined. Didand when
you mean: required.
'vars'?
Example:
count=0
while (count<5):count+=1; print(“Hello, Everyone”)
Hello, Everyone
Hello, Everyone
Hello, Everyone
Hello, Everyone
Hello, Everyone
6. Python - for Loop Statements
• The for loop in Python has the ability to iterate over the items
of any sequence, such as a list or a string.
• The syntax of the loop look is:
for iterating_var in sequence: Current Letter : P
Current Letter : y
statements(s) Current Letter : t
Example: Current Letter : h
Current Letter : o
for letter in 'Python': Current Letter : n
print ('Current Letter :', letter)
• Example:
fruits = ['banana', 'apple', 'mango']
for index in range(len(fruits)):
print ('Current fruit :', fruits[index])
print ("Good bye!“)
Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!
Function range() :
sum = 0
for val in range(1, 6):
sum = sum + val
print(sum)