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
asked Dec 7, 2016 at 22:25
1

1 Answer 1

11

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

answered Dec 7, 2016 at 22:29
Sign up to request clarification or add additional context in comments.

2 Comments

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?
That's the equivalent of tirnary operator in Python and it is the shorter possible way.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.