而使用比较运算符

2024-05-14 10:42:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在自学Python,有以下问题:

这是我的“清单”:

  • 使用while循环获取4个动物的用户输入animal_name
  • 在while循环条件中使用计数器num_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)

来自@Zhd Zilin的改进代码


Tags: 代码用户namein名称namesexitall
3条回答
num_animals = 0
tot_animals = 4
all_names = ""
while num_animals <= tot_animals: # will execute 5 times, 0,1,2,3,4...
    # move into loop, everytime it run, it will ask you input
    animal_name = input("Put in 4 animal names in total per time or \"exit\" for break\n") 
    print(num_animals, "now")
    num_animals += 1

    # when input is exit, quit the program
    if animal_name.lower() == "exit":
        break

    all_names += animal_name + "," # Move this line under break, if "exit" input, don't add it to names, connect the name to all names.

if len(all_names) == 0: # len is 0, then it's empty
    print("no animals")

print("names of all animals: ", all_names)

更新程序,请参阅while语句行的注释

这应该是可行的

num_animals = 0
tot_animals = 4
all_names = [] # Store the names in a list instead

print("Enter names of 4 animal or type 'exit' to stop.")

while num_animals < tot_animals:
    print("Input an animal name")
    animal_name = input(":")
    if animal_name.lower() == "exit":
        break
    else:
        num_animals += 1
        all_names.append(animal_name) # Use .append() method to element to list

if len(all_names) != 0:
    print("All animals:",tot_animals,all_names)
else:
    print("No animals")

另外,要使您的代码干净,改进安排以便于调试

num_animals = 0
tot_animals = 4
all_names = ""

while num_animals <= tot_animals:
    # Doing this within the while loop will prompt the user for input
    # each iteration of the loop.
    animal_name = input("Put in 4 animal names in total per time or \"exit\" for break")
    if animal_name.lower() == "exit":
        break

    num_animals += 1
    # This will append the user's input to all_names
    all_names += animal_name + " "

if len(all_names) == 0:
    print("no animals")
else:
    print("names of all animals: ", all_names)

相关问题 更多 >

    热门问题