我对编码和堆栈交换很陌生。请原谅任何错误的格式问题(欢迎更正)。我的问题是这个。我正在做"Python速成班“的练习7-4。我有两个程序在格式和输出方面非常相似。city_visits是作者给出的例子,并没有导致“中断外部循环”错误。但是,Pizza_toppings会导致“中断外部循环”错误。谁能解释一下导致一个错误而不是另一个错误的区别是什么?谢谢你的帮助!
Pizza_toppings.py
prompt = "\nWelcome to Pizza by the sea!"
prompt += "\nYou can add as manty toppings as you like! Just tell us!"
prompt += "\nWhen you are finished type 'quit'. Tell us what you want: "
while True:
topping = raw_input(prompt)
if topping == "quit":
break
else:
print "Adding " + topping + "."
city_visits
prompt = "\nPlease enter the name of a city you have visited:"
prompt += "\n(Enter 'quit' when you are finished.)"
while True:
city = raw_input(prompt)
if city == 'quit':
break
else:
print "I'd love to go to " + city.title() + "!"
发布于 2016-08-24 21:29:04
在Python中,循环和if/else
块的范围完全由缩进决定,所以如果缩进混乱了--就像代码中的情况一样--它会产生奇怪的结果,或者如果在意外的上下文中使用break
这样的元素,它就会产生奇怪的结果,或者根本不会编译。
在这两个示例中,您的代码应该缩进如下:
while True:
city = raw_input(prompt)
if city == 'quit':
break
else:
print "I'd love to go to " + city.title() + "!"
注意,city
、if
和else
都是(a)比while
缩进得更深,(b)缩进量完全相同。如何缩进并不太重要,但良好的实践决定了4 spaces per level of indentation (although some prefer 1 tab)。此外,不要混合制表符和空格,否则你的缩进在你的编辑器中可能看起来是正确的,但在现实中却是完全混乱的。
发布于 2016-08-24 21:15:00
在Python中缩进是严格的。这是:
if topping == "quit":
break
应该是这样:
if topping == "quit":
break
非常微妙,但在Python中非常重要。
https://stackoverflow.com/questions/39132847
复制相似问题