Python - 来自用户的输入不被识别为" Y"或" N"

时间:2016-07-09 00:59:08

标签: python raw-input

我试图编写一个简单的程序,让自己在我的个人生活导致长时间休息之后重新回到python中。该计划的目的是做如下:

  • 要求用户输入一个等于5的数字(非常简单,我知道)
  • 检查用户输入的内容是否有效
  • 检查用户的输入是否等于5
  • 询问用户是否要再次运行该程序
  • 如果用户输入yY,则运行该程序,如果输入为nN
  • ,则退出该程序

导入os

askme = raw_input("Enter a number that is equal to 5: ")

def check_att(attrib):
    if int(attrib) == 5:
        os.system("cls")
        print "Yes, %s is equal to 5! Good job!" % attrib
        again = raw_input("Would you like to try again? (Y/N): ")
        print again
        if again == again.isalpha():
            if again == "y" or "Y":
                os.system("cls")
                print attrib
                print check_att(attrib)
            elif again == "n" or "N":
                os.system("exit")
        else:
            os.system("cls")
            not_alpha1 = raw_input("Sorry, that's not a valid answer. Would you like to try again? (Y/N): ")
            print not_alpha1
            if not_alpha1 == "y" or "Y":
                os.system("cls")
                print attrib
                print check_att(attrib)
            elif not_alpha1 == "n" or "N":
                os.system("cls")
    else:
        sorry = raw_input("Sorry, %s is not equal to 5. Try again? (Y/N): " % attrib)
        print sorry
        if sorry == sorry.isalpha():
            if sorry == "y" or "Y":
                os.system("cls")
                print attrib
                print check_att(attrib)
            elif sorry == "n" or "N":
                os.system("exit")
        else:
            os.system("cls")
            not_alpha = raw_input("Sorry, that's not a valid answer. Would you like to try again? (Y/N): ")
            print not_alpha
            if not_alpha == "y" or "Y":
                os.system("cls")
                print attrib
                print check_att(attrib)
            elif not_alpha == "n" or "N":
                os.system("cls")

print askme
print check_att(askme)

我遇到的问题是程序要求用户再次运行程序的部分。这是我运行代码时发生的事情:

Enter a number that is equal to 5: 5
5
Yes, 5 is equal to 5! Good job!
Would you like to try again? (Y/N): Y
Y
Sorry, that's not a valid answer. Would you like to try again? (Y/N): 

我不知道如何让程序将Y识别为有效输入。非常感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

而不是if again == "y" or "Y":,您需要:

if again == "y" or again == "Y":

或:

if again.lower() == 'y':

但是,使用如下的raw_input设置可能会更好:

while True:
    entry = raw_input("Enter a number that is equal to 5: ")
    if entry == 5:
        break
    else:
        print("That's not right, please try again.")

while循环的唯一出路是将其设为break;通过这种方式,你不必担心他们输入的内容。如果不是5,他们就不会去任何地方。

答案 1 :(得分:0)

if again == again.isalpha():

我认为这不是你想要的。 again.isalpha()返回True或False,因此将其与again的值进行比较是没有意义的。 你可能打算:

if again.isalpha():

此外,

if again == "y" or "Y":

这可能不符合你的想法。它有逻辑'或' 然后将“y”和“Y”的结果与again进行比较。它不是同义词 为了

if again == "y" or again == "Y":

这可能是你想要的。