I thought it would be fun to track all of my progress learning python, even the VERY humble beginnings. Any of the posts with the CS50 tag are simply copy/pastes of my code from lessons, along with a copy/paste of what the assignment actually wanted me to do for context.
Fuel Gauge
Fuel gauges indicate, often with fractions, just how much fuel is in a tank. For instance 1/4 indicates that a tank is 25% full, 1/2 indicates that a tank is 50% full, and 3/4 indicates that a tank is 75% full.
In a file called fuel.py
, implement a program that prompts the user for a fraction, formatted as X/Y
, wherein each of X
and Y
is an integer, and then outputs, as a percentage rounded to the nearest integer, how much fuel is in the tank. If, though, 1% or less remains, output E
instead to indicate that the tank is essentially empty. And if 99% or more remains, output F
instead to indicate that the tank is essentially full.
If, though, X
or Y
is not an integer, X
is greater than Y
, or Y
is 0
, instead prompt the user again. (It is not necessary for Y
to be 4
.) Be sure to catch any exceptions like ValueError
or ZeroDivisionError
.
```{{python}}
def main():
x = get_input("Fraction: ")
if x >= 99:
print("F")
elif x <= 1:
print("E")
else:
print(int(x),"%", sep="")
def get_input(prompt):
while True:
try:
top, bottom = input(prompt).split("/")
if int(top) <= int(bottom):
return round((int(top) / int(bottom)), 2) * 100
else:
pass
except (SyntaxError, ZeroDivisionError, ValueError):
pass
main()
```
Felipe’s Taqueria
One of the most popular places to eat in Harvard Square is Felipe’s Taqueria, which offers a menu of entrees, per the dict
below, wherein the value of each key is a price in dollars:
```{python}
"Baja Taco": 4.00,
{"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 }
```
In a file called taqueria.py
, implement a program that enables a user to place an order, prompting them for items, one per line, until the user inputs control-d (which is a common way of ending one’s input to a program). After each inputted item, display the total cost of all items inputted thus far, prefixed with a dollar sign ($
) and formatted to two decimal places. Treat the user’s input case insensitively. Ignore any input that isn’t an item. Assume that every item on the menu will be titlecased.
```{{python}}
def main():
#Create Menu Dictionary
menu = {
"Baja Taco": 4.00,
"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
}
#Define total as 0 since that is our starting total
total = 0
#Create loop of getting ordered item, adding it to total, then printing total with correct format
while True:
try:
order = input("Item: ").title().strip()
total = total + menu[order]
print("$",total,0, sep="")
except KeyError:
pass
except EOFError:
print("\n")
quit()
main()
```
Grocery List
Suppose that you're in the habit of making a list of items you need from the grocery store.
In a file called grocery.py
, implement a program that prompts the user for items, one per line, until the user inputs control-d (which is a common way of ending one's input to a program). Then output the user's grocery list in all uppercase, sorted alphabetically by item, prefixing each line with the number of times the user inputted that item. No need to pluralize the items. Treat the user's input case-insensitively.
```{{python}}
def main():
#Create empty list
grocery_list = []
#While loop to continue to add items to list until user inputs stop command (ctrl + d)
while True:
try:
grocery_item = input("").upper().strip()
grocery_list.append(grocery_item)
except EOFError:
break
#Create an alphabetically sorted variation of grocery list
sorted_grocery_list = sorted(grocery_list)
unique = list(dict.fromkeys(sorted_grocery_list))
#For loop to search
for item in unique:
counter = sorted_grocery_list.count(item)
print(counter, item)
main()
```
Outdated
In the United States, dates are typically formatted in month-day-year order (MM/DD/YYYY), otherwise known as middle-endian order, which is arguably bad design. Dates in that format can't be easily sorted because the date's year comes last instead of first. Try sorting, for instance, 2/2/1800
, 3/3/1900
, and 1/1/2000
chronologically in any program (e.g., a spreadsheet). Dates in that format are also ambiguous. Harvard was founded on September 8, 1636, but 9/8/1636 could also be interpreted as August 9, 1636!
Fortunately, computers tend to use ISO 8601, an international standard that prescribes that dates should be formatted in year-month-day (YYYY-MM-DD) order, no matter the country, formatting years with four digits, months with two digits, and days with two digits, "padding" each with leading zeroes as needed.
In a file called outdated.py
, implement a program that prompts the user for a date, anno Domini, in month-day-year order, formatted like 9/8/1636
or September 8, 1636
, wherein the month in the latter might be any of the values in the list
below:
``` {{python}}
["January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"]
```
Then output that same date in YYYY-MM-DD
format. If the user's input is not a valid date in either format, prompt the user again. Assume that every month has no more than 31 days; no need to validate whether a month has 28, 29, 30, or 31 days.
```{{python}}
def main():
months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
]
while True:
user_input = input("Date: ").strip()
#Determine whether to split slashes or spaces, depending on what user inputs
try:
#Split entry in month, day and year
month, day, year = user_input.split("/", 2)
#Make sure entries are within bounds of months and day
if 1 <= int(day) <= 31 and 1 <= int(month) <= 12:
#Print correct date format
print(year,"-",f"{int(month):02d}","-",f"{int(day):02d}", sep="")
break
else:
pass
except ValueError:
try:
#Split entry into month, day and year by spaces
month, day, year = user_input.split(" ", 2)
#Create a variable to store the position of inputted month, add one since lists are zero-based, then print if this variable is found and exists
month_check = months.index(month) + 1
day = int(day.removesuffix(","))
#Make sure entries are within bounds of months and day
if 1 <= day <= 31 and 1 <= month_check <= 12:
print(year,"-",f"{month_check:02d}","-",f"{day:02d}", sep="")
break
else:
pass
except ValueError:
pass
main()
```