What are control flow structures in Python? Describe the if-else and for loop structures with examples.
In Python, control flow structures are used to determine the execution order of statements or blocks of code based on certain conditions. They allow the program to make decisions and repeat certain actions, enabling the creation of dynamic and flexible programs. Two commonly used control flow structures in Python are the if-else statement and the for loop. Let's delve into each of these structures in detail and provide examples:
1. if-else Statement:
The if-else statement allows the program to execute different blocks of code based on a specified condition. It follows the syntax:
```
python`if condition:
# code block executed if condition is True
else:
# code block executed if condition is False`
```
Here's an example that demonstrates the usage of the if-else statement:
```
python`x = 10
if x > 0:
print("x is positive")
else:
print("x is non-positive")`
```
In this example, if the condition `x > 0` is True, the program will execute the code block under the `if` statement and print "x is positive". Otherwise, it will execute the code block under the `else` statement and print "x is non-positive".
2. for Loop:
The for loop allows the program to iterate over a sequence of elements, such as a list, tuple, string, or range, and perform a certain action for each element. It follows the syntax:
```
python`for item in sequence:
# code block executed for each item in the sequence`
```
Here's an example that demonstrates the usage of the for loop:
```
python`fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)`
```
In this example, the for loop iterates over each element in the `fruits` list and prints it. The output will be:
```
`apple
banana
orange`
```
The for loop can also be used with the `range()` function to iterate over a sequence of numbers. Here's an example:
```
python`for i in range(5):
print(i)`
```
This code will print numbers from 0 to 4, as the `range(5)` generates a sequence of numbers from 0 to 4.
Furthermore, the for loop can be combined with the `else` statement to execute a code block once the loop has completed all iterations, except when the loop is terminated by a `break` statement.
Control flow structures like the if-else statement and the for loop are essential in programming as they provide the means to make decisions and perform repetitive tasks based on specific conditions. Mastering these structures allows developers to create more dynamic and flexible programs.