简体   繁体   中英

Running while loop from user input and print list after that

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.

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=', ')

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(", "))

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM