Control Flow in Python

To write programs, rather than batch processing scripts for calculations, we need a way to manage control flow in Python. In order to do so we need a concept of branching (conditional) logic and a concept of loops.

If and Else Statements

If and else statements in Python are similar to other common languages, except for their unusual syntax. The main differences are:

  • Python uses whitespace to signal a code block, not curly braces
  • Python uses elif instead of the more common else if
  • Brackets in if statements are optional in Python, and usually only used in more complex examples
ticket_price = 15.0

age = int(input("What's your age?"))

# child discount
if age < 18:
  ticket_price = 7.5
# student discount
elif age > 18 and age < 21:
  ticket_price = 10.0
# senior discount
elif age > 65:
  ticket_price = 10.0
# pass means "do nothing" and is helpful for code you haven't written yet
else:
  pass

print(f"Your ticket will cost ${ticket_price:2f}, thank you.")

Exercises

  1. Combine the two elif statements in the example above into a single condition.
  2. Change the logic of the statement so that the ticket_price is set in else instead of before the if statement.
  3. Improve your calculator program so that it takes two floats and an operand, performs the operation, and returns an output. You should try to cover the operands +, -, /, and *.

Loops

Python has two main types of loop: while loops and for... in loops. It doesn't have a do-while loop or a generic for loop like most other languages. This is because of the core Python language principle that:

There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch.

while loops continue to execute until their condition evaluates as False.

i = 10

while i > 0:
  print(i)
  i -= 1

for... in loops iterate through an iterable until they run out of elements to iterate through. In practice this is much less complicated than it sounds.

# count to 10
for i in range(10):
  print(i)

# equivalent to our while loop above
# range parameters are start, end, and step
for i in range(10,0,-1):
  print(i)

# loop through a list, one possible iterable
a_list = [1,2,3,4,5]

for number in a_list:
  print(number * 2)

We can use the continue keyword to skip a single iteration of a loop, or the break keyword to escape the loop altogether.

for i in range(10):
  # skip even numbers
  if i % 2 == 0: continue 
  print(i)

i = 0
while True:
  if i >= 10: break  
  print(i)
  i += 1

Exercises

Exercise 1

My friend was born on February 29th. I want a program which counts the number of birthdays she's had since a given year. Write a program which will take a year as an input and log all the years in which my friend celebrated her birthday on February 29th since that year, then finally log the number of birthdays she celebrated. To avoid working with dates, assume today is January 1st. An example output:

> 1988
1988
1992
1996
2000
2004
2008
2012
2016
2020
Number of birthdays: 9

Exercise 2

Improve your calculator app to include m as a valid input, replacing one number. m will start at zero and stores the result of previous calculator runs. When a calculator operation is complete, it should ask the user if they want to reset to zero, store the result in m, or exit. It should then let the user choose and continue the operation.

Exercise 3

Make a simple game of rock-paper-scissors. The game should work as follows: - The player is prompted for a choice of rock-paper-scissors. - The computer logs their choice. - The winner is declared and logged out. - The game prints out how many points the player and the computer have. - The game gives players a choice whether to continue with the game or quit.

You'll need to use a random generator to get the computer's move. This can easily be done with random.choice from the standard library:

import random

# 0 - rock
# 1 - paper
# 2 - scissors
random.choice([0,1,2])