CS50 Introduction To Python Programming


The CS50's Introduction to Programming with Python is a course offered by Harvard University, focusing on teaching Python programming.
This course, led by Harvard Professor David J. Malan, is designed for students with or without prior programming experience who want to learn Python specifically.
It covers topics such as functions, variables, conditionals, loops, exceptions, libraries, unit tests, file I/O, regular expressions, and object-oriented programming.
The course provides hands-on practice opportunities with exercises inspired by real-world programming problems. It can be taken independently or as a precursor to the more general CS50x course,
which covers computer science and programming with C, Python, SQL, and JavaScript.
The CS50's Introduction to Programming with Python course is available online through platforms like Harvard Online, edX, and YouTube, offering a comprehensive introduction to Python programming


Problem Set 3 Solutions

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.

Source Code

        while True:
            try:
                fraction = input("Enter a fraction (e.g. 1/4): ")
                top, bottom = map(int, fraction.split("/"))
                if bottom == 0:
                    print("Error: Cannot divide by zero.")
                    continue
                if top > bottom:
                    print("Error: The top number is greater than the bottom number.")
                    continue
                percentage = top / bottom * 100
                if percentage >= 99:
                    print("F")
                elif percentage <= 1:
                    print("E")
                else:
                    print(f"{round(percentage)}%")
                break
        
            except ValueError:
                print("Error: Invalid input. Please enter a fraction in the format 'x/y'.")
        

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:

{
                "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
            }
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.

Source Code

            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.0
            
            while True:
                try:
                    item = input("Enter an item (or control-d to finish): ").title()
                    if item in menu:
                        total += menu[item]
                        print(f"${total:.2f}")
                    elif item == "":
                        continue
                    else:
                        print("Sorry, that's not a valid item.")
                except EOFError:
                    break
            
            print("Thanks for ordering!")
            

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


Source Code

                    grocery_list = {}

                    while True:
                        try:
                            item = input("").lower()
                            if item == "":
                                continue
                            if item in grocery_list:
                                grocery_list[item] += 1
                            else:
                                grocery_list[item] = 1
                        except EOFError:
                            break
                    
                    sorted_grocery_list = sorted(grocery_list.items())
                    
                    for item, count in sorted_grocery_list:
                        print(f"{count} {item.upper()}")
                    

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:

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

Source Code

                months = [
                    "January",
                    "February",
                    "March",
                    "April",
                    "May",
                    "June",
                    "July",
                    "August",
                    "September",
                    "October",
                    "November",
                    "December"
                ]
                def main():
                    while True:
                        date = input('Date: ')
                        try:
                            mnth,day,year = date.split('/')
                            mnth = int(mnth)
                            day = int(day)
                            year = int(year)
                            if (int (mnth) > 0 and int(mnth) < 13) and (int(day) > 0 and int(day) < 32):
                                if year >= 1000 and year <= 9999:
                                    print (year, f'{mnth:02}',f'{day:02}', sep='-')
                                    break
                        except:
                            try:
                                if "," in date:
                                    mnth,day,year = date.split(' ')
                                    day = day.replace(',','')
                                    day = int(day)
                                    year = int(year)
                                    if mnth in months and (int(day) > 0 and int(day) < 32):
                                        if year >= 1000 and year <= 9999:
                                            mnth= (months.index (mnth)+1)
                                            print (year, f'{mnth:02}',f'{day:02}', sep = '-')
                                            break
                            except:
                                pass
                
                main()