为什么我的脚本需要 int()?

Why does my script require int()?

我创建了一个用作计数器的基本函数。但是,对于我通过脚本传递的每个参数,需要使用 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 - 如果我在没有 int().

的情况下传递变量 b

如何在传递每个变量时不必使用 int() 来使此脚本运行?

因为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'