我正在通过艰难的方式学习 python,在练习 33 额外学分 2 中,我正在尝试利用 raw_input
或 argv
设置将在 while 循环中使用的变量:
# from sys import argv
# script, my_num = argv
def all_the_numbers(n):
"""increment by 1 up to limit n"""
i = 0
numbers = []
while i < n:
print "At the top i is %d" % i
numbers.append(i)
i = i + 1
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
# print "Please enter an integer: "
# n = raw_input("#")
# n = my_num
n = 10
all_the_numbers(n)
硬编码的 n = 10
按预期工作;打印最多 10
行。但是从 argv
中传入一个值作为 my_num
和/或从 raw_input
中设置变量会导致无限向上的整数递增。后两种设置变量的方式有何不同,它们的行为与同一变量的硬编码设置不同?
最佳答案
raw_input()
函数返回一个字符串,而不是一个整数。尝试:
n = int(raw_input("#"))
或
n = int(my_num)
这会转换 raw_input()
返回的字符串变成一个整数,你的 all_the_numbers()
函数期望。
这是 relevant passage from the Python docs (强调我的):
The operators <, >, ==, >=, <=, and != compare the values of two objects. The objects need not have the same type. If both are numbers, they are converted to a common type. Otherwise, objects of different types always compare unequal, and are ordered consistently but arbitrarily.
在您的例子中,数字和字符串是任意排序的,在您的例子中是 <
比较总是评估为 True
.确保此类比较的类型兼容是程序员的责任。
关于python - 为什么这个 python while 循环缺少逻辑运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5466346/