Turr
Turr

Reputation: 13

Unable to separate names in a variable

I'm very new to programming.

I can't seem to separate names taken from input into a single variable other than letter by letter with .split()

My code looks like this:

num_animals = 0
all_animals = ("")
while num_animals < 4:
    animal_name = input("Enter the name of 4 animals: ")
    if animal_name.lower() == "exit":
        break
    elif animal_name.isalpha():
        print("Thats good, added!")
        num_animals += 1
        all_animals += animal_name
    elif animal_name.isalpha() == False:
        print("Hmm, that's probably not an animal.")
print("You have entered", num_animals, "animals as follows", str(all_animals)+".") #couldn't figure out how to separate the list of animals

Upvotes: 1

Views: 30

Answers (2)

aloisdg
aloisdg

Reputation: 23521

I think the array is the most suited answer. If you are looking for a string-based solution, here you go:

num_animals = 0
all_animals = ""
delimiter = " " # we create a delimiter
while num_animals < 4:
    animal_name = input("Enter the name of 4 animals: ")
    if animal_name.lower() == "exit":
        break
    elif animal_name.isalpha():
        print("Thats good, added!")
        num_animals += 1
        all_animals += animal_name + delimiter # we add the delimiter after each entry
    elif animal_name.isalpha() == False:
        print("Hmm, that's probably not an animal.")

# oh no we have a trailing delimiter! Note that you could remove it with `all_animals.strip()`
print("You have entered", num_animals, "animals as follows", all_animals, ".")

Try it online

Upvotes: 0

aloisdg
aloisdg

Reputation: 23521

Do you know how to use an array? If not, it is time to learn about it!

num_animals = 0
all_animals = [] # lets create an array
while num_animals < 4:
    animal_name = input("Enter the name of 4 animals: ")
    if animal_name.lower() == "exit":
        break
    elif animal_name.isalpha():
        print("Thats good, added!")
        num_animals += 1
        all_animals.append(animal_name) # lets add an animal to the array
    elif animal_name.isalpha() == False:
        print("Hmm, that's probably not an animal.")
# `join()` is use to concat items of an array
print("You have entered", num_animals, "animals as follows", ",".join(all_animals) +".")

Try it Online

Upvotes: 1

Related Questions