Skip to content

Sep 06: Quiz 1a, if-else Statements

Learning Objectives

After today's class, you should be able to:

  • Describe the behavior of if, elif, and else statements.

Reminders

  • Due TODAY
  • Read Ch 3 – ideally:
    • 1st half before Friday
    • 2nd half before Monday
  • Submit HW 3 – ideally:
    • 1 and 2 before Friday
    • 3 and 4 before Monday

HW2 Debrief

[10 min]

Some highlights:

  • Splitting up long lines of code
  • Rounding to n decimal places
  • Using math module functions
  • // and % usually go together

Quiz 1a

[25 min]

Instructions:

  • Log in as student
  • Only two windows:
    1. Thonny
    2. Web browser
  • Web traffic monitored
  • Log out when finished

Ch03 Preview

[15 min]

  • Keywords: if, elif, else
  • == is a comparison operator ("is equal to")
    • = is the assignment operator ("is now")
  • Indented blocks show the program structure
    • The line before always ends with a colon
  • Demo: Stepping over code with the debugger
fractions.py
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import math

print("Welcome to the fraction reducer!")

# Input the fraction as two integers
print()
numer = int(input("Numerator? "))
denom = int(input("Denominator? "))
print()

if denom == 0:
    print("Sorry, you can't divide by 0")
    print("Have a nice day")
else:
    # Divide by the greatest common divisor
    gcd = math.gcd(numer, denom)
    numer2 = numer // gcd
    denom2 = denom // gcd

    # Output the result in the right format
    if denom2 == 1:
        print(f"{numer}/{denom} reduces to {numer2}.")
    elif denom2 == denom:
        print(f"{numer}/{denom} is already reduced!")
    else:
        print(f"{numer}/{denom} reduces to {numer2}/{denom2}.")