无论我尝试什么,我都会通过此功能获得无限循环:
# 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
...
提前致谢。
答案 0 :(得分:2)
您的代码对我来说是书面的,但由于使用了混合标签和空格,因此看起来有一些奇怪的缩进。当我使用.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语句之间的选项卡数量的差异。
答案 1 :(得分:1)
如果你混合了空格和制表符,那么尝试像这样运行你的脚本:
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
答案 2 :(得分:0)
这看起来像是在以下几行之后出现了一个缩进错误:
while i < numb:
print "At the top of i is %d" % i
numbers.append(i)
就像詹姆斯说的那样,粘贴时它在这里工作得很好,所以你可能想检查一下你的实际代码中是否有正确的缩进级别。