Introduction to Control Flows
What are Control Flows?
Control flows are programming structures that control the order in which your code runs. Without control flows, your program would just run once from top to bottom, line by line.
With control flows, your program can:
- Make decisions based on conditions
- Repeat actions multiple times
- Skip certain parts of code based on conditions
E.g.
age = int(input("How old are you? "))
if age >= 18:
print("You can vote!")
else:
print("You're too young to vote.")
Here, the program makes a decision based on the user’s age.
- If the user entered 15, the output would be “You’re too young to vote.”
- If the user entered 35, the output would be “You can vote!”
Control flow syntax and code blocks
Conditions
A condition is a statement that can be either True or False. We use comparison operators to create conditions.
Examples:
age >= 18(True if age is 18 or more)score == 100(True if score equals exactly 100)password != "admin"(True if password is not “admin”)
Remember that the = symbol assigns a value, while == compares values.
Code Blocks
A code block is a group of statements that belong together. In Python, code blocks are created using indentation (four spaces are recommended, but some people use two spaces or a tab at the beginning of lines).
if temperature > 30:
print("It's hot!") # Indented
print("Wear light clothes!") # Also indented
if wind > 60:
print("It's windy!") # Indented again and only reached if temperature > 30
print("Have a great day!") # Not indented
Note that this is different from:
if temperature > 30:
print("It's hot!") # Indented
print("Wear light clothes!") # Also indented
if wind > 60:
print("It's windy!") # Indented again but always reached regardless of temperature
print("Have a great day!") # Not indented
Nested Control Flows
Control flows are most powerful when you put them inside each other, as specified by the different levels of indentation.
for day in range(1, 8):
print(f"Day {day}:")
if day <= 5:
print(" It's a weekday - time to work!")
else:
print(" It's the weekend - time to relax!")
if day == 7:
print(" Tomorrow is Monday!")
if Statements
The if statement lets your program make decisions.
Basic if statement
The indented code is only executed if the condition tests true
score = 85
if score >= 60:
print("You passed!") # Only executed if score is greater or equal to 60
This gives the output
You passed!
While the code
score = 35
if score >= 60:
print("You passed!") # Only executed if score is greater or equal to 60
gives no output since score is less than 60.
if-else statement
Choose between two options.
weather = "sunny"
if weather == "rainy":
print("Take an umbrella!")
else:
print("Enjoy the nice weather!")
This gives the output
Enjoy the nice weather!
since weather is “sunny” (and not “rainy”).
if-elif-else statement
Choose between multiple options.
grade = 85
if grade >= 90:
print("Grade: A")
elif grade >= 80:
print("Grade: B")
elif grade >= 70:
print("Grade: C")
elif grade >= 60:
print("Grade: D")
else:
print("Grade: F")
This gives output:
Grade: B
since 85 is greater than 80 (and less than 90).
Logical Operators
You can use the and and or operators to combine multiple conditions to make more complex decisions.
and operator
and requires both (all) conditions to be True.
score = 85
passed_coursework = True
# Both conditions must be true
if score >= 90 and passed_coursework:
print("Pass")
else:
print("Fail")
This gives the output
Fail
since score = 85, which does not satisfy the condition score >= 90, even though passed_coursework = True (which satisfies the passed_coursework condition).
or operator
or only requires that at least one of the conditions must be True.
score = 85
passed_coursework = True
# At least one of the conditions must be true
if score >= 90 or passed_coursework:
print("Pass")
else:
print("Fail")
This gives the output
Pass
since passed_coursework = True (which satisfies the passed_coursework condition). It doesn’t matter that score = 85 and the condition score >= 90 is not satisfied.
not operator
not reverses the condition.
score = 85
passed_coursework = True
if not score < 90 and not passed_coursework==False:
print("Pass")
else:
print("Fail")
This gives the output
Fail
since score = 85, which does not satisfy the condition not score < 90 (since 85 is less than 90), even though passed_coursework = True satisfies the not passed_coursework==False condition.
while Loops
The while loop repeats code as long as a condition is True.
count = 1
while count <= 5:
print(f"Count: {count}")
count = count + 1 # Don't forget to update the variable!
This gives the output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
When using while loops, make sure there is a way for your conditions to become False so you can break out of them. It is very rarely the case that you will want an infinite loop.
for loops
The for loop repeats code a specific number of times.
for loop with lists and tuples (collections)
list_of_colours = ['blue', 'red', 'green']
# Would also work with a tuple, e.g. ('blue', 'red', 'green')
for colour in list_of_colours:
print(colour)
This gives the output:
blue
red
green
for item in collection:means “do this for each item”, e.g.for colour in list_of_coloursmeans “do this for each item inlist_of_colours”.colouris just a variable name given to each item in the list (you could have used any name. For example, the linefor a in list_of_colourswould work exactly the same, although you would then need to writeprint(a)).- The code inside the loop runs once for each element in the list and the order is respected.
for loop with range()
Starting from 0:
for i in range(5):
print(f"Count: {i}")
This gives the output:
Count: 0
Count: 1
Count: 2
Count: 3
Count: 4
With both start and end of range specified:
# Start at 1, end before 6
for i in range(1, 6):
print(f"Count: {i}")
This gives the output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
With step size specified:
# Count by 2s from 0 to 4 (5 is not included)
for i in range(0, 5, 2):
print(f"Even number: {i}")
This gives the output:
Even number: 0
Even number: 2
Even number: 4
break and continue
The break and continue commands are used to stop and exit looping behaviour.
break`
break stops the loop completely.
for i in range(10):
if i == 5:
break # Stop when i equals 5
print(i)
This gives the output:
0
1
2
3
4
continue
continue skips the rest of the current iteration.
for i in range(10):
if i == 5:
continue # Skip when i equals 5
print(i)
This gives the output:
0
1
2
3
4
6
7
8
9
Common Patterns
Data collection pattern {data-collection}
# Collect user input into a list
scores = []
while True:
score = input("Enter score (or 'done'): ")
if score == "done":
break
scores.append(int(score))
Data lookup pattern
# Quick lookups with dictionaries
phone_book = {"Alice": "123-4567", "Bob": "987-6543"}
name = input("Enter name: ")
if name in phone_book:
print(f"Phone: {phone_book[name]}")
else:
print("Name not found")
Data processing pattern
# Process all items in a collection
numbers = [1, 2, 3, 4, 5]
doubled = []
for num in numbers:
doubled.append(num * 2)
# Result: [2, 4, 6, 8, 10]
Sentinel loop
while True:
command = input("Enter command (or 'exit' to quit): ")
if command == "exit":
break
process_command(command)
This keeps asking for a user’s input after processing their command unless they type “exit”. Here, “exit” is the sentinel, the specific value that breaks the loop.
User input loop
password = ""
while password != "secret":
password = input("Enter password: ")
if password != "secret":
print("Wrong password!")
print("Access granted!")
The while password != "secret" part means that the user is repeatedly asked for input until their input is "secret".
Input validation
while True:
age = input("Enter your age: ")
if age.isdigit():
age = int(age)
break
else:
print("Please enter a valid number!")
print(f"Your age is {age}")
The while True part means that the user is repeatedly asked for input until the condition age.isdigit() is met.
Menu system
while True:
print("1. Say Hello")
print("2. Say Goodbye")
print("3. Exit")
choice = input("Choose an option: ")
if choice == "1":
print("Hello there!")
elif choice == "2":
print("Goodbye!")
elif choice == "3":
print("Exiting...")
break
else:
print("Invalid choice!")
The while True part means the commands below are repeated until the user enters a viable choice (in this case, 1, 2 or 3).
Accumulator pattern
# Calculate total score
scores = [85, 92, 78, 95, 88]
total = 0 # Initialize accumulator
for score in scores:
total = total + score # Update accumulator
print(f"Total score: {total}")
This gives the output:
Total score: 438
which is the sum of the scores 85, 92, 78, 95, 88.
The accumulator pattern is used to build up a result over multiple iterations of a loop. In this case, 0 is the initial value you set the accumulator to. This value is then updated by adding an element from the scores list each iteration through the loop.
This can also be combined with conditional if statements.
answers = ["correct", "wrong", "correct", "correct", "wrong"]
correct_count = 0 # Initialize accumulator
for answer in answers:
if answer == "correct":
correct_count = correct_count + 1 # Update accumulator
print(f"You got {correct_count} correct!")
This gives the output:
You got 3 correct!
Practice Exercises
Solidify your understanding of control flows with these exercises.
Q1: if-else
Write a program that asks the user for the temperature and prints whether they should wear a coat.
Expected output:
What's the temperature? 12
Wear a coat!
Example solution
temperature = int(input("What's the temperature? "))
if temperature < 15:
print("Wear a coat!")
else:
print("No coat needed!")
Q2: if-elif-else
Write a program that converts a numerical score to a letter grade.
Grading scale:
- 90 or above: A
- 80-89: B
- 70-79: C
- 60-69: D
- Below 60: F
Expected output:
Enter your score: 85
Your grade is: B
Example solution
score = int(input("Enter your score: "))
if score >= 90:
print("Your grade is: A")
elif score >= 80:
print("Your grade is: B")
elif score >= 70:
print("Your grade is: C")
elif score >= 60:
print("Your grade is: D")
else:
print("Your grade is: F")
Q3: Loop for counting
Write a program that asks the user for a number and counts down from that number to 1, then prints “Blast off!”
Expected output:
Enter countdown start: 5
5
4
3
2
1
Blast off!
Hint
There are two ways to solve this.
One is to use a for loop with range(). Remember that range() needs the right parameters to count backwards.
The other is to use a while loop with the accumulator pattern.
Example solution
With a for loop:
countdown = int(input("Enter countdown start: "))
for i in range(countdown, 0, -1):
print(i)
print("Blast off!")
With a while loop:
countdown = int(input("Enter countdown start: "))
while countdown > 0:
print(countdown)
countdown = countdown - 1
print("Blast off!")
Q3: while loop with variable tracking
Write a program that keeps asking the user for a password until they enter the correct one (“python123”). After 3 wrong attempts, the program should lock them out.
Expected output:
With wrong attempts
Enter password: hello
Wrong password! 2 attempts remaining.
Enter password: world
Wrong password! 1 attempt remaining.
Enter password: python123
Access granted!
When locked out
Enter password: hello
Wrong password! 2 attempts remaining.
Enter password: world
Wrong password! 1 attempt remaining.
Enter password: test
Wrong password! 0 attempts remaining.
Account locked! Too many failed attempts.
Hint
You’ll need a counter variable to track attempts, and a while loop that continues while the password is wrong AND attempts remain.
Example solution
correct_password = "python123"
attempts = 3
while attempts > 0:
password = input("Enter password: ")
if password == correct_password:
print("Access granted!")
break
else:
attempts = attempts - 1
if attempts > 0:
print(f"Wrong password! {attempts} attempts remaining.")
else:
print("Wrong password! 0 attempts remaining.")
print("Account locked! Too many failed attempts.")
(Bonus) If you want to take into account the singular and plural versions of “attempt(s)”
correct_password = "python123"
attempts = 3
while attempts > 0:
password = input("Enter password: ")
if password == correct_password:
print("Access granted!")
break
else:
attempts = attempts - 1
if attempts > 0:
# "attempts" if more than 1 attempt, otherwise "attempt"
print(f"Wrong password! {attempts} attempt{'s' if attempts != 1 else ''} remaining.")
else:
print("Wrong password! 0 attempts remaining.")
print("Account locked! Too many failed attempts.")
