Skip to content

Sep 09: More Logic, Tracing Code

Learning Objectives

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

  • Summarize what values Python considers to be true in a Boolean context.
  • Predict output when using if, elif, else, and nested if statements.
  • Use a debugger to step through and examine programs one line at a time.
  • Write a function that performs a unit conversion (Ex: celsius to fahrenheit).

Reminders

[5 min]

  • Due tomorrow
  • Quiz 1 on Thursday
    • Based on HW 1 and HW 2
    • Review questions from Practice Quiz 1
    • Study practice exercises on Runestone
    • If statements not allowed

MiniLecture from previous class

Mini Activity

[15 min]

  • Boolean Values
    • If you are absent today, complete this activity at home
    • Bring your completed activity to class or office hours

Code snippet:

value = 123
if value:
    print("Truthy")
else:
    print("Falsy")

Tracing Practice

[20 min]

For each example:

  • Predict the output as a team (by hand, on paper)
  • Step through the code using Thonny's debugger

Example 1:

hat = "fedora"

if hat == "fedora":
    print("A")
else:
    print("B")

print("C")

Example 2:

x = 10

if x < 100:
    print("A")
elif x < 50:
    print("B")
else:
    print("C")

print("D")

Example 3:

x = 10

if x < 100:
    print("A")
if x < 50:
    print("B")

print("C")

Example 4:

x = 10
hat = "fez"

if x > 100 or hat == "fez":
    print("A")
    if x < 50:
        print("B")
    else:
        print("C")
else:
    print("D")
    if hat == "fedora":
        print("E")
print("F")

Example 5:

x = 1.0
y = 0.0
b1 = x > 0 and y > 0
b2 = not x <= 0 or y <= 0
b3 = not (x <= 0 or y <= 0)
print(b1, b2, b3)

Next Topic Preview: Functions

[15 min]

  • Functions have parenthesis
    • Example from algebra: \(f(x) = 2x\)
    • \(f\) is a function, \(x\) is a variable, \(2x\) is the result
  • Python keywords: def and return
    def double(number):
        return 2 * number
    
  • Using descriptive names for functions/variables
  • Added Docstring Requirements for Functions
temperature.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
27
28
29
30
31
32
33
34
35
36
37
38
"""Example unit conversion functions.

Author: Chris Mayfield
Version: 09/11/2024
"""


def c_to_f(celsius):
    """Convert celsius to fahrenheit.

    Args:
        celsius (float): degrees in celsius

    Returns:
        float: degrees in fahrenheit
    """
    return (celsius * 1.8) + 32


def f_to_c(fahrenheit):
    """Convert fahrenheit to celsius.

    Args:
        fahrenheit (float): degrees in fahrenheit

    Returns:
        float: degrees in celsius
    """
    return (fahrenheit - 32) / 1.8


if __name__ == "__main__":

    c = f_to_c(30)
    f = c_to_f(30)

    print(f"30 degrees F = {c:5.1f} degrees C")
    print(f"30 degrees C = {f:5.1f} degrees F")

MiniLecture (next time will complete)