如何根据用户输入重新启动程序? [英] How do I restart a program based on user input?

查看:57
本文介绍了如何根据用户输入重新启动程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用基于用户输入的 if-test 重新启动程序.

I'm trying to restart a program using an if-test based on the input from the user.

此代码不起作用,但大致上是我所追求的:

This code doesn't work, but it's approximately what I'm after:

answer = str(raw_input('Run again? (y/n): '))

if answer == 'n':
   print 'Goodbye'
   break
elif answer == 'y':
   #restart_program???
else:
   print 'Invalid input.'

我想做的是:

  • 如果你回答 y - 程序从顶部重新启动
  • 如果您回答 n - 程序结束(该部分有效)
  • 如果您输入其他任何内容,它应该打印无效输入".请输入 y 或 n...' 或其他内容,然后再次询问您是否有新输入.

我非常接近带有while true"循环的解决方案,但是无论您按什么,程序都会重新启动(n 除外),或者无论您按什么都退出(y 除外).有什么想法吗?

I got really close to a solution with a "while true" loop, but the program either just restarts no matter what you press (except n), or it quits no matter what you press (except y). Any ideas?

推荐答案

试试这个:

while True:
    # main program
    while True:
        answer = str(input('Run again? (y/n): '))
        if answer in ('y', 'n'):
            break
        print("invalid input.")
    if answer == 'y':
        continue
    else:
        print("Goodbye")
        break

内部 while 循环循环直到输入是 'y''n'.如果输入是 'y',while 循环再次开始(continue 关键字跳过剩余的代码并直接进入下一次迭代).如果输入是'n',程序结束.

The inner while loop loops until the input is either 'y' or 'n'. If the input is 'y', the while loop starts again (continue keyword skips the remaining code and goes straight to the next iteration). If the input is 'n', the program ends.

这篇关于如何根据用户输入重新启动程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆