【发布时间】:2016-04-24 06:47:37
【问题描述】:
我在 Python 2.7.11 中有一个 main 方法(在第一次执行后)会询问用户是否要继续 (y/n)。 'y' 的响应重新执行了我在main 中实例化的 while 循环就好了,并且考虑了错误的输入并重新提出了问题。但是,当用户输入'n' 时,它不会打印'Goodbye.',而是在没有到达print 语句的情况下退出循环。这是我的代码:
def main():
will_continue = 'y' # Default for the first execution
while will_continue == 'y':
# A bunch of execution code here for the program...
# After executing rest of code
will_continue = raw_input('Do you wish to continue? (y/n): ')
while will_continue != 'y' and will_continue != 'n':
if will_continue == 'n':
print 'Goodbye.'
else:
will_continue = raw_input('Invalid input. Do you wish to continue? (y/n): ')
if __name__ == "__main__":
main()
我想我的问题可能是while continue != 'y' and continue != 'n': 中的and,所以我将其更改为while continue != 'y' or continue != 'n':,但这会让我陷入'Goodbye' 的无限循环,如果我输入'n' 或无限无响应如果我输入'y'。
关于为什么 print 'Goodbye.' 语句在终止 main 之前不会执行的任何想法?
【问题讨论】:
-
你在哪里定义 var
will_continue? -
和
continue是 python 保留关键字。您不能将其用作 var 名称。 -
@WreckeR 你确定吗?我似乎记得我有时会在不知不觉中覆盖保留的关键字。
-
Python 2.7 不允许我执行以
continue作为变量名的脚本。它可能的旧版本 python 允许您使用保留关键字。 -
好的。我把它修回原来的样子。
标签: python python-2.7 if-statement printing while-loop