我如何提供选择再次运行程序或以Python结束程序的选择



我正在尝试运行此程序,该程序从用户那里获取消息,然后向后打印。while循环有效,但最后我想实现一个持续或完全退出的决策点。

请参阅此处:

print("nHi, welcome to my program that will reverse your message")
start = None
while start != " ":
    var_string = input("nSo tell me, what would you like said backwards:")
    print("So your message in reverse is:", var_string[::-1])

input("Press any key to exit")

请建议我如何包含'输入之类的内容(" nif您想要另一个去,告诉我:)':)':)'如果用户决定要重新启动。P>

这对我来说是早日。

我认为您的问题与while循环无关,而有条件语句和continue/break语句,即"控制流量工具"。请参阅下面对您的代码的编辑中的建议:

print("nHi, welcome to my program that will reverse your message")
# This bit is unnecessary. Why use the `start` variable if you're never going to 
# reassign it later in your program?
#start = None 
#while start != " ":
# Instead, use `while True`. This will create the infinite loop which you can
# 'continue` or `break` out of later.
while True:
    var_string = input("nSo tell me, what would you like said backwards:")
    print("So your message in reverse is:", var_string[::-1])
    # Prompt the user again and assign their response to another 
    # variable (here: `cont`).
    cont = input("nWould you like another try?")
    # Using conditional statements, check if the user answers "yes". If they do, then
    # use the `continue` keyword to leave the conditional block and go another
    # round in the while loop.
    if cont == "Yes":
      continue
    # Otherwise, if the user answers anything else, then use the `break` keyword to 
    # leave the loop from which this is called, i.e. your while loop.
    else:
      input("Press any key to exit")
      break

最新更新