在Python中使用比较运算符

我正在自己学习Python,并遇到以下问题:

使用while获得4种动物的用户输入animal_name;在while循环条件下使用num_animals计数器;将名称附加到字符串变量all_animals;用户可以通过键入“退出”(检查;动物名称是否为“退出”并中断)来提早退出;循环结束时,输出all_animals的名称;退出循环后,如果animal_name为空,则打印“ no animals”。

我写了下面的代码,但是没有用。我不知道该怎么做才能使它工作。

animal_name = input("Put in 4 animal names in total per time or \"exit\" for break")
num_animals = 0
tot_animals = 4
all_names = (" ")

while num_animals <= tot_animals:
    print(num_animals, "now")
    num_animals += 1
    all_animals = animal_name

    if animal_name.lower() == ("exit"):
        break

    if animal_name == (" "):
        print("no animals")

print("names of all animals: ", all_animals)
评论
  • 念念不忘
    念念不忘 回复
    animal_name = input("Put in 4 animal names in total per time or \"exit\" for break")
    num_animals = 0
    
    tot_animals = 4
    
    all_names = ""
    
    while num_animals <= tot_animals:
        print(num_animals, "now")
        num_animals += 1
        all_animals += animal_name + "," # connect the name to all names.
    
        if animal_name.lower() == ("exit"):
            break
    
    if len(all_animals) == 0: # len is 0, then it's empty
        print("no animals")
    
    print("names of all animals: ", all_animals)
    

    查看代码中的注释。