1

I'm learning Python and usage of the stackoverflow so that's why this question might be trivial for you.

So; Code goal is to ask user names until user press enter. After that code should count how many names were given and then print list of the names.

Example

Enter a name:Jack
Enter a name:Dack
Enter a name:Nack
Enter a name:
Name count 3
Jack, Dack, Nack

I have created While true loop for name counting, but now I just can figure out how to simply print those names like in the above.

My code is:

count_names = 0

while True:
    given_names = input("Enter a name: ")
    
    if given_names == "":
            print(f"Name count {count_names}")
            break

    count_names += 1 

Result for that is:

Enter a name:Jack
Enter a name:Dack
Enter a name:Nack
Enter a name:
Name count 3

I can feel that the answer is right there but I just can't put my finger on it =/

Thanks again for the help.

JmP
  • 45
  • 5

4 Answers4

0

You can do it like this:

count_names = 0
names = []

while True:
    given_names = input("Enter a name: ")
    names.append(given_names)

    
    if given_names == "":
            print(f"Name count {count_names}")
            names.remove('')
            
            break

    count_names += 1

for name in names:
    print(name, end=', ')
Yasaman Shokri
  • 145
  • 1
  • 1
  • 11
0

Here is another way to print the result

count_names = 0
given_names, result = "abc", ""
while given_names != "":
    given_names = input("Enter a name: ")
    result += f"{given_names}, "
    count_names += 1 
    
print(f"Name count {count_names}")
print(result.rstrip(", "))
Abercrombie
  • 1,012
  • 2
  • 13
  • 22
  • This gives the answer in right format. Only changes what needed to do was set count_names = -1 so enter is not calculated and removed \n from the first print so there's no empty line between. Thanks Mate! – JmP Sep 29 '21 at 17:55
0

Using lists is the best idea in terms of simplicity. I also always use join() method to separate list elements by comma.

nameList = []

count = 0

while True:
    name = input('Enter a name: ')
    if name:
        nameList.append(name)
        count += 1
    else:
        print(f'Name count: {count}')
        print(', '.join(nameList))
        break
0

Try the below code, it will return as you want

    names = '' 
    count_names = 0 
while True:
    given_names = input("Enter a name: ")
    if given_names == "":
        print(f"Name count {count_names}")
        print(names[:-1])
        break
    names += given_names + ','
    count_names += 1
Haresh
  • 1
  • 2