Control
Control
syntax
if <conditional expression> :
The code block to be executed
if the condition is True
Example code in if statement
a = 33 a = 20
if a>0:
b = 200 print("Its Positive")
if b > a: Output:
print("b is greater than a") Its Positive
num = float(input("Enter a number that you want to check it is divisible by 2 or not: "))
if num % 2 == 0:
print(num, " is divisible by 2.")
if num % 2 != 0:
print(num, " is not divisible by 2.")
If-else
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false
Example program:
• number = int(input("Enter a number: ")) # User input
• if number % 2 == 0:
• print(f"{number} is an even number.")
• else:
• print(f"{number} is not an even number.")
Odd or even
• number = int(input("Enter a number: ")) # User input
• if number % 2 == 0:
• print(“even number.")
• else:
• print(“odd number.")
If-elif-else
if (condition):
# Executes this block if
# condition is true
Elif(condition)
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false
example
number = int(input("Enter a number: ")) # User input
if number == 0:
print("The number is zero.")
elif number % 2 == 0:
print(“even number.")
else:
print(“odd number.")
Nested if
if
boolean_expressi
on1: statement(s)
if
boolean_expressi
on2: statement(s)
# Get user input for grade and attendance
grade = int(input("Enter your grade: "))
attendance = int(input("Enter your attendance percentage: "))
15
WHILE LOOP
A while loop is a control flow structure in Python
that allows a block of code to be executed
repeatedly as long as a specified condition is true.
while condition:
# Code block to be executed
SYNTAX
17
FLOWCHART OF WHILE LOOP
Enter the while loop
False
Expression
True
Statement(s)
Exit from the
While loop
18
1) Print i as long as i is less than 6?
i = 1 1
while i < 6: 2
print(i) 3
i += 1 4
5
i = 1
while i < 6: 1
print(i) 2
if i == 3: 3
break
i += 1
The continue Statement
With the continue statement we can stop the current iteration, and
continue with the next:
Hello
while True:
Hello
print("Hello")
Hello
.
.
.
.
FOR LOOP
The for loop iterates over each item in the
specified sequence, executing the code block for
each iteration.
SYNTAX
21
FLOWCHART OF FOR LOOP
For Each Item In Sequence
True
Expression
False
Statement(s)
Exit from the
FOR loop
22
1)Example: Printing elements of a list
x= "python" p
for ch in x: y
print(ch) t
h
o
n
3)Printing elements by using range() function and for loop