Lecture 6 - Python
Lecture 6 - Python
Sherina Sally
OUTLINE
• Decision Making Statements
• Iterative Statements
All Rights Reserved
1
DECISION MAKING
• Checks for the validity of a condition
if STATEMENT
Single if condition: Alternative else condition:
if x > 5: if x > 5:
print(“x is greater than 5”) print(“x is greater than 5”)
else:
print(“x is less than 5”)
if x > 5: print(“x is greater than 5”)
All Rights Reserved
2
CONDITIONAL EXPRESSION
• Known as the Ternary Operator
• Useful if there exists only one statement to be executed after each condition: if, elif, else
print(“x is greater than 5”) if x > 5 else print(“x is less than 5”)
3
NESTED if STATEMENT
• Insert an “if” statement within another “if” statement
if x >= 10:
if x <= 15:
pass STATEMENT
• The body of a conditional statement, function, class cannot be empty
if x > 5:
pass
4
ITERATIVE STATEMENTS
• Iterates until a condition is unsatisfactory or iterates over a sequence
• Looping statements:
while LOOP
x = 2
while x < 10:
print(x)
x += 2
All Rights Reserved
2
4
6
8
Department of ICT, Faculty of Technology, University of Colombo All Rights Reserved 10
5
for LOOP
red hat
red scarf
blue hat
blue scarf
Department of ICT, Faculty of Technology, University of Colombo All Rights Reserved 12
6
break STATEMENT
• Terminates from the existing loop and moves to the next statement
for x in ‘programming’:
continue STATEMENT
• Ignores the statements of the current iteration and continues with the next iteration
for x in ‘programming’:
All Rights Reserved
if x == ‘g’:
continue
print(x)
7
range()
incremental
• Iterates over a set number of times start factor
• The starting number, ending number and the incremental factor can be controlled
for x in range(30):
print(x)
Department of ICT, Faculty of Technology, University of Colombo All Rights Reserved 15
for x in range(30):
print(x)
else:
All Rights Reserved
x = 0
while x < 5:
print(x)
else:
print(“x is now 5”)
8
Department of ICT, Faculty of Technology, University of Colombo