python - 为什么我的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 循环会继续要求输入,即使它符合条件。
解决方案
不要使用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"
总是,无论如何,它总是 与一个命题不同,这不是与第一个相反的布尔值,而是正如你所说的,如果第二个你没有那个问题True
type
if
if
if
推荐阅读
- java - ArrayIndexOutOfBoundsException 对于我没有声明其大小的数组。我该怎么办?
- python - 为什么 Python 有 @property 装饰器时有 __set__ / __get__ 和 __setattr__ / __getattr__?
- javascript - 如何修复错误:WHERE 参数“id”具有无效的“未定义”值
- python - 在 ctor 和 Python 中的类定义中设置变量有什么区别?
- security - 为什么我需要 sudo 的 tty?要求它有什么安全好处?
- javascript - 添加和移除组件的 onClick 函数
- javascript - 使用 @angular/fire 在 Prod 模式下将文档添加到 Firebase
- typescript - 具有通用接口的约束标识函数
- azure - az appconfig kv list --key 过滤器不适用于 * 通配符
- oauth-2.0 - OKTA:获取 403 - 禁止:访问被拒绝错误