Home > Blockchain >  how can I make name_animal print all at once
how can I make name_animal print all at once

Time:07-16

num_animals = 0
while num_animals < 4:

  name_animal = input("Name an animal: ").capitalize()
  if name_animal == "Exit":
      break
  else:
    num_animals  = 1
print(name_animal)

The output is only just one of the animals I want it to be all the animals.

CodePudding user response:

you should save the input in a variable. You now set name_animal to your input everytime the while runs. But on every new while loop it get overwrited! save your output to a variable, for instance a list.

num_animals = 0
my_name_list = []

while num_animals < 4:

name_animal = input("Name an animal: ").capitalize()
if name_animal == "Exit":
    break
else:
    my_name_list.append(name_animal) # <-- we append the name to the list
    num_animals  = 1
print(my_name_list)
# or loop over my_name_list and print every element like this:
for name in my_name_list:
    print(name)

CodePudding user response:

You can use a data structure like a list for salve the inputs:

num_animals = 0
animals_list = []
while num_animals < 4:
    name_animal = input("Name an animal: ").capitalize()
    animals_list.append(name_animal)
    if name_animal == "Exit":
        break
    else:
        num_animals  = 1
print(animals_list)

CodePudding user response:

Here's one way that you could do this:

num_animals = 0
animal_names = [ '', '', '', '']
while num_animals < 4:

  name_animal = input("Name an animal: ").capitalize()
  if name_animal == "Exit":
      break
  else:
    animal_names[num_animals] = name_animal
    num_animals  = 1
print('Animal Names')
print('1: ', animal_names[0])
print('2: ', animal_names[1])
print('3: ', animal_names[2])
print('4: ', animal_names[3])

CodePudding user response:

Try this code snippet to see if you can follow, or have any further questions.


num_animals = 0
animals = []

while num_animals < 4:

  name = input("Name an animal: ").capitalize()
  if name == "Exit":
      break
  else:
    animals.append(name)
    num_animals  = 1
print(*animals)

Running interactively:

Name an animal: dog
Name an animal: cat
Name an animal: bird
Name an animal: mice
Dog Cat Bird Mice        # <---- all output in one line 

Alternatively you can do this as well:

animals = input('Enter four animals separated by space: ').split()
animals = ' '.join(name.capitalize() for name in animals)
print(animals)
  • Related