首页 > 解决方案 > 为什么我的while循环会再次要求输入,即使它符合条件

问题描述

class volunteer:
    def __init__ (self, name, age, type, hourContribution):
        self.__name = name
        self.__age = age
        self.__type = type
        self.__hourContribution = hourContribution

这是志愿者班

check = True
name = input("Name of volunteer? ")
age = int(input("Age? "))
type = input("Type of volunteer ('F/P/E/T'): ")
type = type.lower()
while check != False:
    if type == "f" or type == "p" or type == "e" or type == "t":
        check = False
    elif type != "f" or type != "p" or type != "e" or type != "t":
        print ("Invalid type! Please enter again!")
        type = input("Type of volunteer ('F/P/E/T'): ")

hourCont = int(input("Contribution hour? "))
while hourCont <= 0:
    print ("Invalid value! Please enter again!")
    hourCont = int(input("Contribution hour? "))

newGroup.addVolunteer(volunteer(name, age, type, hourCont))
print ("... Volunteer has been added successfully.")

我不明白为什么第一个 while 循环会继续要求输入,即使它符合条件。

标签: pythonwhile-loop

解决方案


不要使用type它作为builtin获取变量类型的名称。你可以简化你的if条件和你的while循环以获得与你其他人相同的结构while

volunteer_type = input("Type of volunteer ('F/P/E/T'): ").lower()
while volunteer_type not in "fpet":
    print("Invalid type! Please enter again!")
    volunteer_type = input("Type of volunteer ('F/P/E/T'): ").lower()

你也有一个错误,但是由于你是如何编写代码的,你看不到它:type != "f" or type != "p" or type != "e" or type != "t"总是,无论如何,它总是 与一个命题不同,这不是与第一个相反的布尔值,而是正如你所说的,如果第二个你没有那个问题Truetypeif ifif


推荐阅读