Python Control Flow
Control flow is the order in which statements are executed in a program. In this tutorial, we'll learn how Python provides structures that let you control the flow of your code, allowing you to make decisions, repeat actions, and skip certain code blocks when needed.
Introduction to Control Flow
Control flow refers to the order in which individual statements, instructions, or function calls are executed in a program. By default, Python executes code sequentially from top to bottom. However, with control flow structures, you can:
- Execute code only if certain conditions are met
- Skip sections of code
- Repeat sections of code
- Jump to different parts of your program
These capabilities are fundamental to creating dynamic and responsive programs.
Conditional Statements
The if
Statement
The if
statement allows you to execute a block of code only if a certain condition is true.
temperature = 25
if temperature > 30:
print("It's hot outside!")
print("Program continues...")
Output:
Program continues...
In this example, since the temperature is not greater than 30, the message "It's hot outside!" is not printed.
if-else
Statement
The if-else
statement provides an alternative execution path when the condition is false.
temperature = 25
if temperature > 30:
print("It's hot outside!")
else:
print("The temperature is moderate.")
print("Program continues...")
Output:
The temperature is moderate.
Program continues...
if-elif-else
Statement
For multiple conditions, use the elif
(short for "else if") statement.
temperature = 25
if temperature > 30:
print("It's hot outside!")
elif temperature > 20:
print("The weather is pleasant.")
elif temperature > 10:
print("It's a bit cool.")
else:
print("It's cold outside!")
Output:
The weather is pleasant.
Nested Conditionals
You can place conditional statements inside other conditional statements.
temperature = 25
is_raining = True
if temperature > 20:
print("It's warm outside.")
if is_raining:
print("But bring an umbrella!")
else:
print("Enjoy the sunshine!")
else:
print("It's cold outside.")
Output:
It's warm outside.
But bring an umbrella!
Loops
Loops allow you to repeat a block of code multiple times.
for
Loops
The for
loop is used to iterate over a sequence (like a list, tuple, dictionary, set, or string).
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like {fruit}s")
Output:
I like apples
I like bananas
I like cherrys
The range()
Function
The range()
function generates a sequence of numbers that you can iterate over.
# Print numbers from 0 to 4
for i in range(5):
print(i)
Output:
0
1
2
3
4
# Print numbers from 1 to 5
for i in range(1, 6):
print(i)
Output:
1
2
3
4
5
# Print even numbers from 2 to 10
for i in range(2, 11, 2):
print(i)
Output:
2
4
6
8
10
while
Loops
The while
loop repeats a block of code as long as a condition is true.
count = 0
while count < 5:
print(f"Count is: {count}")
count += 1
Output:
Count is: 0
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Loop Control Statements
Loop control statements change the execution from its normal sequence.
break
Statement
The break
statement terminates the loop containing it.
for i in range(10):
if i == 5:
print("Breaking the loop")
break
print(i)
Output:
0
1
2
3
4
Breaking the loop
continue
Statement
The continue
statement skips the current iteration and continues with the next one.
for i in range(10):
if i % 2 == 0: # Skip even numbers
continue
print(i)
Output:
1
3
5
7
9
else
Clause with Loops
Python allows you to use an else
clause with both for
and while
loops. The else
block is executed when the loop condition becomes false.
for i in range(5):
print(i)
else:
print("Loop completed successfully!")
Output:
0
1
2
3
4
Loop completed successfully!
The else
clause is not executed if the loop is terminated by a break
statement.
for i in range(5):
if i == 3:
break
print(i)
else:
print("Loop completed successfully!") # This won't be executed
Output:
0
1
2
Practical Examples
Example 1: Finding Elements in a List
Let's use control flow to find specific elements in a list:
numbers = [10, 25, 33, 42, 57, 68, 79, 84, 95]
even_numbers = []
odd_numbers = []
for num in numbers:
if num % 2 == 0:
even_numbers.append(num)
else:
odd_numbers.append(num)
print(f"Even numbers: {even_numbers}")
print(f"Odd numbers: {odd_numbers}")
Output:
Even numbers: [10, 42, 68, 84]
Odd numbers: [25, 33, 57, 79, 95]
Example 2: Simple Number Guessing Game
import random
# Generate a random number between 1 and 10
secret_number = random.randint(1, 10)
attempts = 0
max_attempts = 3
print("Welcome to the number guessing game!")
print(f"I'm thinking of a number between 1 and 10. You have {max_attempts} attempts.")
while attempts < max_attempts:
try:
guess = int(input("Enter your guess: "))
attempts += 1
if guess < secret_number:
print("Too low!")
elif guess > secret_number:
print("Too high!")
else:
print(f"Congratulations! You guessed the number {secret_number} correctly!")
break
except ValueError:
print("Please enter a valid number.")
remaining = max_attempts - attempts
if remaining > 0:
print(f"You have {remaining} attempts left.")
else:
print(f"Sorry, you've used all your attempts. The secret number was {secret_number}.")
Example 3: Data Processing for Pandas
This example shows how control flow can help prepare data for analysis with Pandas:
# Sample data (imagine this is from a CSV file)
sales_data = [
{"date": "2023-01-01", "product": "A", "units": 50, "price": 10},
{"date": "2023-01-02", "product": "B", "units": 30, "price": 15},
{"date": "2023-01-03", "product": "A", "units": 25, "price": 10},
{"date": "2023-01-04", "product": "C", "units": 10, "price": 25},
{"date": "2023-01-05", "product": "B", "units": 35, "price": 15}
]
# Calculate total revenue for each product
product_revenue = {}
for sale in sales_data:
product = sale["product"]
revenue = sale["units"] * sale["price"]
if product in product_revenue:
product_revenue[product] += revenue
else:
product_revenue[product] = revenue
# Find the best-selling product
best_seller = None
max_revenue = 0
for product, revenue in product_revenue.items():
print(f"Product {product} generated ${revenue} in revenue")
if revenue > max_revenue:
max_revenue = revenue
best_seller = product
print(f"\nThe best-selling product is {best_seller} with ${max_revenue} in revenue")
Output:
Product A generated $750 in revenue
Product B generated $975 in revenue
Product C generated $250 in revenue
The best-selling product is B with $975 in revenue
Summary
Control flow is a fundamental concept in Python programming. In this tutorial, you learned:
- How to use
if
,elif
, andelse
statements to make decisions in your code - How to use
for
loops to iterate over sequences - How to use
while
loops for condition-based iteration - How to control loops with
break
andcontinue
statements - How to use the
else
clause with loops
Understanding control flow is essential for working with Pandas, as you'll often need to:
- Filter data based on conditions
- Iterate through data frames
- Perform different operations based on data values
- Process and transform data
Exercises
-
Write a program that prints all numbers from 1 to 100, but for multiples of 3, print "Fizz" instead of the number, for multiples of 5, print "Buzz", and for multiples of both 3 and 5, print "FizzBuzz".
-
Create a simple calculator program that takes two numbers and an operator (+, -, *, /) as input and performs the corresponding operation.
-
Write a program that takes a list of temperatures in Celsius and converts them to Fahrenheit using a for loop.
-
Create a program that checks if a given year is a leap year.
-
Write a program that removes all duplicate items from a list while preserving the original order.
Additional Resources
- Python Documentation on Control Flow
- Real Python: Python Conditional Statements and Loops
- W3Schools Python Conditions and Loops
- Python for Data Science Handbook
Understanding control flow is crucial for your journey with Python and Pandas. These concepts will form the foundation of how you'll structure your data analysis code.
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)