KEMBAR78
Python programming : Control statements | PDF
Control Statements
Team Emertxe
Single Control Statements
If Statements
If-Else
 Syntax
if condition:
statements
else:
statements

Example
if num % 2:
print("ODD")
else:
print("EVEN")
If Statements
If-Elif-Else
 Syntax
if condition1:
statements
elif condition2:
statements
else
statements

Example
if num == 1:
print("You entered 1")
elif num == 2:
print("You entered 2")
else:
print("You entered 3")
Multiple Control Statements
Multiple Statements
While
 Syntax
while condition:
statements

Example
i = 1
while i <= 10:
print(i)
i = i + 1
Multiple Statements
For
 Syntax
for var in sequence:
statements

Example-v1.1
str = "Hello"
for ch in str:
print(ch, end='')

Example-v1.2
n = len(str)
for i in range(n):
print(str[i])
Else Suite
Multiple Statements
For with Else suite
 Syntax
for var in sequence:
statement / statements
else:
statement / statements

Example
for i in range(5):
print(i)
else:
print("Over")
Multiple Statements
While with Else suite
 Syntax
while condition:
statement / statements
else:
statement / statements

Example
i = 0
while i < 5
print(i)
i += 1
else:
print("Over")
While searching an elemnt in the sequence is not found,
else will be the best option to display the item not found
Misc Statements
Misc Statements
Break
 Example
x = 10
while x >= 1:
print("x = ", x)
x -= 1
if x == 5:
break
Misc Statements
Continue
 Example
x = 10
while x >= 1:
if x == 5:
x -= 1
continue
print("x = ", x)
x -= 1
Misc Statements
Pass
 Example-1
x = 0
while x < 10:
x += 1
if x == 5:
pass
print(x)
Misc Statements
Pass
 Example-2: Program to retrieve only the negative numbers from the list
num = [1, 2, 3, -4, -5, -6, 7, 8]
for i in num:
if (i > 0):
pass
else:
print(i)
Pass does nothing
Misc Statements
Assert
 Syntax:
assert expression, message
 Example-1
num = int(input("Enter the number greater than zero: "))
assert num > 0, "Wrong input"
print("Num: ", num)
Misc Statements
Assert: Try Except
 Example-1
num = int(input("Enter the number greater than zero: "))
try:
assert num > 0, "Wrong input"
print("Num: ", num)
except AssertionError:
print("You entered wrong input")
print("Enter positive number")
Misc Statements
Return
 Example-1: To add two numbers & return the result
def sum(a, b):
return a + b
res = sum(5, 10)
print(res)
THANK YOU

Python programming : Control statements