Solving CS50P - Problem Set 4
Libraries are snippets of code written by you or others that you can use in your program. Using libraries can save time and effort for both novice and experienced programmers, preventing the need to reinvent the wheel when encountering certain problems. This article provides insight into how to use libraries to solve coding problems in Python.
Emojize
In this program, we import the emoji
library to access its functions. We prompt the user to input text using the input
function. The input text is then passed to the emoji.emojize
function, which converts the text into emojis. Here's an example:
Input: :smile:
Output: 😄
Solution:
import emoji
code = input("Input: ")
emojis = emoji.emojize(code, language='alias')
print(f"Output: {emojis}")
Frank, Ian and Glen’s Letters
This program imports sys
, random
, and pyfiglet
libraries to use their functions. The pyfiglet
library in Python is a library that generates ASCII art text in various fonts. The program is designed to take input text from the user and generate ASCII art text in a randomly selected font or a user-specified font using the pyfiglet
library. Example:
Input: Hello World
Output:
_ _ _ _ __ __ _ _ _
| | | | ___| | | ___ \ \ / /__ _ _| |__ (_) |
| |_| |/ _ \ | |/ _ \ \ \ /\ / / _ \| | | | '_ \| | |
| _ | __/ | | (_) | \ V V / (_) | |_| | |_) | | |
|_| |_|\___|_|_|\___/ \_/\_/ \___/ \__,_|_.__/|_|_|
Solution:
import sys
import random
from pyfiglet import Figlet
figlet = Figlet()
figlet.getFonts()
font = random.choice(figlet.getFonts())
try:
if len(sys.argv) == 3:
if sys.argv[1] != "-f":
if sys.argv[1] != "--font":
sys.exit("Invalid use")
if sys.argv[2] in figlet.getFonts():
font = sys.argv[2]
else:
sys.exit("Invalid use")
else:
sys.exit("Invalid use")
except IndexError:
pass
figlet.setFont(font=font)
s = input("Input: ")
print(f"Output:\n{figlet.renderText(s)}")
Guessing Game
This program is designed to be a fun game. The game allows the user to specify the difficulty by inputting a maximum number between 1 to 100. The randint
function from the random library generates a random number within that range. The user is then prompted to guess that number with hints between each guess.
import random
while True:
try:
level = int(input("Level: "))
except ValueError:
pass
else:
if level > 0:
if level <= 100:
break
answer = random.randint(1, level)
while True:
try:
guess = int(input("Guess: "))
except ValueError:
pass
else:
if guess > answer:
print("Too large!")
elif guess < answer:
print("Too small!")
else:
print("Just right!")
break
Adieu, adieu
This program demonstrates using the inflect
library for proper grammar and punctuation. We continuously ask the user for names until the user ends the program by inputting control-d. We then print a farewell message ("Adieu, adieu, to.."), followed by the names. If there is only one name, we print it. If there are two names, we use the join
function from the inflect
library to join them with "and". If there are more than two names, the join
function joins them with commas and "and" before the last name.
import inflect
p = inflect.engine()
names = []
while True:
try:
name = input("Name: ")
names.append(name)
except EOFError:
break
print()
print("Adieu, adieu, to ", end="")
if len(names) == 1:
for n in names:
print(n)
else:
names = p.join(names)
print(names)
Little Professor
This program is a math quiz game in Python. The user is prompted to specify the difficulty level. The game generates random addition problems using the random
module, based on the selected level and keeps track of the user's score. The game generates 10 addition problems, with three chances to answer each problem correctly. If the user answers incorrectly three times, the correct answer is displayed, and the next problem is generated. After 10 problems, the final score is displayed.
import random
def main():
l = get_level()
count = 0
score = 0
wrong = 0
while True:
while count < 10:
x = generate_integer(l)
y = generate_integer(l)
ans = x + y
print(f"{x} + {y} = ", end="")
count += 1
while True:
if wrong == 3:
print(ans)
wrong = 0
break
try:
my_ans = int(input())
except ValueError:
wrong += 1
print("EEE")
print(f"{x} + {y} = ", end="")
else:
if my_ans == ans:
score += 1
break
else:
wrong += 1
print("EEE")
print(f"{x} + {y} = ", end="")
else:
print(f"Score: {score}")
break
def get_level():
valid = [1, 2, 3]
while True:
try:
level = int(input("Level: "))
except ValueError:
pass
else:
if level in valid:
return level
def generate_integer(level):
if level not in [1, 2, 3]:
raise ValueError
if level == 1:
num = random.randint(0,9)
elif level == 2:
num = random.randint(10,99)
else:
num = random.randint(100,999)
return num
if __name__ == "__main__":
main()
Bitcoin Price Index
This simple Bitcoin price converter program in Python uses the CoinDesk API to get the current Bitcoin price in USD. The program takes a command-line argument for the amount of USD to convert and prints the equivalent amount in Bitcoin. Firstly we check if a valid command-line argument is provided. Then make a GET request to the CoinDesk API to get the current Bitcoin price in USD. If the request is successful, we parse the JSON response and calculate the current cost of x amount of Bitcoins in USD.
import requests
import sys
import json
n = sys.argv
if len(n) < 2:
sys.exit("Missing command-line argument")
else:
try:
float(n[1])
except ValueError:
sys.exit("Command-line argument is not a number")
else:
try:
response = requests.get("https://api.coindesk.com/v1/bpi/currentprice.json")
except requests.RequestException:
sys.exit("Something went wrong, please try again.")
else:
o = response.json()
rate = o["bpi"]["USD"]["rate_float"]
rate = float(rate)
dollar = n[1]
dollar = float(dollar)
amount = rate * dollar
print(f"${amount:,.4f}")
Subscribe to my newsletter
Read articles from Karabo Molefi directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by