1

无论我做什么,我都无法让这个 while 循环工作;除非我硬编码值。

count = 0
value = raw_input('How many?')
print value
while (count <= value):
        print "a"
        count= count + 1

起初我尝试使用命令行参数,使用 sys.argv[1] 作为值,但我遇到了同样的问题。这看起来很简单,但我一生都无法弄清楚我做错了什么。

4

3 回答 3

9

确保值是整数,

while (count <= int(value)):
    count= count + 1

默认情况下是一个字符串,并且对于我们拥有raw_input的每个整数n和每个字符串(!),因此您的循环(没有)永远不会中断。sn<s is Trueint

注意:在 Python 3 中,比较字符串和整数会给出一个TypeError: unorderable types: str() < int(),这可能是更“预期”的行为。

于 2012-09-04T10:20:11.197 回答
1

首先将输入转换为整数

value = int(raw_input('How many?'))
print value
于 2012-09-04T10:21:33.590 回答
1

By the way, if you really want to get your statement to be value times printed change condition from

count <= int(value)

to

count < int(value)

or start count from 1

于 2012-09-04T10:51:56.947 回答