I thought it would be fun to track all of my progress learning python, even the VERY humble beginnings. Any of the posts with the CS50 tag are simply copy/pastes of my code from lessons, along with a copy/paste of what the assignment actually wanted me to do for context.
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.
```{{python}}
import emoji
def main():
user_input = input("Input: ")
print(emoji.emojize(f"Output: {user_input}", language="alias"))
main()
```
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:
Expects zero or two command-line arguments:
Zero if the user would like to output text in a random font.
Two if the user would like to output text in a specific font, in which case the first of the two should be
-f
or--font
, and the second of the two should be the name of the font.
Prompts the user for a
str
of text.Outputs that text in the desired font.
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.
```{{python}}
import sys
#Define what is wanted from Figlet
from pyfiglet import Figlet
figlet = Figlet()
def main():
#If no argument is passed after file name, then ask for input and print rendered text
if len(sys.argv) == 1:
user_input = input("Input: ").strip()
print("Output:")
print(figlet.renderText(user_input))
#If there are two additional arguments after file name, ensure Font name exists
elif len(sys.argv) == 3:
#Attempt to find index name, if unable then a ValueError will be returned which causes the function to exit
try:
search_list = figlet.getFonts()
search_list.index(sys.argv[2])
pass
except ValueError:
sys.exit("Invalid usage")
#Ensure that second argument equals "-f" otherwise exit
if sys.argv[1] != "-f":
sys.exit("Invalid usage")
#set the font to desired and print the rendered text
figlet.setFont(font=(sys.argv[2]))
user_input = input("Input: ").strip()
print("Output:")
print(figlet.renderText(user_input))
#Catch all in case more or less arguments are added
else:
sys.exit("Invalid usage")
main()
```
Adieu, Adieu
In The Sound of Music, there’s a song sung largely in English, So Long, Farewell, with these lyrics, wherein “adieu” means “goodbye” in French:
Adieu, adieu, to yieu and yieu and yieu
Of course, the line isn’t grammatically correct, since it would typically be written (with an Oxford comma) as:
Adieu, adieu, to yieu, yieu, and yieu
To be fair, “yieu” isn’t even a word; it just rhymes with “you”!
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 n names with n−1 commas and one and
, as in the below:
Adieu, adieu, to Liesl
Adieu, adieu, to Liesl and Friedrich
Adieu, adieu, to Liesl, Friedrich, and Louisa
Adieu, adieu, to Liesl, Friedrich, Louisa, and Kurt
Adieu, adieu, to Liesl, Friedrich, Louisa, Kurt, and Brigitta
Adieu, adieu, to Liesl, Friedrich, Louisa, Kurt, Brigitta, and Marta
Adieu, adieu, to Liesl, Friedrich, Louisa, Kurt, Brigitta, Marta, and Gretl
```{{python}}
def main():
names = []
while True:
try:
user_input = input("Name: ")
names.append(user_input)
except EOFError:
break
print("\n","Adieu, adieu, to ", end="")
if len(names) == 1:
print(names[0])
elif len(names) == 2:
print(names[0],"and",names[1],)
#if there are more than two names, continue to iterate until reaching the last name, at which point print "and (Last name)"
else:
iteration = 0
for name in names:
if iteration == (len(names) - 1):
print("and", name)
else:
print(name,",", sep = "", end=" ")
iteration = iteration + 1
main()
```
Guessing Game
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 n, 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.
``` {{python}}
import random
import sys
def main():
#While loop to get requested level and generate a random number in between 1 and requested level
while True:
try:
user_level = int(input("Level: ").strip())
answer = random.randint(1, user_level)
break
except ValueError:
pass
#While loop for guessing the answer
while True:
try:
user_guess = int(input("Guess: ").strip())
#If tree to determine if answer to too high, low, or just right
if user_guess < answer:
print("Too small!")
elif user_guess > answer:
print("Too large!")
else:
print("Just right!")
sys.exit()
except ValueError:
pass
main()
```
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
, or3
, the program should prompt again.Randomly generates ten (10) math problems formatted as
X + Y =
, wherein each ofX
andY
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
:
```{{python}}
import random
def main():
#Ask for level, generate x and y
level = get_level()
correct_answers = 0
for _ in range(10):
#Generate x and y for problem, reset # of tried to 0
x = generate_integer(level)
y = generate_integer(level)
tries = 0
while True:
#Print the problem and get input
print(f"{x} + {y} = ", end="")
user_answer = int(input("").strip())
#Check if answer is correct or not, break & add 1 to correct_answer count if correct; give 3 tries to answer if not correct,
if user_answer == (x + y):
correct_answers = correct_answers + 1
break
else:
tries = tries + 1
print("EEE")
try:
if tries == 3:
print(f"{x} + {y} = {x + y}")
break
else:
pass
except ValueError:
pass
print(f"Score: {correct_answers}")
def get_level():
while True:
try:
user_input = int(input("Level: ").strip())
#return level value only if it is 1, 2, or 3
if 1 <= user_input <= 3:
return user_input
else:
pass
except ValueError:
pass
def generate_integer(level):
if level == 1:
return random.randint(0, 9)
elif level == 2:
return random.randint(10, 99)
elif level == 3:
return random.randint(100, 999)
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 viasys.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 n Bitcoins in USD to four decimal places, using
,
as a thousands separator.
```{python}
import requests
import sys
import json
def main():
if len(sys.argv) != 2:
"Missing command-line argument")
sys.exit(
try:
= requests.get("https://api.coindesk.com/v1/bpi/currentprice.json")
bitcoin = bitcoin.json()
bitcoin_json = bitcoin_json["bpi"]["USD"]["rate"].replace(",", "")
bitcoin_price = float(bitcoin_price) * float(sys.argv[1])
bitcoin_price
print(f"${bitcoin_price:,.4f}")
except requests.RequestException:
pass
except ValueError:
"Command-line argument is not a number")
sys.exit(
main()```