你怎么知道它是否不会终止?有没有让它继续运行的功能?如果我想在一定次数后停止循环,我该怎么做?
2 回答
Generally, it's impossible to know ahead of time whether a program will loop forever or eventually stop. This is called the Halting problem. Of course, in practice you can probably make a reasonable guess just by looking at the condition.
a while loop will keep going as long as its condition is true. You do not need a function to make it keep going.
while True:
print "hello, world!"
#no functions required here!
If you want something to loop a certain number of times, it's preferable to use a for loop:
for i in range(10):
print "hello, world!"
#prints ten times
although you still can use a while loop if you really want.
count = 0
while count < 10:
print "hello, world!"
count += 1
A while
loop is terminated
if the condition it uses is false at the time it gets evaluated.
Example:
x = 10 while x > 5: x -= 7 print x x += 6 print x
successively will print the numbers 3, 9, 2, 8, 1, 7, 0, 6, -1, 5 and only then terminate.
x
becomes<= 5
during execution, but only the state at the time where the loop is restarted is relevant.if it is left meanwhile with
break
:x = 10 while x > 5: print x x -= 1 break
only prints 10, because it is left "forcefully" afterwards.
A loop which runs a certain number of times would be done
x = 0
while x < n:
do_stuff()
x += 1
or better with for:
for x in range(n):
do_stuff()