python重复程序而为真 [英] python repeat program while true

查看:19
本文介绍了python重复程序而为真的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户输入 y/n 时,我试图让我的程序重复,但是我对如何在这种类型的输入中使用 while true 感到困惑,下面是一些代码.

I am attempting to make my program repeat when the user inputs y/n, however I am confused on how to use a while true with this type of input, below is some code.

again = input("Would you like to play again? enter y/n:  ")
if again == "n":
    print ("Thanks for Playing!")
    quit

if again == "y":
    print ("Lets play again..")
    ????

此外,如果用户输入不同的字符,我想执行 else 语句,但考虑到我有 2 个不同的 if 语句,我不确定如何进行.

Also, I want to do an else statement if the user enters in a different character, but am unsure on how to go about that considering I have 2 different if statements.

推荐答案

当您编写独立的 Python 程序时,最好使用 main 函数.它允许您轻松添加一些单元测试,使用其他模块中的函数或类(如果您导入它们)等.

When you're writing a standalone Python program, it’s a good practice to use a main function. it allows you to easily add some unit tests, use your functions or classes from other modules (if you import them), etc.

如果您必须检查某个条件是否满足以防其他条件不满足,并根据哪个条件为真执行一些操作,则可以使用 if...elif...else 语句.

If you have to check if some condition is satisfied in case some other condition is not satisfied, and perform some actions depending on which condition is true, you can use an if…elif…else statement.

另外,请注意,在这种情况下,您不能为您的程序使用 input() 函数.你真正想在这里使用的是 raw_input.这两个函数之间的区别在于 raw_input() 将始终返回一个字符串,而 input() 将评估用户的输入,就好像它是写在您的代码中而不是 input() 中一样.因此,如果用户输入y"(带引号),则字符串对象将存储为变量的值.但是如果用户输入 y(不带引号),input() 将尝试评估它,如果 y 未定义,则会抛出错误.

Also, please note that you cannot use the input() function for your program in this case. What you really want to use here is raw_input. The difference between these two functions is that raw_input() will always return a string and input() will evaluate user’s input as if it was written in your code instead of input(). So, if the user enters "y" (with the quotation marks), then a string object is stored as the value for the variable. But if the user enters y (without the quotation marks), input() will try to evaluate this and an error will be thrown if y is not defined.

您可以在此处阅读有关此主题的更多信息.

You can read more on this subject here.

def main():
    while True:
        again = raw_input("Would you like to play again? Enter y/n: ")

        if again == "n":
            print ("Thanks for Playing!")
            return
        elif again == "y":
            print ("Lets play again..")
        else:
            print ("You should enter either "y" or "n".")

if __name__ == "__main__":
    main()

这篇关于python重复程序而为真的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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