这两个while循环之间有什么区别?

时间:2016-03-13 04:33:59

标签: python python-2.x

i = 0
numbers = []

while i < 6:
    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 "numbers:"

for num in numbers:
    print num

此版本可以正常工作,但我修改了这个但无法正常工作,如下所示:

i = 0
numbers = []
start_num = raw_input('>>>')

def show_num(start_num):
global i
while i < start_num:
    print "At the top i is %d" %i
    numbers.append(i)
    i += 1
    print "Number now: ", numbers
    print "At the bottom i is %d" %i


show_num(start_num)

正确的结果是:

at the top i is 0
Numbers now: [0]
At the bottom i is 1
at the top i is 1
Numbers now: [0, 1]
At the bottom i is 2
at the top i is 2
Numbers now: [0, 1, 2]
At the bottom i is 3
at the top i is 3
Numbers now: [0, 1, 2, 3]
At the bottom i is 4
at the top i is 4
Numbers now: [0, 1, 2, 3, 4]
At the bottom i is 5
at the top i is 5
Numbers now: [0, 1, 2, 3, 4, 5]
At the bottom i is 6
numbers:
0
1
2
3
4

但第二个代码显示无限加一加......

为什么第二个代码会失败?

2 个答案:

答案 0 :(得分:2)

raw_input将输入作为字符串

你需要做

start_num = int(raw_input('>>>'))

答案 1 :(得分:0)

Hackaholic已经回答了你的问题,但我想提出一些建议。

对于for循环来说,这是一个更好的地方,因为现在这样做会被视为unpythonic

此外,%s是较旧的做事方式,我建议使用.format()

def show_num():
    start_num = int(raw_input('>>>'))
    numbers = []
    for i in range(start_num):
        print 'At the top i is {0}'.format(i)
        print 'At the bottom i is {0}'.format(i)
        numbers.append(i)
        print 'Numbers now:', numbers

show_num()
相关问题