**Python: Control Flow
This lesson introduces control flow in Python, essential for creating dynamic and interactive programs. You'll learn how to use conditional statements (if, elif, else) to make decisions and loops (for, while) to repeat tasks, controlling the order in which your code executes.
Learning Objectives
- Understand and use `if`, `elif`, and `else` statements for conditional logic.
- Implement `for` loops to iterate through sequences like lists and strings.
- Employ `while` loops to repeat code blocks based on a condition.
- Learn to use `break` and `continue` statements within loops to control execution flow.
Text-to-Speech
Listen to the lesson content
Lesson Content
Conditional Statements: Making Decisions
Conditional statements allow your program to make decisions based on certain conditions. The if statement evaluates a condition, and if it's true, the code block indented under the if statement is executed.
age = 20
if age >= 18:
print("You are an adult.")
elif (else if) allows you to check for additional conditions if the previous if or elif conditions were false. The else statement provides a default code block to execute if none of the preceding conditions are true.
score = 75
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: D")
For Loops: Iterating Through Sequences
for loops are used to iterate over a sequence (such as a list, tuple, string, or range). This means you can execute a block of code for each item in the sequence.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
You can also use for loops with the range() function to iterate a specific number of times:
for i in range(5):
print(i) # Prints 0, 1, 2, 3, 4
While Loops: Repeating Until a Condition is Met
while loops execute a block of code as long as a specified condition is true. Be careful to ensure your loop condition eventually becomes false to avoid infinite loops.
count = 0
while count < 3:
print("Count:", count)
count += 1
Inside loops, break stops the loop entirely, and continue skips the current iteration and goes to the next one.
for i in range(10):
if i == 5:
break # Exit the loop when i is 5
print(i)
for i in range(10):
if i % 2 == 0:
continue # Skip even numbers
print(i) # Prints only odd numbers
Deep Dive
Explore advanced insights, examples, and bonus exercises to deepen understanding.
Day 3: Data Scientist - Python Control Flow - Extended Learning
Welcome to Day 3 of your Python journey! You've grasped the fundamentals of control flow. Now, let's deepen your understanding and explore some powerful techniques to make your code even more dynamic and efficient.
Deep Dive: Nested Control Flow and the Power of Boolean Logic
You've seen how to use if, elif, and else for decision-making and for and while loops for repetition. But what happens when you combine them? This is where nested control flow comes into play. You can put loops inside of loops, or if statements inside of loops (or vice versa!). This allows you to create more complex and nuanced program logic.
Another crucial aspect is Boolean logic. Python uses and, or, and not to combine multiple conditions. Understanding how these operators work is essential for writing robust conditional statements. Remember the order of operations: Parentheses, Not, And, Or. This helps ensure your conditions evaluate correctly.
Example of Nested Control Flow:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for number in numbers:
if number % 2 == 0: # Check if even
print(f"{number} is even.")
if number > 5: # Nested condition
print(f"{number} is even and greater than 5.")
else:
print(f"{number} is odd.")
Example using Boolean Logic:
age = 25
has_license = True
is_student = False
if age >= 18 and has_license:
print("You can drive.")
elif is_student or age < 16:
print("You are not eligible to drive yet.")
else:
print("Check your eligibility.")
Bonus Exercises
Exercise 1: Age Checker Refined
Write a program that takes a user's age as input and determines their eligibility for different activities. Use nested if statements and boolean operators to check:
- If they are eligible to vote (18+)
- If they are eligible to drink alcohol (21+ in many places)
- If they can get a senior discount (65+)
Exercise 2: Prime Number Finder
Create a program that identifies and prints all prime numbers within a given range (e.g., from 2 to 50). Use a nested for loop. The outer loop iterates through the numbers, and the inner loop checks if the number is divisible by any number smaller than itself.
Real-World Connections
Control flow is fundamental in almost every data science application:
- Data Cleaning: Cleaning your data often involves using
ifstatements to handle missing values (e.g., imputing values or removing rows) or filtering data based on certain criteria. - Data Analysis: Loops are used to iterate through datasets, calculating statistics, and performing analysis on each data point or subset. For example, calculating the average of a column in a dataset.
- Machine Learning: Control flow is essential in model training, for iterating through training data in batches, and in model evaluation, for testing the model's accuracy on the test data.
- Automation: Data scientists frequently automate repetitive tasks using loops and conditional statements (e.g., web scraping, report generation).
Challenge Yourself
Create a simple game, such as "Guess the Number." The program should randomly generate a number, and the user has a limited number of attempts to guess it. Use a while loop to control the game flow, if statements to compare the user's guess to the random number, and break or continue to control the game flow and implement hints.
Further Learning
- List Comprehensions: Learn to create concise and efficient loops for creating lists. This combines loops and conditionals in a single line.
- Functions: Start learning how to define and use functions. Functions are a key component in organizing your code and making it reusable.
- Error Handling (try-except blocks): Explore how to handle potential errors in your code using
try-exceptblocks. This makes your programs more robust. - Explore Python's Documentation: The official Python documentation is an invaluable resource.
Interactive Exercises
Conditional Coffee Prices
Write a program that takes the user's order (e.g., "latte", "espresso", "tea") as input and then, using `if`/`elif`/`else` statements, prints the price of the drink. Assume: * Latte costs $4. * Espresso costs $3. * Tea costs $2. * Any other order is "Not available."
Looping Through Numbers
Create a `for` loop that iterates through the numbers from 1 to 10 (inclusive) and prints each number, along with whether it's even or odd.
Guessing Game with While Loop
Write a number-guessing game. Generate a random number between 1 and 10. Use a `while` loop to repeatedly prompt the user to guess the number. Provide feedback to the user on whether their guess is too high or too low. End the loop when the user guesses correctly or runs out of attempts (e.g., 3 attempts).
Loop Control Challenge
Create a `for` loop that iterates through a list of numbers: `[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]`. Within the loop, use `continue` to skip even numbers and `break` when the number is greater than 7. Print only the odd numbers less than or equal to 7.
Practical Application
Develop a program that simulates a simple quiz. The program should present questions to the user and track their score. Use if/elif/else statements to check the user's answers and for loops to iterate through the questions. You can expand this by using while loop if you want to implement different game modes or add retry logic.
Key Takeaways
Conditional statements (`if`, `elif`, `else`) enable decision-making in your programs.
`for` loops are ideal for iterating over sequences.
`while` loops are used to repeat code as long as a condition holds true.
`break` and `continue` provide control over loop execution.
Next Steps
Review data types and operators from the previous lessons.
Prepare to learn about functions in the next session, focusing on how to organize and reuse code.
Your Progress is Being Saved!
We're automatically tracking your progress. Sign up for free to keep your learning paths forever and unlock advanced features like detailed analytics and personalized recommendations.
Extended Learning Content
Extended Resources
Extended Resources
Additional learning materials and resources will be available here in future updates.