Search code examples
pythonif-statementargv

Python: using an if statement on an argument which may or may not be there


I've been trying to make a small script (I'm brand new to Python, by the way), which will return a a scrabble score for a given word (argv[1], and to prompt me to type a word if I dont give it one. After fiddling around with if statements and many index errors later, I settled on this:

try:
    do something with sys.argv[1]
except IndexError:
    print 'Type an argument'

But it's not as elegant as I would like. Its basically just saying "If you get this kind of error, print this:" right? I had been trying something like:

if argv[1] >= 1:
    do something with sys.argv[1]
else:
    print 'Type an argument'

But I kept getting an index error on the if portion, which i think i figured out was because if argv[1] is less than one, there is no argument, which means argv[1] doesn't exist. am i on the right page? I'd like to say something like "if there's no argument given, print this:" Is that possible?

Here's the actual code I'm using

from sys import argv
from string import maketrans

i = 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r' 's' 't' 'u' 'v' 'w' 'x' 'y' 'z' 'A' 'B' 'C' 'D' 'E' 'F' 'G' 'H' 'I' 'J' 'K' 'L' 'M' 'N' 'O' 'P' 'Q' 'R' 'S' 'T' 'U' 'V' 'W' 'X' 'Y' 'Z'
o = '0' '2' '2' '1' '0' '3' '1' '3' '0' '7' '4' '0' '2' '0' '0' '2' '9' '0' '0' '0' '0' '3' '3' '7' '3' '9' '0' '2' '2' '1' '0' '3' '1' '3' '0' '7' '4' '0' '2' '0' '0' '2' '9' '0' '0' '0' '0' '3' '3' '7' '3' '9'
t = maketrans(i, o)

def main():
  try:
   print sum(int(x) for x in argv[1].translate(t)) + len(argv[1])
  except IndexError:
   print 'Type a word, you shmuck'

if __name__ == '__main__':
  main()

Solution

  • Part of Python's philosophy is "It is better to ask forgiveness than permission" - and as this is an error case, there is no harm to the try, except. That said, if you want to avoid it, you could just check the number of arguments:

    def main():
        if len(argv) < 2:
            print "We need at least one argument"
            return
        # Remainder of implementation goes here