Skip to content

Sep 11: Quiz1, def Statements

Learning Objectives

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

  • Write a function that performs a unit conversion (Ex: celsius to fahrenheit).

Reminders

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

HW3 Debrief

[10 min]

Some highlights:

  • Use else whenever possible, instead of extra elif
  • Boolean values as variables, for flags and conditions
  • Avoid doing the same conditions / logic multiple times

Quiz 1

[25 min]

Instructions:

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

Ch04 Preview

[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")