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

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

问题描述

我试图让我的程序在用户输入y / n时重复,但是我对如何使用这种类型的输入时使用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语句,但我不确定考虑到我有两个不同的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程序时,它是使用主要功能的好习惯。它允许您轻松添加一些单元测试,使用您的函数或来自其他模块的类(如果您导入它们)等。

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.

你可以详细了解此处

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天全站免登陆