Python Control Flow Statements: Understanding If/Else, While, and For Loops
Control flow statements are an essential part of any programming language, including Python. These statements allow you to control the flow of execution in your code based on certain conditions or criteria. In this article, we’ll explore three of the most commonly used control flow statements in Python: if/else
statements, while
loops, and for
loops.
If/else statements
An if/else
statement is used to execute a block of code if a certain condition is true, and another block of code if the condition is false. The basic syntax of an if/else
statement in Python is as follows:
if condition:
# execute code if condition is true
else:
# execute code if condition is false
Here’s an example of an if/else
statement that checks if a number is positive or negative:
num = -5
if num >= 0:
print("The number is positive")
else:
print("The number is negative")
In this example, the condition num >= 0
is checked, and the appropriate message is printed based on whether the condition is true or false.
While loops
A while
loop is used to execute a block of code repeatedly as long as a certain condition is true. The basic syntax of a while
loop in Python is as follows:
while condition:
# execute code while condition is true
Here’s an example of a while
loop that counts down from 10 to 1:
countdown = 10
while countdown > 0:
print(countdown)
countdown -= 1
In this example, the condition countdown > 0
is checked, and the loop continues to execute as long as the countdown is greater than 0. The countdown
variable is decremented by 1 on each iteration of the loop.
For loops
A for
loop is used to iterate over a sequence of values, such as a list or tuple, and execute a block of code for each value in the sequence. The basic syntax of a for
loop in Python is as follows:
for variable in sequence:
# execute code for each value in sequence
Here’s an example of a for
loop that iterates over a list of names and prints each name:
names = ["Alice", "Bob", "Charlie"]
for name in names:
print(name)
In this example, the for
loop iterates over each element in the names
list and assigns the value to the name
variable. The print
statement is then executed for each value in the list.
Conclusion
Control flow statements such as if/else
statements, while
loops, and for
loops are essential building blocks of any Python program. They allow you to control the flow of execution based on certain conditions or criteria, and to iterate over sequences of values to perform specific tasks. By mastering these control flow statements, you can write more powerful and flexible Python programs that can accomplish a wide range of tasks.