Control flow
Make your programs smart with decisions
Welcome! Today, we're going to dive into the exciting world of control flow in Python. This is where your programs start to get really clever!
Making programs think
Imagine giving instructions to a friend. You might say, "If it's raining, take an umbrella." Or, "When you finish your homework, you can play outside." Programs work in a similar way. They need to make decisions.
Control flow is all about telling your computer how to make those decisions. It lets your code react to different situations. This makes your programs much more powerful and flexible.
What you'll learn
- How to use
if,elif, andelsestatements to create conditional branches. - Understanding logical operators like
and,or, andnot. - Making your programs repeat actions with
forloops. - Repeating actions based on conditions with
whileloops. - Controlling loops with
break,continue, andpass.
Real-world examples
You encounter control flow every day! Here are a few examples:
- Websites: If you enter the correct password, you log in. Else, you see an error message.
- Games: If your health points reach zero, the game ends. While there are enemies left, keep fighting.
- Smartphones: If your battery is low, display a warning. If you press a button, open an app.
Prerequisites
Before we dive in, make sure you're comfortable with these basics:
- Basic Python syntax (how to write simple lines of code).
- Variables (storing information like numbers or text).
- Data types (like
intfor numbers,strfor text,boolfor True/False).
Let's begin!
Are you ready to make your Python programs smarter? Let's start with the most common decision-making tool: the if statement!
temperature = 25
if temperature > 30:
print("It's a hot day!")
print("Done checking temperature.")In this example, print("It's a hot day!") only runs if the temperature is greater than 30. Notice the colon (:) and the indentation – they are super important!
Practice
Try these exercises to lock in what you just learned.