PYTHON Tutorial

Control Flow

Control flow refers to the order in which statements in a Python program are executed. It allows you to alter the flow of execution based on conditions or loops.

Key Concepts:

  • Python if statement: Evaluates a condition and executes a block of code if the condition is true.
if condition:
    # Code to execute if condition is true
  • Python for loop: Iterates over a sequence of elements, executing a block of code for each element.
for element in sequence:
    # Code to execute for each element
  • Python while loop: Continues executing a block of code while a condition remains true.
while condition:
    # Code to execute while condition is true
  • Python break: Terminates the execution of a loop early.
  • Python continue: Skips the remaining code within the current loop iteration and proceeds to the next iteration.

Example: Basics of Control Flow

# Check if a number is greater than 5
if number > 5:
    print("Number is greater than 5")

# Loop through a list of numbers
for number in [1, 2, 3, 4, 5]:
    print(number)

# Continue looping while number is less than 10
while number < 10:
    number += 1
    print(number)