Conditional statements and loops allow you to control the flow of execution in your Python programs based on certain conditions.
Conditional Statements
Conditional statements, such as if
, elif
, and else
, are used to execute code blocks based on the evaluation of one or more conditions. Here’s an example:
x = 10
if x > 0:
print("Positive number")
elif x < 0:
print("Negative number")
else:
print("Zero")
In this example, if the value of x
is greater than 0, the first print()
statement will be executed. If x
is less than 0, the second print()
statement will be executed. Otherwise, the else
block will be executed.
Loops
Loops allow you to repeat a block of code multiple times. Python supports two types of loops: for
loops and while
loops.
For Loop
The for
loop is used to iterate over a sequence (such as a list, tuple, or string) or other iterable objects. Here’s an example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
This will output each fruit in the list fruits
.
While Loop
The while
loop is used to execute a block of code repeatedly as long as a specified condition is true. Here’s an example:
i = 0
while i < 5:
print(i)
i += 1
This will print the numbers from 0 to 4.
Understanding control flow statements is essential for writing dynamic and interactive Python programs. In the next chapter, we’ll explore functions and modules, which allow you to organize and reuse code more effectively.