为什么argv不能与我的功能一起工作?

2024-10-06 14:29:29 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的密码

from sys import argv

a,b = argv

def gcd(a,b):
    while a:
        a,b = b%a, a
    print b

现在如果我用这个从命令行运行它

^{pr2}$

我得到这个错误

^{3}$

但是如果我去掉两个输入之间的空格,像这样

python euclidian_algorithm.py 40,48

然后我就完全没有输出了。在

首先,我不明白为什么有太多的值需要解包,而我只放了两个参数。 第二,为什么第二种情况下没有输出?在


Tags: 命令行fromimport密码def错误sysalgorithm
3条回答

尝试使用“a,b=argv[1:]”,因为file name是返回的第一个值。在

引用^{}文档

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).

因此,argv的第一个值将是当前脚本名。在第一种情况下,您尝试将三个值解压到两个变量上。这就是它失败的原因。在

在第二种情况下,将当前脚本名称分配给a,并将48,40分配给b。在

您可以通过打印argva和{}来确认这一点,如下所示

➜  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

文件名欧几里得_算法.py也是争论之一。另外,像在你的例子中那样解压参数是一种非常糟糕的做法。在

相关问题 更多 >