class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
name = input("inter name ")
for i in p1:
if name in i.name:
print(true)
我想让程序检查name是否在Person类中,如果有,打印为true
您不需要使用for
来检查单个项目属性。你只需要,
p1 = Person("John", 36)
person_name = input("inter name ")
if p1.name == person_name:
print(True) # Boolean True is capitalized. "true" is undefined.
else:
#sth else
如果您想再试一次,可以使用while循环来完成:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def get_name(self):
return self.name
def get_age(self):
return self.age
def main():
p1 = Person("John", 36)
while input != 'quit':
name = input("Enter name or 'quit': ")
if name == p1.get_name():
print(f"{p1.get_name()} was the right name!")
print(f"and {p1.get_name()} is {p1.get_age()} years old.")
break
if name == "quit":
break
else:
print(f"{name} was the wrong naem, try another name again.")
if __name__ == "__main__":
main()