Home > Blockchain >  How to add User Input (String) into a list?
How to add User Input (String) into a list?

Time:09-04

For some reason any user input isn't appended to the empty list. I'm not sure where I'm going wrong. This is an example to a larger issue I'm having. Any help would be appreciated. Thanks

list = []

print("Who wrote War and Peace?: ")
book1 = input()

for i in list:
    list.append(book1)
    print(f"Author: "   i)

CodePudding user response:

I see that you are trying to add an item to an empty list and using a for loop to access it but you are doing the opposite.

Another thing is you are using a formatted string to print the author's name. Remember when doing a formatted string, you use {} and just put the variable inside it instead of doing variable

my_list = []

print("Who wrote War and Peace?: ")
book1 = input('')

my_list.append(book1)

for i in my_list:
    print(f"Author: {i}")

CodePudding user response:

When you print out the value of list, Python interprets this as the list data-types. You can fix your issue by changing the variable name to something like l or my_list.

EDIT: On further notice, you are looping for every item in the list, but the list is empty, so the for-loop won't run.

CodePudding user response:

Welcome to StackOverFlow!

From my reproduction, there is no "i" value in list (its empty). Therefor the for loop is not triggering, nothing to loop over.

Reproduction:

user_input=(input("\nWhat is the airspeed velocity of a (European) unladen swallow?: "))
a=False
list = []
for i in list:
    a=True #if For Loop is triggered a is True and prints pass
    list.append(user_input)
    print(list)
if a is not True: #if For loop is not triggered then fail will be printed
    print('fail')
else:
    print('pass')

Results

What is the airspeed velocity of a (European) unladen swallow?: 24 mph
fail

In order to append to the list. Remove the for loop for the initial input.

user_input1=(input("\nWhat is the airspeed velocity of a (European) unladen swallow?: \n"))
list_ = []
list_.append(user_input1)

user_input2=(input("We are the Knights who say?: \n"))
for i in range(len(list_)):
    list_.append(user_input2)
    print(list_)

Results

What is the airspeed velocity of a (European) unladen swallow?: 
24 mph
We are the Knights who say?: 
Ni
['24 mph', 'Ni']

As Neurotricity said dont use list as a variable for a list (I usually put a "_" at the end). (see their comment for more detail)

Cheers!

  • Related