Python Programming for Applied Projects
Control Flow
Making Decisions
So far, your Python scripts have run straight from top to bottom. But that's not how interesting programs work. Just like you decide to bring an umbrella if it's raining, programs need to make decisions based on certain conditions. This is called control flow.
The most basic way to make a decision in Python is with an if statement. It checks if a condition is true. If it is, the code inside the if block runs.
weather = "sunny"
if weather == "sunny":
# This code runs because the condition is true
print("Don't forget your sunglasses!")
Notice the structure: the if keyword, followed by the condition (weather == "sunny"), and a colon. The line of code to be executed is indented. This indentation is crucial in Python; it tells the interpreter what code belongs to the if statement.
What if the weather isn't sunny? We can add an else statement to handle the alternative case. The code inside the else block runs only when the if condition is false.
weather = "rainy"
if weather == "sunny":
print("Don't forget your sunglasses!")
else:
# This code runs because the 'if' condition is false
print("You might need an umbrella.")
Sometimes you have more than two possibilities. For this, you can use elif, which is short for "else if." It lets you check for multiple conditions in sequence. Python checks them one by one until it finds one that's true and runs its code block. If none are true, the final else block runs.
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
# This runs because score is not >= 90, but is >= 80
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: D or F")
Repeating Actions
Decision-making is powerful, but what if you need to do the same thing over and over? You wouldn't want to write print("Hello!") a hundred times. This is where loops come in. They let you execute a block of code repeatedly.
The for loop is perfect for when you want to iterate over a sequence, like the items in a list or a range of numbers.
# Let's print numbers from 1 to 5
# range(1, 6) generates numbers starting at 1 up to (but not including) 6
for number in range(1, 6):
print(number)
In this example, the for loop assigns each number from the range to the number variable one at a time and then runs the indented print() statement for each one.
The other main type of loop is the while loop. Instead of running a set number of times, a while loop keeps running as long as its condition is true. It's useful when you don't know in advance how many times you'll need to loop.
count = 1
while count <= 5:
print(count)
count = count + 1 # Crucial step! This eventually makes the condition false.
Be careful with
whileloops! If you forget to include a line that changes the condition (likecount = count + 1), the condition will always be true, and your program will be stuck in an infinite loop.
Controlling Loops
Sometimes you need more precise control over how a loop behaves. Python gives you special statements to manage the loop from within its code block.
The break statement immediately exits the current loop, regardless of the loop's condition. The program then continues with the code right after the loop.
# Find the first number divisible by 7
for number in range(1, 20):
if number % 7 == 0:
print(f"Found it! The first number is {number}")
break # Exit the loop immediately
print(f"Checking {number}...")
The continue statement is different. It doesn't exit the whole loop. Instead, it just skips the rest of the code in the current iteration and jumps to the beginning of the next one.
# Print only the odd numbers from 1 to 10
for number in range(1, 11):
if number % 2 == 0: # If the number is even...
continue # ...skip the print statement and go to the next number
print(number)
Finally, there's the pass statement. It's a bit odd because it does absolutely nothing. It acts as a placeholder. You might use it when you're sketching out your code and need to write a syntactically valid if statement or loop that you plan to fill in later.
for number in range(5):
if number == 3:
# TODO: Add logic for when number is 3
pass # Do nothing for now
else:
print(number)
Now let's test your understanding of these control flow concepts.
What will the following Python code print?
temperature = 25
if temperature > 30:
print("Hot")
elif temperature > 20:
print("Nice")
else:
print("Cold")
A while loop continues to execute as long as its condition evaluates to True.
With conditionals and loops, you can now write programs that are much more dynamic and intelligent, reacting to data and automating repetitive work.