4

How do I write letter = sys.argv[2] or 'a' so that if there is no argument passed in a will be assigned to letter. So basically I want the default value of letter to be a unless something is passed in. If something is to be passed in, I want that to be assigned to letter

this is my simple program:

$ cat loop_count.py
import sys

def count(word,letter):
        for char in word:
                if char == letter:
                        count = count + 1
        return count
                                # WHAT I WANT
word = sys.argv[1] or 'banana'  # if sys.argv[1] has a value assign it to word, else assign 'banana' to word
letter = sys.argv[2] or 'a'     # if sys.argv[2] has a value assign it to letter, else assign 'a' to letter

print 'Count the number of times the letter',letter,' appears in the word: ', word

count = 0
for letter in word:
        if letter == 'a':
                count = count + 1
print count

This is me running the program by passing it 2 arguments pea and a

$ python loop_count.py pea a
Count the number of times the letter a  appears in the word:  pea
1

I want the arguments to be optional so I was hoping the letter arguemt does not have to be passed. So how do I write letter = sys.argv[2] or 'a' so that if there is no argument passed in letter will be assigned to a

This is me running the program with only one argument, I want the arguments to be optional.

$ python loop_count.py pea
Traceback (most recent call last):
  File "loop_count.py", line 10, in <module>
    letter = sys.argv[2] or 'a'
IndexError: list index out of range
HattrickNZ
  • 4,373
  • 15
  • 54
  • 98
  • Possible duplicate of [Getting a default value on index out of range in Python](http://stackoverflow.com/questions/2574636/getting-a-default-value-on-index-out-of-range-in-python) – ykaganovich Dec 07 '16 at 22:32

1 Answers1

10

You can use the following:

letter = sys.argv[2] if len(sys.argv) >= 3 else 'a'

sys.argv[2] is the 3rd element in sys.argv, this means that the length of sys.argv should be at least 3. If it is not >= 3, we assign 'a' to letter

ettanany
  • 19,038
  • 9
  • 47
  • 63
  • tks thats it, but is there a shorter way to write that like `letter = sys.argv[2] ? len(sys.argv) : 'a'` or is that java sccript? – HattrickNZ Dec 07 '16 at 23:44
  • That's the equivalent of tirnary operator in Python and it is the shorter possible way. – ettanany Dec 07 '16 at 23:59