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 1 Solutions

Deep Thought

In deep.py, implement a program that prompts the user for the answer to the Great Question of Life, the Universe and Everything, outputting Yes if the user inputs 42 or (case-insensitively) forty-two or forty two.
Otherwise output No.

Source Program

        def main():
            user_input = input("What is the answer to the Great Question of Life, the Universe and Everything? ").lower().strip()
            if user_input == '42' or user_input == 'forty two' or user_input == 'forty-two':
                print("Yes")
            else:
                print("No")
        
        if __name__ == "__main__":
            main()
        

Home Federal Savings Bank

In a file called bank.py, implement a program that prompts the user for a greeting.
If the greeting starts with “hello”, output $0. If the greeting starts with an “h” (but not “hello”), output $20.
Otherwise, output $100. Ignore any leading whitespace in the user's greeting, and treat the user's greeting case-insensitively.

Source Code

def main():
                greeting = input("Say something nice: ").lower().strip()
                if greeting.startswith('hello'):
                    print("$0")
                elif greeting.startswith('h'):
                    print("$20")
                else:
                    print("$100")
            
            if __name__ == "__main__":
                main()
            

File Extensions

In a file called extensions.py, implement a program that prompts the user for the name of a file and then outputs that file's media type if the file's name ends, case-insensitively, in any of these suffixes:

                .gif
                .jpg
                .jpeg
                .png
                .pdf
                .txt
                .zip

If the file's name ends with some other suffix or has no suffix at all, output application/octet-stream instead, which is a common default.

Source Code

def main():
                    file_name = input("Enter the name of the file: ").lower().strip()
                    if file_name.endswith('.gif'):
                        print("image/gif")
                    elif file_name.endswith(('.jpg', '.jpeg')):
                        print("image/jpeg")
                    elif file_name.endswith('.png'):
                        print("image/png")
                    elif file_name.endswith('.pdf'):
                        print("application/pdf")
                    elif file_name.endswith('.txt'):
                        print("text/plain")
                    elif file_name.endswith('.zip'):
                        print("application/zip")
                    else:
                        print("application/octet-stream")
                
                if __name__ == "__main__":
                    main()
                

Math Interpreter

Python already supports math, whereby you can write code to add, subtract, multiply, or divide values and even variables.

But let's write a program that enables users to do math, even without knowing Python.

In a file called interpreter.py, implement a program that prompts the user for an arithmetic expression and then calculates and outputs the result as a floating-point value formatted to one decimal place.
Assume that the user's input will be formatted as x y z, with one space between x and y and one space between y and z, wherein: x is an integer
y is +, -, *, or /
z is an integer
For instance, if the user inputs 1 + 1, your program should output 2.0. Assume that, if y is /, then z will not be 0.
Note that, just as python itself is an interpreter for Python, so will your interpreter.py be an interpreter for math!

Source Code

def main():
                expression = input("Enter an arithmetic expression: ").strip()
                x, y, z = expression.split(" ")
                x = int(x)
                z = int(z)
            
                if y == "+":
                    result = x + z
                elif y == "-":
                    result = x - z
                elif y == "*":
                    result = x * z
                elif y == "/":
                    result = x / z
                else:
                    raise ValueError("Invalid arithmetic expression")
            
                print("{:.1f}".format(result))
            
            if __name__ == "__main__":
                main()
            

Meal Time

Suppose that you're in a country where it's customary to eat breakfast between 7:00 and 8:00, lunch between 12:00 and 13:00, and dinner between 18:00 and 19:00.
Wouldn't it be nice if you had a program that could tell you what to eat when?

In meal.py, implement a program that prompts the user for a time and outputs whether it's breakfast time, lunch time, or dinner time.
If it's not time for a meal, don't output anything at all. Assume that the user's input will be formatted in 24-hour time as #:## or ##:##.
And assume that each meal's time range is inclusive. For instance, whether it's 7:00, 7:01, 7:59, or 8:00, or anytime in between, it's time for breakfast.
Structure your program per the below, wherein convert is a function (that can be called by main) that converts time, a str in 24-hour format, to the corresponding number of hours as a float.
For instance, given a time like "7:30" (i.e., 7 hours and 30 minutes), convert should return 7.5 (i.e., 7.5 hours). def main():
...
def convert(time):
...
if __name__ == "__main__":
main()

Source Code

                def main():
                    time = input("Enter a time in 24-hour format (#:## or ##:##): ").strip()
                    hours, minutes = time.split(":")
                    hours = convert(hours, minutes)
                
                    if 6.0 <= hours < 11.0:
                        print("It's breakfast time!")
                    elif 11.0 <= hours < 14.0:
                        print("It's lunch time!")
                    elif 17.0 <= hours < 21.0:
                        print("It's dinner time!")
                
                def convert(hours, minutes=0):
                    return float(hours) + float(minutes) / 60.0
                
                if __name__ == "__main__":
                    main()