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

标签 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

我希望参数是可选的,所以我希望不必传递字母 arguemt。 那我怎么写letter = sys.argv[2] or 'a'这样,如果没有传入参数, letter 将被分配给 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

关于python - 如果在 + python 中没有传递参数,我如何分配默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41028491/

相关文章:

python - 如何使用Python在满足两个条件的数组中查找值

python - 自定义 Django 管理界面功能

python - 如何设置环境变量 R_user 以在 python 中使用 rpy2

python - TypeError : int() argument must be a string, 类字节对象或数字,不是 'Tensor'

python - 为什么我的正则表达式与我需要的电话号码不匹配?

python - 为什么 Azure ML 的得分概率响应大于 1?

python - 在 Jupyter 笔记本单元中漂亮地打印几个变量

Python 子图

python - Pandas,根据现有的重复计数创建新列

python - 如何在我的网站空间上使用 python 执行 JSONP?