簡體   English   中英

為什么我的while循環會再次要求輸入,即使它符合條件

[英]Why my while loop will ask for input again even it is match the condition

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

這是志願者的class

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 循環會繼續要求輸入,即使它符合條件。

不要使用type ,因為它是獲取變量類型的builtin名稱。 您可以簡化if條件和while循環以獲得與 yoru other 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"總是是的,無論是哪種type ,它總是與一個命題不同,即if不是與第一個if相對的True ,但正如你所說的那樣, if你沒有那個問題

我假設使用函數會使這段代碼更簡單:


def get_positive(message):
    while True:
        try:
            value = int(input(message))
            if value <= 0:
                print("Not positive value")
                continue
        except ValueError:
            print("Wrong value")
            continue
        return value

def get_type(message, possible_values):
    spv = set(list(possible_values.lower()))
    while True:
        value = input(message)
        if value.lower() in spv:
            return value
        print("Wrong value")


name = input("Name of volunteer? ")
age = get_positive("Age? ")
typ = get_type("Type of volunteer ('F/P/E/T'): ", "fpet")
hourCont = get_positive("Contribution hour? ")
newGroup.addVolunteer(volunteer(name, age, typ, hourCont))
print ("... Volunteer has been added successfully.")

PS 不要使用“類型”變量,因為這是 python 自己的保留字之一

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM