繁体   English   中英

如果没有在+ python中传递参数,我该如何分配默认值

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

我怎样写letter = sys.argv[2] or 'a' ,这样,如果没有传入参数a将被分配到信。 因此,基本上,我希望letter的默认值是a除非传入了一些东西。如果要传入一些东西,我希望将其分配给letter

这是我的简单程序:

$ 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

这是我通过传递2个参数peaa来运行程序

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

我希望参数是可选的,因此我希望不必传递字母体。 那么我该怎么写letter = sys.argv[2] or 'a'以便如果没有传入的参数将被分配给a

这是我仅使用一个参数运行程序的情况,我希望参数是可选的。

$ 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

您可以使用以下内容:

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

sys.argv[2]是在第三元件sys.argv ,这意味着的长度sys.argv应至少为3,如果它不是>= 3 ,我们分配'a'letter

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM