继续使用while循环提示用户输入布尔值,但在满足参数后仍会重复

问题描述

如果他们没有输入isMaleTrue,我想继续向用户询问False。 但是,即使我输入TrueFalse时,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,则称为{{ 1}}将是notValid

我添加了一些字符串方法,可帮助您格式化输入false以删除多余的空格,以及strip()来格式化输入。

而且所有条件都不能在输入和输入之间进行检查,输入和输出都是字符串和布尔值的形式,所以我将tittle()更改为isMale == True是因为它们都是字符串,所以比较起来很容易。

示例

isMale == 'True'