Control Flow, Conditional Statements & Loops in Python

Control Flow in Python

  • Control flow refers to the order in which statements and instructions are executed in a program.
  • Python provides various control flow structures that allow you to alter
    • This can be based on certain conditions and perform repetitive tasks.
  • In this article, we'll explore conditional statements and loops

Conditional Statements

  • Conditional statements allow you to execute different blocks of code
    • These are based on specific conditions.
  • In Python, the most commonly used conditional statements are if, elif (short for "else if"), and else.
  • These statements are used to perform different actions depending on the truthfulness of certain conditions.
  • Here's an example:
# Example of conditional statements
age = 18

if age >= 18:
  print("You are an adult.")
elif age >= 13:
  print("You are a teenager.")
else:
  print("You are a child.")

# In this example:
# We check the value of the age variable and print different messages 
# The message we print is based on conditions being met
# The if statement checks if the age is greater than or equal to 18
# The elif statement checks if the age is greater than or equal to 13
# The else statement handles all other cases

Loops

Loops allow you to:

  • Iterate over a sequence of elements
  • Repeat a block of code until a certain condition is met

Python provides two main types of loops:

  • for loops
  • while loops.

For Loops

  • A for loop is used to iterate over a sequence
    • Such as a list, tuple, or string (or any iterable object).
    • Here's an example:
# Example of a for loop
fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
  print(fruit)


# In this example:
# The for loop iterates over each element in the fruits list
# It prints the value each iteration

Introduction to While Loops

In Python, a while loop allows you to repeatedly execute a block of code as long as a certain condition is true. It is useful when you want to repeat a set of actions until a specific condition is met.

Syntax

The syntax of a while loop in Python is as follows:

while condition:
    # Code block
    # to be executed
    # while condition is true

Here's a breakdown of the components:

condition:

  • It is an expression that is evaluated before each iteration.
  • If the condition is true, the code block is executed.
  • If the condition is false, the loop is terminated, and program execution continues with the next statement after the loop.

code block:

  • It is a set of statements that are executed as long as the condition is true.
  • Make sure to indent the code block properly.

Here's an example:

  • Let's say we want to print the numbers from 1 to 5 using a while loop:
while num <= 5:
  print(num)
  num += 1

The output of the code with be:

1
2
3
4
5