在我的代码中添加一个 while 循环,以重新 运行 程序或根据用户输入终止 [Python 2.7]

Adding a while loop to my code to either re-run the program or terminate based on user input [Python 2.7]

我目前正在尝试向我的代码添加一个 while 循环,如下所示。我试图做的事情背后的理论如下:

正如您在我代码的最底部看到的那样,我确认了用户的预订并询问 he/she 是否愿意创建另一个。如果用户输入“是”,我希望程序重新 运行。如果不是,则程序应该终止。我知道完成此操作的最佳方法是使用 while 循环,但我我执行这个有点困难,因为我的教科书在这个问题上有点混乱。

我知道它应该看起来像这样(或类似的东西):

while True:
expression
break

虽然我似乎无法编译它。有什么建议么?下面是我的代码:

user_continue = str(raw_input("Your reservation was submitted successfully.  Would you like to do another?"))

if user_continue != 'yes':

print('Thank you for flying with Ramirez Airlines!')

这里有一个简单的例子,展示了如何使用 while 循环:

import time

while True:
    print time.ctime()
    print 'Doing stuff...'
    response = raw_input('Would you like to do another? ')
    if response != 'yes':
        break

print 'Terminating'

请注意,while 循环 中的代码必须 缩进,这与您的第一个代码块中的代码不同。缩进在 Python 中 非常 重要。请始终确保您的问题(和答案)中的代码正确缩进。

FWIW,raw_input() 输入函数 returns 一个字符串,所以 str(raw_input()) 是不必要的混乱。


您的代码结尾应类似于:

user_continue = raw_input("Your reservation was submitted successfully.  Would you like to do another?")    
if user_continue != 'yes':
    break

print('Thank you for flying with Ramirez Airlines!')

...

你的打印语句有点滑稽。由于您使用的是 Python 2.7,因此您无需执行

print ('The total amount for your seats is: $'),user_people * 5180

你可以做到

print 'The total amount for your seats is: $', user_people * 5180

或者如果您想使用 Python 3 样式,请将要打印的所有内容 放在括号内 ,如下所示:

print ('The total amount for your seats is: $', user_people * 5180)

但是,输出看起来会有点乱,因为 $ 和金额之间会有一个 space。请阅读 python 文档以了解如何解决该问题。

...

此外,您的循环中有 import time。不要那样做。通常,import 语句应该位于脚本的顶部,位于任何其他可执行代码之前。