The list of command line arguments passed to a Python script. argv[0] is the script name (it is operating system dependent whether this is a full pathname or not).
➜ Desktop cat Test.py
from sys import argv
print argv
a, b = argv
print a, b
def gcd(a, b):
while a:
a, b = b % a, a
print b
➜ Desktop python Test.py 40, 48
['Test.py', '40,', '48'] # Note that argv has three items and first is the file name
Traceback (most recent call last):
File "Test.py", line 4, in <module>
a, b = argv
ValueError: too many values to unpack
➜ Desktop python Test.py 40,48
['Test.py', '40,48']
Test.py 40,48
Secondly, why do I get no output in the second case?
这是因为根本没有调用函数gcd。在
为了解决这个问题,因为您只需要两个项目,我将简单地分配如下
^{pr2}$
然后调用函数,像这样
gcd(a, b)
我们需要将值转换为整数,因为参数将是字符串。在
注意:另外,传递的参数需要用空格字符隔开,而不是逗号。所以,你可以这样执行程序
from sys import argv
def gcd(a, b):
while a:
a, b = b % a, a
print b
a = int(argv[1])
b = int(argv[2])
gcd(a, b)
➜ Desktop python Test.py 40 48
8
尝试使用“a,b=argv[1:]”,因为file name是返回的第一个值。在
引用^{} 文档
因此,
argv
的第一个值将是当前脚本名。在第一种情况下,您尝试将三个值解压到两个变量上。这就是它失败的原因。在在第二种情况下,将当前脚本名称分配给
a
,并将48,40
分配给b
。在您可以通过打印}来确认这一点,如下所示
argv
、a
和{这是因为根本没有调用函数
gcd
。在为了解决这个问题,因为您只需要两个项目,我将简单地分配如下
^{pr2}$然后调用函数,像这样
我们需要将值转换为整数,因为参数将是字符串。在
注意:另外,传递的参数需要用空格字符隔开,而不是逗号。所以,你可以这样执行程序
文件名欧几里得_算法.py也是争论之一。另外,像在你的例子中那样解压参数是一种非常糟糕的做法。在
相关问题 更多 >
编程相关推荐