In the previous posts, you learned how to set up Python, use the REPL, print messages, and work with basic variables and data types. Now it’s time to make your programs smarter and more dynamic! In this installment, we’ll explore:
- Making decisions in code using if, elif, and else statements
- Looping through sequences and repeating actions with for and while loops
- Applying these concepts in a simple guessing game to practice what you’ve learned
Making Decisions With if, elif, and else
Control flow refers to the order in which your code is executed. By default, Python executes code from top to bottom. However, with conditional statements (if, elif, else), you can tell Python to run certain blocks of code only when specific conditions are met.
Here’s a simple example:
age = 20
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
Because age is 20 (which is greater than or equal to 18), the first block prints "You are an adult.". If age were, say, 15, then Python would print "You are a minor.".
What if you have more than two conditions? That’s where elif comes in:
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: D or F")
Python will check the conditions in order, stopping at the first one that’s true. For a guided walkthrough of if statements, take a look at this video tutorial.
Looping With for and while
Loops let you repeat code multiple times without writing it over and over. Python has two main types of loops: for and while.
Using for Loops
A for loop lets you iterate over a sequence, such as a list or a string:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
This will print each fruit in the list. If you want to iterate over a range of numbers, you can use the range() function:
for i in range(5):
print("Number:", i)
This prints the numbers from 0 to 4. To learn more about for loops, check out this introduction to for loops.
Using while Loops
A while loop repeats as long as a given condition is true. For example:
count = 0
while count < 5:
print("Count is:", count)
count += 1 # Increases count by 1 each iteration
This loop runs until count is no longer less than 5. For more examples, watch this while loop tutorial.
Putting It All Together: A Simple Guessing Game
Let’s combine conditions and loops into a small project. We’ll create a guessing game where the player has to guess a secret number:
secret_number = 7
guess = None
print("Guess the secret number (between 1 and 10)!")
while guess != secret_number:
guess = int(input("Enter your guess: ")) # Get user input and convert to int
if guess < secret_number:
print("Too low! Try again.")
elif guess > secret_number:
print("Too high! Try again.")
else:
print("Congratulations! You guessed the secret number!")
How It Works:
- We initialize secret_number to 7 (you can change this to anything you like).
- We set guess to None initially so the loop can start.
- Inside the loop, we ask the user for their guess and check it against the secret number using if, elif, and else.
- The loop continues until the user guesses the correct number, at which point we print a congratulations message and the loop ends.
Try running this code in your REPL or editor and test it out. If you need a refresher on how to get user input, watch this video on using input() in Python.
Tips for Mastering Control Flow
- Practice writing if statements with multiple conditions. Can you write a program that classifies a person’s age group or a student’s grade level?
- Experiment with for loops by iterating over lists, strings, and ranges. Try printing out all even numbers between 1 and 20, for example.
- Use while loops to create simple interactive programs. Just remember to ensure the loop eventually ends—otherwise, you’ll have an infinite loop!
What’s Next?
Now you’ve got the power to make decisions and repeat actions in your code! The next step is to learn about more complex data structures—like lists, tuples, and dictionaries—that will allow you to store and manage larger sets of data more effectively.
Coming Up: Getting Started with Python for Beginners #4: Collections & Data Structures
- Working with lists, tuples, and dictionaries
- Indexing, slicing, and iterating through collections
- Applying collections in a small project to manage data more easily
If you want to get ahead, consider watching this introduction to Python lists and dictionaries.
Wrapping Up
You’ve just unlocked a major milestone in your Python journey: the ability to control the flow of your program. With if statements and loops, your programs can respond dynamically to different inputs and conditions, making them far more powerful and interesting.
Keep practicing! The more you experiment, the better you’ll understand when and how to use conditions and loops effectively.