Control Flow Statements
Control Flow Statements
Control Flow Statements
1. Conditional statements
2. Iterative statements.
3. Transfer statements
Conditional statements
1. if statement
2. if-else
3. if-elif-else
4. nested if-else
Iterative statements
1. for loop
2. while loop
Transfer statements
1. break statement
2. continue statement
3. pass statements
If statement in Python
If the condition is True, then the True block of code will be executed,
and if the condition is False, then the block of code is skipped, and
The controller moves to the next line
if condition:
statement 1
statement 2
statement n
Python if statements
Let’s see the example of the if statement. In this example, we will
calculate the square of a number if it greater than 5
Example
number = 6
if number > 5:
# Calculate square
print(number * number)
print('Next lines of code')
Output
36
Next lines of code
If – else statement
The if-else statement checks the condition and executes the if block of
code when the condition is True, and if the condition is False, it will
execute the else block of code.
if condition:
statement 1
else:
statement 2
if password == "PYnative@#29":
print("Correct password")
else:
print("Incorrect Password")
Output 1:
Correct password
Output 2:
Incorrect Password
elif condition-3:
stetement 3
...
else:
statement
Example
def user_check(choice):
if choice == 1:
print("Admin")
elif choice == 2:
print("Editor")
elif choice == 3:
print("Guest")
else:
print("Wrong entry")
user_check(1)
user_check(2)
user_check(3)
user_check(4)
Output:
Admin
Editor
Guest
Wrong entry
if conditon_outer:
if condition_inner:
statement of inner if
else:
statement of inner else:
statement ot outer if
else:
Outer else
statement outside if block
Output 1:
56 is greater than 15
Output 2:
29 is smaller than 78
Example
number = 56
Example
x=1
while x <= 5: print(x,end=" "); x = x+1
Output
12345
Output
1
10
Syntax of while-loop
while condition :
body of while loop
num = 10
sum = 0
i=1
while i <= num:
sum = sum + i
i=i+1
print("Sum of first 10 number is:", sum)
Output
The break statement is used inside the loop to exit out of the loop. It
is useful when we want to terminate the loop as soon as the condition
is fulfilled instead of doing the remaining iterations. It reduces
execution time. Whenever the controller encountered a break
statement, it comes out of that loop immediately
Let’s see how to break a for a loop when we found a number greater
than 5.
Output
4
5
stop processing.
Let’s see how to skip a for a loop iteration if the number is 5 and
continue executing the body of the loop for other numbers.
Output
7
Pass statement in Python
Example
Output