Home > Net >  Printing list of user inputted names
Printing list of user inputted names

Time:03-20

Hey all was hoping for some help with this piece of code. The code needs the user to input a name until done is typed and it should provide an output of Hello (name) for every name inputted. Below is the code I have written:

names = input("Enter a name:")
list = []

while True:
  
  if names == 'done':
    break
  
  list.append(names)
    
print("Hello",list)

After I run the code and enter a name nothing happens, it won't allow me to input another name or even done and I have to shut it down. Any help or tips would greatly appreciated. Thanks!!

CodePudding user response:

Move names = input("Enter a name:") into the while True: block. This will mean that input is requested for every iteration until the input is equal to 'done'

CodePudding user response:

This should work:

list_of_names = []
while True:
  names = input("Enter a name:")  
  if names == 'done':
    break
  print("Hello",names)
  list_of_names.append(names)

With this the program keeps running until you input done and for every iteration it prints the current value of names

CodePudding user response:

There are two issues:

  1. You need to move the input() call inside the while loop, so that you can accept multiple names.
  2. list is not a good variable name, as it shadows the list() builtin.

Here is a code snippet that resolves both issues:

name = ""
data = []
while name != 'done':
  name = input("Enter a name:")
  if name != 'done':
    print("Hello", name)
    data.append(name)

CodePudding user response:

First, you need to initialize the global variables that you will need:

names = ''

list1= [] I change the name from list to list1 since its a keyword in python.

Second, take in the input:

while names != 'done': names = input("Enter a name:") list1.append(names)

Since done will be added to the list we need to remove it:

list1.remove('done')

Code:

names = ''
list1= []

while names != 'done':
     names = input("Enter a name:")
     list1.append(names)

list1.remove('done')

for x in names: 
     print('Hello',x)
  • Related