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


Emojize

Because emoji aren't quite as easy to type as text, at least on laptops and desktops, some programs support “codes,” whereby you can type, for instance, :thumbs_up:, which will be automatically converted to 👍. Some programs additionally support aliases, whereby you can more succinctly type, for instance, :thumbsup:, which will also be automatically converted to 👍.
See carpedm20.github.io/emoji/all.html?enableList=enable_list_alias for a list of codes with aliases.
In a file called emojize.py, implement a program that prompts the user for a str in English and then outputs the “emojized” version of that str, converting any codes (or aliases) therein to their corresponding emoji.


Source Code

                import emoji

                text = input("Input: ")
                find_emoji_name = text.find(":")
                
                emoji_name = text[find_emoji_name:]
                other_text = text[:find_emoji_name]
                
                create_emoji = emoji.emojize(emoji_name, language = "alias")
                print("Output: ", other_text + create_emoji)
                
            

Frank, Ian and Glen's Letters

FIGlet, named after Frank, Ian, and Glen's letters, is a program from the early 1990s for making large letters out of ordinary text, a form of ASCII art:

            _ _ _          _   _     _
           | (_) | _____  | |_| |__ (_)___
           | | | |/ / _ \ | __| '_ \| / __|
           | | |     __/ | |_| | | | \__ \
           |_|_|_|\_\___|  \__|_| |_|_|___/

Among the fonts supported by FIGlet are those at figlet.org/examples.html.
FIGlet has since been ported to Python as a module called pyfiglet.
In a file called figlet.py, implement a program that:

If the user provides two command-line arguments and the first is not -f or --font or the second is not the name of a font, the program should exit via sys.exit with an error message.


Source Code


            import sys
            from pyfiglet import Figlet
            from random import choice
            
            figlet = Figlet()
            
            # No command-line argument (just the script name)
            if len(sys.argv) == 1:
                figlet.setFont(font=choice(figlet.getFonts()))
                print("Output:", figlet.renderText(input("Input: ")), sep="\n")
                # Gets the input first, converts it and prints the output
                # \n separates arguments in different lines
            
            # Two command-line arguments
            elif len(sys.argv) == 3 and sys.argv[1] in ["-f", "--font"] and sys.argv[2] in figlet.getFonts():
                figlet.setFont(font=sys.argv[2])
                print("Output:", figlet.renderText(input("Input: ")), sep="\n")
            
            else:
                sys.exit("Invalid usage")

Adieu, Adieu


In a file called adieu.py, implement a program that prompts the user for names, one per line, until the user inputs control-d. Assume that the user will input at least one name. Then bid adieu to those names, separating two names with one and, three names with two commas and one and, and names n with n-1 commas and one and, as in the below:


Source Code

        def bid_adieu(names):
            if len(names) == 1:
                return f"Adieu, adieu, to {names[0]}"
            elif len(names) == 2:
                return f"Adieu, adieu, to {names[0]} and {names[1]}"
            elif len(names) == 3:
                return f"Adieu, adieu, to {names[0]}, {names[1]}, and {names[2]}"
            else:
                return f"Adieu, adieu, to {', '.join(names[:-1])}, and {names[-1]}"
        
        names = []
        
        try:
            while True:
                name = input("Enter a name (type control-d to finish): ")
                if name:
                    names.append(name)
        except EOFError:
            pass
        
        adieu_message = bid_adieu(names)
        print(adieu_message)

Guessing Game

I'm thinking of a number between 1 and 100…
What is it?
It's 50! But what if it were more random?
In a file called game.py, implement a program that:
Prompts the user for a level,n If the user does not input a positive integer, the program should prompt again.
Randomly generates an integer between 1 and ,inclusive, using the random module.
Prompts the user to guess that integer. If the guess is not a positive integer, the program should prompt the user again.
If the guess is smaller than that integer, the program should output Too small! and prompt the user again.
If the guess is larger than that integer, the program should output Too large! and prompt the user again.
If the guess is the same as that integer, the program should output Just right! and exit.

Source Code

            import random
            low = 1
            
            while True:
                try:
                    n = int(input("Level: "))
                    right_answer = random.randint(1, n)
                    if n < low:
                        pass
                    if n < 101:
                        break
                except ValueError:
                    pass
            
            while True:
                try:
                    guess = int(input("Guess: "))
                    if guess < right_answer:
                        print("Too small!")
                    elif guess > right_answer:
                        print("Too large!")
                    else:
                        print("Just right!")
                        break
            
                except ValueError:
                    pass

Little Professor

One of David's first toys as a child, funny enough, was Little Professor, a “calculator” that would generate ten different math problems for David to solve. For instance, if the toy were to display 4 + 0 = , David would (hopefully) answer with 4. If the toy were to display 4 + 1 = , David would (hopefully) answer with 5. If David were to answer incorrectly, the toy would display EEE. And after three incorrect answers for the same problem, the toy would simply display the correct answer (e.g., 4 + 0 = 4 or 4 + 1 = 5). In a file called professor.py, implement a program that:

Prompts the user for a level, n. If the user does not input 1, 2, or 3, the program should prompt again.

Randomly generates ten (10) math problems formatted as X + Y = , wherein each of X and Y is a non-negative integer with n digits. No need to support operations other than addition (+).

Prompts the user to solve each of those problems. If an answer is not correct (or not even a number), the program should output EEE and prompt the user again, allowing the user up to three tries in total for that problem. If the user has still not answered correctly after three tries, the program should output the correct answer. The program should ultimately output the user's score: the number of correct answers out of 10.

Structure your program as follows, wherein get_level prompts (and, if need be, re-prompts) the user for a level and returns 1, 2, or 3, and generate_integer returns a randomly generated non-negative integer with level digits or raises a ValueError if level is not 1, 2, or 3:

import random
            
            
            def main():
                ...
            
            
            def get_level():
                ...
            
            
            def generate_integer(level):
                ...
            
            
            if __name__ == "__main__":
                main()

Source Code

                import random


                def main():
                    score = 10
                    level = get_level()
                
                    for _ in range(10):
                        x, y = generate_integer(level)
                
                        i = 0
                        while i < 3:
                            print(f"{x} + {y} = ", end='')
                
                            try:
                                ans = int(input())
                            except ValueError:
                                print("EEE")
                                i += 1
                                continue
                
                            if ans != x+y:
                                print("EEE")
                                i += 1
                                continue
                            else:
                                break
                
                        if i == 3:
                            print(f"{x} + {y} = {x+y}")
                            score -= 1
                
                    print(f"Score: {score}")
                
                def get_level():
                
                    while True:
                        try:
                            level = int(input("Level: "))
                        except ValueError:
                            continue
                
                        if level not in [1, 2, 3]:
                            continue
                        else:
                            return level
                
                def generate_integer(level):
                
                    if level == 1:
                        x = random.randint(0, 9)
                        y = random.randint(0, 9)
                
                    elif level == 2:
                        x = random.randint(10, 99)
                        y = random.randint(10, 99)
                
                    elif level == 3:
                        x = random.randint(100, 999)
                        y = random.randint(100, 999)
                
                    return x, y
                
                
                if __name__ == "__main__":
                    main()

            

Bitcoin Price Index


Bitcoin is a form of digitial currency, otherwise known as cryptocurrency. Rather than rely on a central authority like a bank, Bitcoin instead relies on a distributed network, otherwise known as a blockchain, to record transactions.

Because there's demand for Bitcoin (i.e., users want it), users are willing to buy it, as by exchanging one currency (e.g., USD) for Bitcoin.
In a file called bitcoin.py, implement a program that:

Expects the user to specify as a command-line argument the number of Bitcoins, n , that they would like to buy. If that argument cannot be converted to a float, the program should exit via sys.exit with an error message.
Queries the API for the CoinDesk Bitcoin Price Index at https://api.coindesk.com/v1/bpi/currentprice.json, which returns a JSON object, among whose nested keys is the current price of Bitcoin as a float. Be sure to catch any exceptions, as with code like:

import requests
            
            try:
                ...
            except requests.RequestException:
                ...
            Outputs the current cost of 
             Bitcoins in USD to four decimal places, using , as a thousands separator.

Source Code


            import requests
            import sys
            
            # Getting a JSON object
            try:
                response = requests.get(" insert link here, youtube doesn't allow it")
            except requests.RequestException:
                sys.exit(1)
            else:
                bitcoin_dict = response.json()
                # Current price of Bitcoin as a float
                bitcoin_price = bitcoin_dict["bpi"]["USD"]["rate_float"]
            
            
            # User must specify one command-line argument:
            # A floating point number that represents the number of Bitcoins.
            if len(sys.argv) != 2:
                sys.exit("Missing command-line argument")
            else: # The script name (sys.argv[0]) and one argument.
                try:
                    n = float(sys.argv[1])
                except ValueError:
                    sys.exit("Command-line argument is not a number")
                else:
                    # Outputs the current cost of n Bitcoins in USD.
                    print(f"${n * bitcoin_price:,.4f}")
                    # Four decimal places. Comma as a thousands separator