In computer science, control flow (or flow of control) is the order in which individual statements, instructions or function calls of an imperative program are executed or evaluated. [1]
This page provides syntax for some of the common control flow methods in Python. Each section includes an example to demonstrate the described methods
Use Cases and Syntax
Test if a specified expression is true or false
Short-circuit evaluation
Test if all of the conditions are true x and y
Test if any of the conditions are true x or y
Test if a condition is not true not z
Conditional evaluation
if statement
if-else
if-elif-else
Ternary operator
true_value ifcondition else false_value
Conditional Statements
Input:
x, y, z = 100, 200, 300
print(f"x = {x}, y = {y}, z = {z}")
# Test if x equals 100
if x == 100:
print(f"{x} equals 100")
# Test if y does not equal z
if y != z:
print(f"{y} does not equal {z}")
# Test multiple conditions
if x < y < z:
print(f"{y} is less than {z} and greater than {x}")
# Test multiple conditions using "and"
if x < y and x < z:
print(f"{x} is less than {y} and {z}")
# Test multiple conditions using "or"
if y < x or y < z:
print(f"{y} is less than {x} or {z]")
# if-else statement
if x < 100:
print(f"{x} less than 100")
else:
print(f"{x} is equal to or greater than 100")
# Same logic as above but using the ternary operator
print(f"{x} less than 100 again" if x < 100 else f"{x} equal to or greater than 100 again")
# if-elif-else statement
if y < 100:
print(f"{y} is less than 100")
elif y < 200:
print(f"{y} is less than 200")
elif y < 300:
print(f"{y} is less than 300")
else:
print(f"{y} is greater than or equal to 300")
Output:
x = 100, y = 200, z = 300
100 equals 100
200 does not equal 300
200 is less than 300 and greater than 100
100 is less than 200 and 300
200 is less than 100 or 300
100 is equal to or greater than 100
100 equal to or greater than 100 again
200 is less than 300
Loops
Repeat a block of code a specified number of times or until some condition is met
while loop
for loop
Use break to terminate loop
Input:
# Demonstrates use of loops
i = 1
# while loop for incrementing i by 1 from 1 to 3
while i <= 3:
print(f"while: {i}")
i +=1
# for loop
for j in range(1,4):
print(f"for: {j}")
for j in range(1,4):
print(f"for again: {j}")
# nested for loop
for j in range(1,4):
for k in range(1,4):
print(f"nested for: {j} * {k} = {j*k}")