打破内部循环 python
Breaking inner loop python
我只想退出放置中断的内部循环。使用 continue 可以工作,但我认为 break 应该退出最内层的循环,但它似乎退出了整个程序。 break 是怎么回事?
counter = 0
while counter == 0:
print "You enter a dark room with two doors. Do you go through door #1 or door #2?"
door = raw_input("> ")
if door == "1":
print "There's a giant bear here eating a cheese cake. What do you do?"
print "1. Take the cake."
print "2. Scream at the bear."
bear = raw_input("> ")
if bear == "1":
print "The bear eats your face off. Good job!"
elif bear == "2":
print "The bear eats your legs off. Good job!"
else:
print "Well, doing %s is probably better. Bear runs away." % bear
break
else:
print "You stumble around and fall on a knife and die. Good job!"
你的代码中只有一个循环,break 正在退出它,"if" 不是循环,它是一个语句...即使你有多个,它们也是语句,并且 break, will "break" 来自你的 while 循环,而不是 "if" 语句。
break
- Jumps out of the closest enclosing loop (past the entire loop
statement)
在你的情况下,这正是它在做什么。 if
不是循环语句,它是控制语句。
您只有一个循环,即 while
。
我只想退出放置中断的内部循环。使用 continue 可以工作,但我认为 break 应该退出最内层的循环,但它似乎退出了整个程序。 break 是怎么回事?
counter = 0
while counter == 0:
print "You enter a dark room with two doors. Do you go through door #1 or door #2?"
door = raw_input("> ")
if door == "1":
print "There's a giant bear here eating a cheese cake. What do you do?"
print "1. Take the cake."
print "2. Scream at the bear."
bear = raw_input("> ")
if bear == "1":
print "The bear eats your face off. Good job!"
elif bear == "2":
print "The bear eats your legs off. Good job!"
else:
print "Well, doing %s is probably better. Bear runs away." % bear
break
else:
print "You stumble around and fall on a knife and die. Good job!"
你的代码中只有一个循环,break 正在退出它,"if" 不是循环,它是一个语句...即使你有多个,它们也是语句,并且 break, will "break" 来自你的 while 循环,而不是 "if" 语句。
break
- Jumps out of the closest enclosing loop (past the entire loop statement)
在你的情况下,这正是它在做什么。 if
不是循环语句,它是控制语句。
您只有一个循环,即 while
。