有条件的错误输入行为

时间:2019-05-12 20:21:23

标签: python

如果用户未为性别输入mf,我试图将其重置。

GenderSelect = input("Are they male or female?(m/f)\n")

os.system("clear")
gerror = 1
while gerror == 1:
    os.system("cls")
    print("Create a name for your new friend.\n" + NameCreate + "\nHow old are they?\n" + str(AgeSelect))
    input("Are they male or female?(m/f)\n")
    if (GenderSelect.lower() == "m"):
        print("Name: " + NameCreate + "\nAge: " + str(AgeSelect) + "\nGender: Male\n")
        gerror = 0
    if (GenderSelect.lower() == "f"):
        print("Name: " + NameCreate + "\nAge: " + str(AgeSelect) + "\nGender: Female\n")
        gerror = 0
    if (not(GenderSelect.lower() == "f" GenderSelect.lower() == "m")):
        gerror = 1

Confirm = input("Is this correct?\n")

if(Confirm.lower() == "y" or Confirm.lower() == "yes"):

当我键入fm时,它会重置,但是如果我键入其他任何内容,它都不会重置。

2 个答案:

答案 0 :(得分:0)

几个问题:

  1. 对于相互排斥的事物,请使用elif而不是if
  2. gerror块中的最终if语句中,两个条件之间需要一个or。或只使用else

答案 1 :(得分:0)

这部分代码:

if (GenderSelect.lower() == "f"):
    print("Name: " + NameCreate + "\nAge: " + str(AgeSelect) + "\nGender: Female\n")
    gerror = 0
if (not(GenderSelect.lower() == "f" GenderSelect.lower() == "m")):
    gerror = 1

应为:

elif (GenderSelect.lower() == "f"):
    print("Name: " + NameCreate + "\nAge: " + str(AgeSelect) + "\nGender: Female\n")
    gerror = 0
else:
    gerror = 1