Solving CS50P - Problem Set 3

Exceptions are errors that occur within our coding. We will discuss how to handle exceptions in Python using try and except, which are ways of testing out user input before something goes wrong.

Disclaimer: The following code solutions are for educational purposes only and are not intended to be used or submitted as your own. Cheating is a violation of the Academic Honesty of the course. All problem sets presented are owned by Harvard University.

Fuel Gauge

This program is designed for a fuel gauge, it prompts the user for a fraction and calculates the percentage value. Depending on the percentage value it outputs "E", "F" or the percentage.

Exception handling:

  • The program uses a try and except block to handle exceptions that might occur during execution.

  • It catches the ValueError and ZeroDivisionError respectively.

  • It tries to process the input by evaluating certain conditions.

  • If the conditions are not satisfied (e.g. invalid input or division by zero), an exception (either ValueError or ZeroDivisionError) is raised.

  • the program continues to the next iteration of the loop.

while True:
    user_input = (input("Fraction: "))
    try:
        numerator, denominator = user_input.split('/')
    except ValueError:
        pass
    else:
        try:
            int(numerator), int(denominator)
        except ValueError:
            pass
        else:
            if int(numerator) <= int(denominator):
                try:
                    fraction = int(numerator)/int(denominator)
                except ZeroDivisionError:
                    pass
                else:
                    percentage = fraction * 100
                    percentage = round(percentage)
                    if percentage <= 1: # if 1% or less output E
                        print("E")
                    elif percentage >= 99: # if 99% or more output F
                        print("F")
                    else:
                        print(f"{percentage}%")
                    break

Grocery List

The program collects input items which are stored in a list. The occurrence of each item is determined and displayed alongside each unique item.

Exception handling:

  • The program uses a try and except block to catch the EOFError exception.

  • If the user signals the end of input by pressing control-d, an EOFError is raised.

  • When this exception occurs, the program breaks out of the loop using break.

item_list = []
while True:
    try:
        items = input().upper()
        item_list.append(items)
    except EOFError:
        break
print()

import numpy as np
values, keys = np.unique(item_list, return_counts=True)
item_dict = {values[i]: keys[i] for i in range(len(values))}
for item in item_dict:
    print(item_dict[item], item)

Outdated

The program prompts the user for a date in month-day-year order, formatted like 9/28/1986 (numeric format) or September 28, 1986 (word format). Then outputs the same date in year-month-day order (YYYY-MM-DD).

Exception handling:

  • The program uses a try and except block to handle exceptions that might occur during execution.

  • It attempts to process the input by validating certain conditions.

  • It catches the ValueError exception.

  • If no exception occurs the program prints the date in the format YYYY-MM-DD and breaks out of the loop.

  • Otherwise, if a ValueError is raised the program continues to the next iteration.

months = [
    "January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December"
]

while True:
    date = input("Date: ").strip()
    # if date is numeric format
    if "/" in date:
        try:
            month, day, year = date.split("/")
            month = int(month)
            day = int(day)
            year = int(year)
            if month <= 12 and day <= 31:
                print(f"{year}-{month:02}-{day:02}")
                break
            else:
                continue
        except ValueError:
            pass
    # if date is word format
    elif "," in date:
        try:
            month_day, year2 = date.split(",")
            month2, day2 = month_day.split(" ")
            year2 = int(year2)
            day2 = int(day2)
            month2 = months.index(month2) + 1
            if month2 <= 12 and day2 <= 31:
                print(f"{year2}-{month2:02}-{day2:02}")
                break
            else:
                continue
        except ValueError:
            pass
    else:
        continue

Felipe’s Taqueria

The program enables the user to place an order at a restaurant. It prompts for items one per line and displays the total cost of all items inputted thus far after each new item is entered.

Exception handling:

  • The program uses a try and except block to catch the EOFError exception.

  • If the user signals the end of input by pressing control-d, an EOFError is raised.

  • When this exception occurs, the program breaks out of the loop using break.

menu = {
    "Baja Taco": 4.25,
    "Burrito": 7.50,
    "Bowl": 8.50,
    "Nachos": 11.00,
    "Quesadilla": 8.50,
    "Super Burrito": 8.50,
    "Super Quesadilla": 9.50,
    "Taco": 3.00,
    "Tortilla Salad": 8.00
}

total = 0

while True:
    try:
        order = input("Item: ").title()
    except EOFError:
        print()
        break
    else:
        try:
            if order in menu:
                total += menu[order]
                print(f"Total: ${total:.2f}")
        except KeyError:
            pass