Skip to content

Sep 03: 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

  • Due TODAY
  • Read Week 3 – ideally:
    • 1st half before Friday
    • 2nd half before Monday
  • Submit HW 3 – ideally:
    • 1 and 2 before Friday
    • 3 and 4 before Monday
  • Upcoming events
    • CS Dept Club Mixer – Thursday 9/4 at 5:00pm in King 259 + 260
    • Professional Resources – Friday 9/5 at 4:00pm in King Hall 259

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]

Quiz Logistics

Before the quiz:

  • Log in to the lab machine as student (no password)
  • Open a web browser – do NOT open Thonny until later!
  • Log in to Gradescope; close all other tabs and windows
  • Silence your phone and place on top of the computer

When the quiz begins:

  • Start recording (double click the icon on the desktop)
  • Open the "Prac1 Written" assignment on Gradescope
  • If you finish early, start reading the coding portion
  • You may use the coding portion as scratch paper

At the 10-minute mark:

  • Open Thonny when instructed – do NOT open before!
  • Test your code in Thonny; Gradescope won't give hints

At the end of the quiz:

  • Submit files to Gradescope before the time runs out
  • Stop recording when instructed (not when you finish)
  • Turn in the coding portion handout to the prof or TA
  • Log out as student; you may log back in as yourself

At the end of class:

  • Don't forget your phone sitting on the computer
  • Do NOT discuss the quiz outside of the classroom

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}.")