簡體   English   中英

Python 循環從 class 創建對象,直到用戶說停止

[英]Python loop to create objects from class untill user says to stop

我正在嘗試從用戶可以通過輸入數據創建的 class 創建幾個對象。我在下面創建了一個示例代碼來說明我想要實現的目標。

class Person:
def __init__(self, Name, Age, City):
    self.Name = Name
    self.Age = Age
    self.City = City

Person1 = Person(str(input("Name ")), str(input("Age ")), str(input("City ")))
Person2 = Person(str(input("Name ")), str(input("Age ")), str(input("City ")))
Person3 = Person(str(input("Name ")), str(input("Age ")), str(input("City ")))
Persons = (Person1, Person2, Person3)


for person in Persons:
    print("Hello " + person.Name)
    print("You are " + person.Age)
    print("And live in " + person.City)

Person1、2 和 3 在哪里我實際上希望 python 要求用戶輸入此數據,直到該人不想再輸入任何數據為止。

目前我正在使用以下代碼來嘗試完成此操作:

class Person:
    def __init__(self, Name, Age, City):
        self.Name = Name
        self.Age = Age
        self.City = City

cont = True
entity = {str("Person" + 1)}
while True:
    entity = Person(str(input("Name ")), str(input("Age ")), str(input("City ")))
    cont = input("Continue? True of False ")

Persons = (entity)


for person in Persons:
    print("Hello " + person.Name)
    print("You are " + person.Age)
    print("And live in " + person.City)

我認為 while 循環會在這里起到作用,用戶可以說 True 或 False 讓 while 循環繼續直到用戶鍵入 False,但它似乎沒有這樣做,我在試圖弄清楚如何做到這一點。 Python 給了我一個錯誤:只能將 str(而不是“int”)與 str 連接起來,但我確信這里還有更多問題。 有人能幫助我嗎?

謝謝!

有人發布了這個,但由於某種原因,該評論被刪除了。 無論如何,這似乎奏效了。

 # class definition unchanged
class Person:
    def __init__(self, Name, Age, City):
        self.Name = Name
        self.Age = Age
        self.City = City

# using a list, because it's mutable
Persons = []

while True:
    entity = Person(str(input("Name ")), str(input("Age ")), str(input("City ")))

    # a different option for breaking the loop, commented out
    #if entity.Name == "":
    #    break

    # add the new person to the list
    Persons.append(entity)

    cont = input("Continue? Press Enter. Else F ")

    # check the input to decide whether to continue
    if cont == "False" or cont == "F" or cont == "f":
        break;

# output loop unchanged
for person in Persons:
    print("Hello " + person.Name)
    print("You are " + person.Age)
    print("And live in " + person.City)

謝謝大家幫助我!

暫無
暫無

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

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