Skip to content

Sep 04: Prac1, if-else Statements

Learning Objectives

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

  • Explain the logistics for taking a quiz in CS 149.
  • Describe the behavior of if, elif, and else.

Reminders

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

Practice Quiz 1

[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 if"), 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
    • Go to Tools > Options… > Run & Debug
    • Change preferred debugger to "faster"
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}.")