I am working my way through CS50's Introduction to Programming with Python. For the current problem I am supposed to write a program which involves:
- 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
-for--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
-for--fontor the second is not the name of a font, the program should exit viasys.exitwith an error message.
The code I have tried so far is included below. Problems include:
- When I enter no arguments in the command line I get
IndexError: list index out of range - When I enter 2 arguments and the first argument is not
-for--fthesys.exitis not executing as it should.
import sys
import random
fonts = ['fontA', 'fontB']
def main():
s = input("Text: ")
if len(sys.argv) == 0:
print(print_random(s))
elif len(sys.argv) == 2 and (sys.argv[1] == "-f" or sys.argv[1] == "--font") and sys.argv[2] in fonts:
print(print_argument(s))
else:
sys.exit()
def set_font(font):
pass # dummy implementation
def print_random(s):
set_font(font=random.choice(fonts))
# render_text(s)
def print_argument(s):
set_font(font=sys.argv[2])
# render_text(s)
main()
len(sys.argv) should be == 3.
If you type
before
you will understand