Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do i assign a default value if no argument is passed in + python

Tags:

python

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
like image 983
HattrickNZ Avatar asked Nov 03 '25 03:11

HattrickNZ


1 Answers

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

like image 96
ettanany Avatar answered Nov 05 '25 17:11

ettanany



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!