OIM3640 - Problem Solving and Software Design

2025 Spring

Session 08 (2/13)

contain

Today's Agenda

  • Welcome/News/Announcements
  • Review
    • Exercises
    • Quiz 0
  • Lecture - Iterations

Welcome/News/Announcements

  • Quiz Policy
    • Quiz 0 counts as one exercise.
    • There are no make-up opportunities for unexcused absences.
    • The lowest grade will be dropped automatically, including any missed quiz.
  • Communications
    • Meet with me in person during office hours at least once this semester.
    • Email - specify course # in subject title, e.g., "OIM3640: GitHub settings"
    • Use Slack/GitHub when asking code-related questions
  • Questions?

What we have learned so far...

  • Variables, expressions, statements
  • Types: int, float, string, boolean, Nonetype, other data structures
  • Functions
  • turtle module
  • Pseudo-code
  • Conditional Statements
    • if...elif...else
    • recursion (not recommended for beginners)

Quick Quiz

  1. What are the two main purposes of functions in programming?
  2. If score is 95, what will be printed?
     if score >= 60:
         print("Pass")
     elif score >= 90:
         print("A")
     else:
         print("Fail")
    
  3. Do the two function calls below have the same effect?
    def polygon(t, n, length):
        ...
    
    polygon(leo, 7, 70)
    polygon(leo, length=70, n=7)
    

Python Tips

  1. __main__ check
    if __name__ == '__main__':
    # Running as the main program ...
    # but does not execute if loaded with import ...
    
  2. To swap two variables:
    1. Use a temporary variable (in other programming languages)
    2. A more Pythonic way: x, y = y, x
  3. Use comparison chain:
    # if bmi >= 18.5 and bmi <= 30:
    if 18.5 <= bmi <= 30:
    

Exercises

  • Please check your OIM3640/Issues on GitHub.
    • Reply if we need to continue the conversation.
    • Reply (with evidence) and Close if you think it is fixed.
    • If you have any question regarding
  • Suggestions / Requirements:
    • File/folder names - lowercase and underscore, eg. session04/type_demo.py
    • Please add docstrings for the functions your create!
    • Please test your functions!
    • Please use separate files for different questions.

Issues #0

def check_fermat(a, b, c, n):
    """"Checks Fermat's Last Theorem and prints the result."""
    if n > 2 and a**n + b**n == c**n:
        print("Holy smokes, Fermat was wrong!")
    else:
        print("No, that doesn't work.")


def check_number():
    """Gets inputs and calls check_fermat function"""
    a = int(input("Select value of a: "))
    ...
    return check_fermat(a, b, c, n)
  • No need to add return in the second function

Issues #1

def get_bmi_category(BMI):
    """"""
    if BMI < 18.5:
        print("Underweight")
    elif 18.5 <= BMI < 24.9:
        print("Normal weight")
    elif 25 <= BMI < 29.9:
        print("Overweight")
    elif BMI > 30:
        print("Obesity")
  • What if BMI is 29.95?

Issues #2

def calculate_bmi(height, weight):
    """Calculate bmi through input of your height and weight."""
    height = float(input("Your height in meters: "))
    weight = float(input("Your weight in kilograms: "))
    print("Your bmi is: ", round(weight / (height * height), 2))

calculate_bmi(1.70, 70)
  • When calling the calculate_bmi function, the height and weight values are provided as arguments.
  • Inside the function, the parameter variables - height and weight - should be treated as given, and should not be reassigned (unless absolutely necessary.)

Issues #3

def get_bmi_catagory(bmi):
    bmi = float(bmi)
    if bmi <= 18.5:
        print('Underweight')
    elif bmi in range[18.5, 25]:
        print('Normal weight')
    elif bmi in range[25, 30]:
        print('Overweight')
    else:
        print('Obesity')
  • It's incorrect to use range in this context.
    • range is a function used to generate a sequence of numbers, commonly used in for loops.
    • range is not designed for checking if a value is within a range.

Issues #4

    ...
    if bmi < 18.5:
        print("Underweight")
    else:
        if bmi >= 18.5 and bmi < 25:
            print("Normal Weight")
        else:
            if bmi >= 25 and bmi < 30:
                print("Overweight")
            else:
                print("Obesity")
  • Avoid excessive nesting of if ... else statements.

Issues #5

def get_bmi_category():
    weight = float(input("Input weight"))
    height = float(input("Input height in inches"))
    if calculate_bmi(weight, height) < 18.5:
        print("Underweight")
    elif calculate_bmi(weight, height) >= 18.5 and calculate_bmi(weight, height) < 25:
        print("Normal weight")
    elif calculate_bmi(weight, height) >= 25 and calculate_bmi(weight, height) < 30:
        print("Overweight")
    elif calculate_bmi(weight, height) >= 30:
        print("Obese")
  • Function calculate_bmi(weight, height) might be executed 6 times in worst case, which is not ideal if
    • the function costs a lot of time/computing,
    • or the function has some other side effects.

Issues #6

def calculate_bmi(weight, height):
    bmi = 703 * (weight/height**2)
    if bmi <= 18.5:
        return "You are underweight"
    elif bmi > 18.5 and bmi <= 25:
        return "You are normal weight"
    elif bmi > 25 and bmi <= 29.9:
        return "You are overweight"
    else:
        return "You are obese!"

def start_bmi(weight, height):
    response = calculate_bmi(weight, height)
    return response
  • start_bmi has no added value.
  • calculate_bmi only needs to calculate and return bmi instead of doing everything in one place.

Session 08

- **Assignment 1** is posted on Canvas. Please **accept** it now. - It should be a **separate** repo. Do not copy it to your ***OIM3640*** repo. - Read instructions including the [code grading rubric](https://github.com/OIM3640/resources/blob/main/code_grading_rubric.md), before starting to code.

--- # Quick Quiz - Python Trivia Facts 1) Was **Python** created as a **hobby project**? 2) Where does the name "**Python**" for the programming language come from? 1) Guido van Rossum's favorite *[pet animal](https://en.wikipedia.org/wiki/Python_(genus))* 2) Guido van Rossum's favorite *[comedy TV show](https://www.youtube.com/watch?v=JrdEMERq8MA)* 3) Guido van Rossum's favorite *[artwork](https://www.metmuseum.org/art/collection/search/398703)* 4) Guido van Rossum's favorite *[mythical creature](https://en.wikipedia.org/wiki/Python_%28mythology%29)* 3) Is **Python** open source? --- # One More ~~Python~~ Programming Fun Fact * Try `0.1 + 0.2` in Python interactive shell * **Do not worry! It is NORMAL!** * This happens in all programming languages that use floating point decimals, **not just in Python**. * Because computers represent decimal numbers in **binary (Base-2) format**. * Check out <https://0.30000000000000004.com> * How to avoid? * Consider using the [`decimal` library](https://docs.python.org/3/library/decimal.html) if precision matters to your program. * We could use `print(f'{result:.1f}')` to hide such floating point errors. * Read [more discussions on stackoverflow](https://stackoverflow.com/questions/19473770/how-to-avoid-floating-point-errors)

Use keyword arguments when a function has many variables.