1 min read

Python Control Flow

Control flow statements in Python allow you to control the order in which the code is executed.

if Statements

The if statement is used to execute a block of code only if a certain condition is true.

x = 10
if x > 5:
  print("x is greater than 5")

if...else Statements

The if...else statement is used to execute one block of code if a condition is true, and another block of code if it is false.

x = 10
if x > 5:
  print("x is greater than 5")
else:
  print("x is not greater than 5")

if...elif...else Statements

The if...elif...else statement is used to check for multiple conditions.

x = 10
if x > 10:
  print("x is greater than 10")
elif x < 10:
  print("x is less than 10")
else:
  print("x is equal to 10")

for Loops

The for loop is used to iterate over a sequence (like a list, tuple, or string).

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
  print(fruit)

while Loops

The while loop is used to execute a block of code as long as a certain condition is true.

i = 1
while i < 6:
  print(i)
  i += 1