Python provides several control structures that allow you to control the flow of your program. The two most common control structures are if/else statements and loops.
1. If/else statements: Used to execute different blocks of code depending on whether a condition is true or false.
python # If/else statement x = 5 if x > 0: print("x is positive") else: print("x is not positive")
In this example, the `if` statement checks whether `x` is greater than 0. If the condition is true, the code in the first block is executed (which prints “x is positive”); otherwise, the code in the second block is executed (which prints “x is not positive”).
2. Loops: Used to execute a block of code repeatedly.
python # While loop x = 0 while x < 5: print(x) x += 1
In this example, the `while` loop executes the code in the block as long as the condition (`x < 5`) is true. The loop increments `x` by 1 each time the block is executed, so the output will be the numbers 0 to 4.
python # For loop fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit)
In this example, the `for` loop iterates over the items in the `fruits` list and assigns each item to the variable `fruit`. The loop then executes the code in the block for each item in the list, so the output will be the words "apple", "banana", and "cherry".
Python also provides several other control structures, such as `elif` statements for handling multiple conditions and nested loops for executing multiple loops within each other. These control structures allow you to write more complex programs that can handle a wide variety of situations.