Python 使用while循环不断提示用户进行布尔输入,但在满足参数后仍会重复

Python 使用while循环不断提示用户进行布尔输入,但在满足参数后仍会重复,python,operator-keyword,Python,Operator Keyword,如果用户没有输入True或False,我想继续要求用户输入isMale。 但是,即使我输入True或False,while循环仍会不断询问。我不知道为什么 name = input("Name: ") age = int(input("Age: ")) isMale = bool(input("Male? ")) while (isMale != True) or (isMale != False): #Is this correct

如果用户没有输入
True
False
,我想继续要求用户输入
isMale
。 但是,即使我输入
True
False
,while循环仍会不断询问。我不知道为什么

name = input("Name: ")
age = int(input("Age: "))
isMale = bool(input("Male? "))

while (isMale != True) or (isMale != False): #Is this correct?
    print("Wrong Input. Please type True/False")
    isMale = bool(input("Male? "))

if(isMale == True):
    print("His name is "+ name)
    print("He is {input} years old.".format(input= age))
    print("He is a Male")

elif(isMale == False):
    print("Her name is " + name)
    print("She is {input} years old.".format(input= age))
    print("She is a Female")

这是一个简单的解决方案,但让我解释一下,当您将输入转换为布尔值时,如果输入为空,则将是
false
,如果输入包含的内容将是
true
,无论字符串如何,都将始终是
true
,因此在这种情况下,我决定创建变量并初始化它到
false
,如果其中一个条件的计算结果为
true
,则称为
notValid
的变量将为
false

我添加了一些字符串方法,可以帮助您格式化输入,这些方法是
strip()
,以删除额外的空格,以及
title()
,它们将输入大写

而且,所有的条件都没有在和输入之间进行检查,这是字符串和布尔值的形式,我将
isMale==True
更改为
isMale==True'
,因为两者都是字符串,比较起来很容易

例子
@夸姆拉纳,我想我把那部分说对了。我试着把它改成这样,但它甚至接受错误的输入,并自动假设isMale是真的,这是否回答了你的问题@frdspuzi bool('True')和bool('False')都将为True,因为两个字符串的长度都不是0。我认为问题源于'bool(input(…)'。它只会返回真或假,而不会返回其他任何东西。您可能需要自己的转换,而不是python的“Truthy”和“Falsy”概念。
name = input("Name: ")
age = int(input("Age: "))
isMale = input("Male? ").strip().title()
notValid = True

if(isMale == 'True'):
    print("His name is "+ name)
    print("He is {input} years old.".format(input= age))
    print("He is a Male")
    notValid = False

elif(isMale == 'False'):
    print("Her name is " + name)
    print("She is {input} years old.".format(input= age))
    print("She is a Female")
    notValid = False

while notValid:
    if (isMale != 'True') or (isMale != 'False'):
        print("Wrong Input. Please type True/False")
        isMale = input("Male? ").strip().title()
    else:
        notValid = False