---
# System prepended metadata

title: Homework problemset_4

---

# 1.emojize
```
import emoji


string = ""

print("Input:", end = "")
string = input(string)
string = emoji.emojize(string)
print("Output:", "{}".format(string))
```
# 2.figlet
```
from pyfiglet import Figlet
import sys
import random

def get_font(available_fonts, font_name=None):
    if font_name and font_name in available_fonts:
        return font_name
    else:
        print("Invalid usage")
        sys.exit(1)
        # return "standard"

def main():
    f = Figlet()
    available_fonts = f.getFonts()

    if len(sys.argv) == 3 and sys.argv[1] in ['-f', '--font']:
        font_name = get_font(available_fonts, sys.argv[2])
    else:
        print("Invalid usage")
        sys.exit(1)

    user_input = input("Input:")
    f.setFont(font=font_name)
    print(f.renderText(user_input))

if __name__ == "__main__":
    main()
```
# 3.adieu
```
# while True:

# for i in name:

def get_names():
    names = []
    try:
        # print("Name:", end = "")
        while True:
            # for p in range(0, 100):
            name = input("Name:")
            names.append(name)
    except (EOFError):
        pass
    return names

# print("Adieu, adieu, to", end="")

def format_names(names):
    length = len(names)
    if length == 1:
        # print("{}".format(name[0])) == 1:
        return names[0]
        # print("{}".format(name[0]))
    elif length == 2:
        return f"{names[0]} and {names[1]}"
    else:
        formatted_names = ", ".join(names[:-1]) #   ex; , Friedrich, Louisa
        return f"{formatted_names}, and {names[-1]}"

        # print("{}".format(name[0]), end = "")
        # print(", {}".format(name[i+1]), end="")
        # if len(name[i]) == i+1:
        #     print(", and {}".format[i])
def bid_adieu(names):
    for i in range(len(names)):
        print("Adieu, adieu, to", format_names(names[:i + 1]))  #   i原本==0

if __name__ == "__main__":
    names = get_names()
    bid_adieu(names)
```
# 4.game
```
import random

def get_user_input(prompt):
    while True:
        try:
            user_input = int(input(prompt))
            if user_input <= 0:
                print("Please enter a positive integer.")
            else:
                return user_input
        except ValueError:
            print("Invalid input. Please enter a positive integer.")

def main():
    print("Welcome to the Number Guessing Game!")
    level = get_user_input("Choose a level (1 for easy, 2 for medium, 3 for hard): ")

    if level == 1:
        lower_bound, upper_bound = 1, 50
    elif level == 2:
        lower_bound, upper_bound = 1, 75
    else:
        lower_bound, upper_bound = 1, 100

    target_number = random.randint(lower_bound, upper_bound)

    while True:
        guess = get_user_input(f"Guess a number between {lower_bound} and {upper_bound}: ")

        if guess < target_number:
            print("Too small!")
        elif guess > target_number:
            print("Too large!")
        else:
            print("Just right!")
            break

if __name__ == "__main__":
    main()

```
# 5.professor
```
import random


def main():
    level = get_level()
    score = 0

    for _ in range(10):
        x, y = generate_integer(level)
        correct_answer = x + y
        tries = 0

        while tries < 3:
            try:
                user_answer = int(input(f"{x} + {y} = "))
                if user_answer == correct_answer:
                    score += 1
                    break
                else:
                    print("EEE")
                    tries += 1
                    if tries == 3:
                        print("EEE")#. Invalid input.")
                        print(f"{x} + {y} = {correct_answer}.")
            except ValueError:
                tries += 1
                if tries == 3:
                    print("EEE")#. Invalid input.")

    print("Score:{}".format(score)) #f"Your score: {score} out of 10.")


def get_level():
    while True:
        try:
            level = int(input("Level: "))
            if level not in [1, 2, 3]:
                print("\nEEE")#"Invalid level. Please choose 1, 2, or 3.")
            else:
                return level
        except ValueError:
            print("EEE")#. Please enter a number.")


def generate_integer(level):
    if level not in [1, 2, 3]:
        raise ValueError#("Invalid level")#. Please choose 1, 2, or 3.")

    min_num = 1 * (10 ** (level - 1))
    if min_num == 1:
        min_num = 0
    max_num = 10 ** level - 1
    x = random.randint(min_num, max_num)
    y = random.randint(min_num, max_num)
    return x, y


if __name__ == "__main__":
    main()
```
# 6.bitcoin
```
# import requests
# import json
# import sys

# try:
#     respond = requests.get("https://api.coindesk.com/v1/bpi/currentprice.json")
#     # print(json.dumps(respond.json(), indent = 2))
#     # if len(sys.argv) != 2:
#     #     sys.exit()
#     o = respond.json()
#     for bpi in o["bpi"]:
#         print(bpi["USD"])
#     # ...
#     # sys.argv[1]
# except requests.RequestException:
#     print("Missing command-line argument")  # Command-line argument is not a number
#     ...

import sys
import requests
import json

def get_current_bitcoin_price():
    try:
        response = requests.get("https://api.coindesk.com/v1/bpi/currentprice.json")
        response.raise_for_status()  # Check for request errors

        data = json.loads(response.text)
        bitcoin_price = data["bpi"]["USD"]["rate"]#))
        bitcoin_price_float = float(bitcoin_price.replace(",", "").replace("$", ""))
        return bitcoin_price_float
    except requests.RequestException as e:
        print(f"Error fetching data from API: {e}")
        sys.exit(1)
    except (ValueError, KeyError):
        print("Error parsing API response.")
        sys.exit(1)

def main():
    if len(sys.argv) != 2:
        print("Usage: python bitcoin.py <number_of_bitcoins>")
        sys.exit(1)
    # if sys.argv[1] == 1:
    #     print("$37,817.3283")
    # elif sys.argv[1] == 2:
    #     print("$")#75,634.6566")
    # elif sys.argv[1] == 2.5:
    #     print("$94,543.3207")
    try:
        bitcoins = float(sys.argv[1])
    except ValueError:
        print("Invalid input. Please enter a valid number of Bitcoins.")
        sys.exit(1)

    if bitcoins <= 0:
        print("Number of Bitcoins must be greater than 0.")
        sys.exit(1)


    # print(sys.argv[1])
    current_price = get_current_bitcoin_price()
    # print(current_price)
    # current_price = float(current_price_str.replace(",", ""))
    total_cost = bitcoins * current_price
    # print(total_cost)

    # print(f"Current cost of {bitcoins:.4f} Bitcoins in USD: {total_cost:,.4f}")

    print(f"${total_cost:,.4f}")


if __name__ == "__main__":
    main()
```