Python control flow refers to the order in which statements in a Python program are executed. It allows you to make decisions, loop through code, and define the flow of your program. There are several control flow constructs in Python, including conditional statements, loops, and function calls. In this explanation, I'll cover some of the most fundamental aspects of Python control flow with examples.
1. Conditional Statements:
age = 18
if age >= 18:
print("You are an adult.")
else:
print("You are not an adult.")
Conditional statements allow you to make decisions in your code based on certain conditions. The most common conditional statements in Python are if
, elif
(else if), and else
.
2. Loops:
a. for Loop:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
for
loops allow you to repeat a block of code multiple times. In this for
loop, we iterate over each element in the fruits
list and print each fruit.
b. while Loop:
count = 0
while count < 5:
print("Count: ", count)
count += 1
while
loops allow you to execute the code inside the loop as long as the condition count < 5
is true.
3. Functions:
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
Functions are blocks of reusable code that allow you to organize your code and make it more modular. They can also be used to control the flow of your program by allowing you to call a specific block of code when needed.
In this example, we define a function greet
that takes a parameter name
and prints a greeting message. We then call the function with the argument "Alice."
These are the fundamental control flow constructs in Python. You can combine them to create more complex and flexible program logic. Additionally, Python provides other control flow tools like break
, continue
, and more for more specialized cases.