yiping
yiping

Reputation: 55

What is the difference between these two while loops?

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

This version can work correctly, but I modify this but can not work correctly, as follows:

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)

The correct result is:

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

but the second code shows the infinite one plus one plus...

Why does the second code fail?

Upvotes: 0

Views: 70

Answers (2)

Jason
Jason

Reputation: 2304

Hackaholic has already answered your question, but I would like to give a few suggestions.

This is a better place for a for loop, as doing it as you are now is considered unpythonic.

Also, %s is an older way of doing things, I'd recommend using .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()

Upvotes: 0

Hackaholic
Hackaholic

Reputation: 19733

raw_input takes input as string

you need to do

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

Upvotes: 2

Related Questions