The lesson this week was very short. We covered the following functions: SyntaxError
. ValueError
. try
. except
. NameError
. else
. pass
. raise
. In short, the lesson talked about how to deal with error messages more cleanly.
try:
x = int(input("what's x? "))
print(f"x is {x}")
except ValueError:
print("x is not an integer")
Here is a very simple program. The user inputs a value for x and then the program prints “x is {x}” for whatever the value was. However if the value inputted for x was not an integer we would get a ValueError message. Instead of outputting a long and ugly error message in the case x is not an integer, we use the try and except functions to output “x is not an integer” if x is not integer. We can do the same for all sorts of error messages, like NameError.
def main():
x = get_int("What's x? ")
print(f"x is {x}")
def get_int(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
pass
main()
Here, we are using the same concept to define function get_int(). The pass function means nothing happens and the while loop continues to run. So in main() the user will get the value of x using get_int() which will ask the user for a value until they receive an integer. Then it will print. Else means complete unless a error occurs, and the lesson did not actually cover Raise.
Problem 1: Fuel Guage
In this problem we are asked to take an input X/Y and convert it to a percent for a fuel gauge. I started by defining a function get_percent and asking the user for the input and splitting it into X and Y. Then I ran errors like ValueError and ZeroDivisionError. I made sure X was not greater than Y. Then I returned the percent. If it was over 99% it was F (full) and if it was less than 1% it was E (empty) and if not it just displayed the rounded percent.
def main():
percent = get_percent("Fraction: ")
if percent >= 99:
print("F")
elif percent <= 1:
print("E")
else:
print(f"{percent:.0f}%")
def get_percent(prompt):
while True:
try:
X, Y = input(prompt).strip().split("/")
X = int(X)
Y = int(Y)
if X > Y:
continue
percent = (X / Y) * 100
except ValueError:
pass
except ZeroDivisionError:
pass
else:
return percent
main()
Problem 2: Felipe’s Taqueria
In this problem we are calculating an order total at a taqueria. We are given the dict (menu) in the prompt. To do this I created a variable order_total and set it to zero. Then I created a loop that continuously asks the user what their order item is. If they input a viable item in the dict, the price gets added to the total. This continues until the user types CTR-D which terminates the input and the loop.
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
}
order_total = 0
while True:
try:
order_item = input("Item: ").strip().lower().title()
if order_item in menu:
order_total += menu[order_item]
except EOFError:
print("")
break
else:
print(f"Total: ${order_total:.2f}")
Problem 3: Grocery List
This problem serves as a functioning grocery list, where the user inputs a list of groceries, and then the program stores and repeats back those items and the quantity of each. To do this, I created a continuous loop for the user to input groceries. Every time the user inputs a new grocery, the item gets added to an empty dictionary as a key with a value of 1. If the item is already in the dictionary, the item’s value increases by one. When the user wants to stop inputting items, they hit CTRL – D to stop the input (EOFError).
Then we have to sort the the items alphabetically. To do this, I created a new variable, keys, which takes the keys from grocery_list and sorts them using the sorted() function. Then we create a new dictionary called sorted_keys. Then, we copy every value from grocery_list to sorted_keys, using a for loop. Then we print the sorted list and the quantity of each item.
grocery_list = {}
while True:
try:
grocery_item = input().upper().strip()
if grocery_item not in grocery_list:
grocery_list[grocery_item] = 1
elif grocery_item in grocery_list:
grocery_list.update({grocery_item: grocery_list[grocery_item] + 1})
except EOFError:
print("")
break
keys = grocery_list.keys()
keys = sorted(keys)
sorted_keys = {}
for value in keys:
sorted_keys[value] = grocery_list[value]
for key, value in sorted_keys.items():
print(value, key)
Problem 4:
In this problem, we are converting inputs of the US standard date format MM-DD-YYYY or Month, Day, Year to the international standard YYYY-MM-DD. In the prompt, we are given a list of the months. I created a while loop to deal with both kinds of input.
For the standard MM-DD-YYYY format I used the split function to split the input at the “/” into three variables: month, day, and year. I converted those units to integers and tried them for ValueError or TypeError. This means that if the user inputs something that is not an int like “October” instead of 10, the program will prompt the user for a new input. If the input satisfied the constraints, the international format would print. Using f”{n:02}” means that 0 will fill in if the month or day is not a double digit.
For the second format, Month Day, Year, I also used a split function but only on white space. I also had to try for ValueError or TypeError, but I also had to check that the “,” was present and, if it was, strip it from the day variable. Then I printed the date in the new format.
months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
]
while True:
user_input = input("Date: ").strip()
if "/" in user_input:
month, day, year = user_input.split("/")
try:
month = int(month)
day = int(day)
year = int(year)
if month > 12 or day > 31:
continue
except ValueError or TypeError:
pass
else:
print(f"{year}-{month:02}-{day:02}")
break
elif "," and " " in user_input:
month, day, year = user_input.split()
try:
month = months.index(month)
if "," not in day:
continue
else:
day = int(day.strip(","))
year = int(year)
if month > 12 or day > 31:
continue
except ValueError or TypeError:
pass
else:
print(f"{year}-{month+1:02}-{day:02}")
break
else:
continue
I feel like as the lessons progress, the problem sets get progressively more challenging but also more rewarding. Super looking forward to week 4.