2016-03-13 76 views
0
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 

這個版本可以正常工作,但我改變這一點,但不能正常工作,具體如下:這兩個while循環有什麼區別?

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

raw_input需要輸入作爲字符串

你需要做的

start_num = int(raw_input('>>>')) 
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() 
+0

感謝您的分享。在Learning Python中,我注意到Hard Way顯示不同的類型使用不同的%,例如%d%s%r,並且您的方法也需要在不同情況下進行更改? {0}是什麼意思?這意味着格式號碼? – Annndy

+0

Google是你的朋友。 https://pyformat.info/ – tripleee

+0

也http://stackoverflow.com/questions/13451989/pythons-many-ways-of-string-formatting-are-the-older-ones-going-to-be-deprec – tripleee