'Appending user input to a list not working
I am trying to take user input and append all numbers to a list. However the output I am getting just a blank list with nothing inside.
while True:
my_add = input("Give me numbers and I will add them to the list. Enter 'q' to quit.")
my_list = []
if my_add == 'q':
break
else:
my_list.append(my_add)
print(my_list)
Solution 1:[1]
my_list = []
while True:
my_add = input("Give me numbers and I will add them to the list. Enter 'q' to quit.")
if my_add == 'q':
break
else:
my_list.append(my_add)
print(my_list)
my_list was set to empty list [] at every loop iteration
Solution 2:[2]
Remove the variable my_list from the while loop as it is resetting on every iteration.
my_list = []
while True:
my_add = input("Give me numbers and I will add them to the list. Enter 'q' to quit.")
if my_add == 'q':
break
else:
my_list.append(my_add)
print(my_list)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Stefanos Asl. |
| Solution 2 | Dan Wilstrop |
