[英]Python infinite while loop inside a function
無論我嘗試什么,我都會通過此函數不斷獲得無限循環:
# Excercise 33 - LPTHW
i = 0
numbers = []
#Ec 1
#numb = 6
#iplus = 10
def theloop(numb):
global i
#i = 0
#number = []
while i < numb:
print "At the top of i is %d" % i
numbers.append(i)
i = i + 1
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
print "The numbers: "
for num in numbers:
print num
theloop(7)
當我運行腳本時,它只會繼續打印:
At the top of i is 0
At the top of i is 0
...
提前致謝。
您的代碼對我來說是書面的,但由於使用了混合的制表符和空格,因此看起來有些奇怪。 當我使用.readlines閱讀腳本時,您會看到以下內容:
' def theloop(numb):\n',
' \t\tglobal i\n',
' \t\t#i = 0\n',
' #number = []\n',
' \t\twhile i < numb:\n',
' \t\t\tprint "At the top of i is %d" % i\n',
' \t\tnumbers.append(i)\n',
' \n',
' \t\ti = i + 1\n',
因此,我建議到處切換到四個空間,然后再移到另一個空間。 請注意,print語句和append / increment語句之間的制表符數量有所不同。
如果您混合使用空格和制表符,則嘗試像這樣運行腳本:
python -tt yourscript.py ##this will raise error if you've mixed spaces and tabs
這是運行腳本后得到的,不是無限的。
At the top of i is 0
Numbers now: [0]
At the bottom i is 1
At the top of i is 1
Numbers now: [0, 1]
At the bottom i is 2
At the top of i is 2
Numbers now: [0, 1, 2]
At the bottom i is 3
At the top of i is 3
Numbers now: [0, 1, 2, 3]
At the bottom i is 4
At the top of i is 4
Numbers now: [0, 1, 2, 3, 4]
At the bottom i is 5
At the top of i is 5
Numbers now: [0, 1, 2, 3, 4, 5]
At the bottom i is 6
At the top of i is 6
Numbers now: [0, 1, 2, 3, 4, 5, 6]
At the bottom i is 7
The numbers:
0
1
2
3
4
5
6
在以下幾行之后,似乎出現了縮進錯誤:
while i < numb:
print "At the top of i is %d" % i
numbers.append(i)
就像James所說的那樣,在粘貼時它在這里工作得很好,因此您可能需要檢查實際代碼中的縮進級別是否正確。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.