pythonindexingargv

Indexing and other errors when using variable number of command-line arguments


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 -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.

The code I have tried so far is included below. Problems include:

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()

Solution

  • len(sys.argv) should be == 3.

    If you type

    print(str(sys.argv))
    

    before

    if len(sys.argv) == 0:
    

    you will understand