【问题标题】:Why does my script require int()?为什么我的脚本需要 int()?
【发布时间】:2015-12-08 07:44:21
【问题描述】:

我创建了一个用作计数器的基本函数。但是,对于我通过脚本传递的每个参数,都需要使用 int() 将变量转换为整数。

“fun_loop(n, b)”中的两个变量都需要 int()。

from sys import argv

script, max_number, increment = argv 

def fun_loop(n, b):

    i = 0
    numbers = []

    while i < int(n):
        print "At the top i is %d" % i
        numbers.append(i)

        i = i + int(b)
        print "Numbers now: ", numbers
        print "At the bottom i is %d" % i


    print "The numbers: "

    for num in numbers:
        print num

print "We can just give the numbers directly"
fun_loop(6, 1)

print "Or we can use variables from our script"
fun_loop(max_number, increment)

如果我在变量上运行没有 int() 的代码,那么我会得到...

一个无限循环 - 如果我传递变量 n 而没有 int()

TypeError: unsupported operand - 如果我传递变量 b 而没有 int()

在传递每个变量时,我怎样才能使这个脚本工作而不必使用int()

【问题讨论】:

    标签: python string shell python-2.7 integer


    【解决方案1】:

    因为sys.argv 列表的元素总是字符串。

    您可以在将它们传递给函数之前将它们转换为整数

    max_number, increment = map(int, argv[1:])
    fun_loop(max_number, increment)
    

    具体来说,您会得到一个无限循环,因为在 Python 2 中整数排在其他所有内容之前:

    >>> 1 < '1'
    True
    

    你得到你的TypeError,因为在一个整数和一个字符串上使用+在Python中不是一个有效的操作:

    >>> 0 + '1'
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: unsupported operand type(s) for +: 'int' and 'str'
    

    【讨论】:

    • 我之前通过将参数转换为整数来运行代码,就像您发布的代码一样。但是我遇到了这个错误。 File "ex33s.py", line 5, in &lt;module&gt; script, max_number, increment = map(int, argv[1:]) ValueError: need more than 2 values to unpack我的代码如下script, max_number, increment = map(int, argv[1:]) def fun_loop(n, b):
    • @user3200293:仔细看看我给你的代码。我分配给script, max_number, increment。我省略了script,因为脚本名称不需要转换为整数。
    • 是的,一旦你对你的评论设置格式,我就知道你为什么会收到错误。
    猜你喜欢
    • 2021-05-12
    • 2018-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-09
    • 1970-01-01
    • 2012-05-21
    • 1970-01-01
    相关资源
    最近更新 更多