I am learning python and already know how to add new items to a list by myself with append. I don't know the code to ask the user for a number and add this to the list.
Thanks in advance.
Marloes
I am learning python and already know how to add new items to a list by myself with append. I don't know the code to ask the user for a number and add this to the list.
Thanks in advance.
Marloes
Try the below code:
x = list() # Your list
x.append(1) # Appended by you
user = int(input("Enter Number")) #User Input
x.append(user) # Appended user input
print(x)
some_List = [] # an empty list
for i in range(3): # a for-loop with 3 iteration
userInp = input("Enter a str to add to the list: ") # take the inp from user
some_List.append(userInp) # append that input to the list
print(some_List) # print the list
OUTPUT:
Enter a str to add to the list: 1
Enter a str to add to the list: a
Enter a str to add to the list: 2
['1', 'a', '2']
Try this one in Python3
listname = []
inputdata = input("enter anything : ")
listname.append(inputdata)
print(inputdata)
You can use the inbuilt method 'input' to ask for input from the user.
But remember one important thing, that whatever you will receive from that will be of the type str so make sure that you convert it according to your use case.
number_list = list()
number = input("Enter Number: ")
# now for your use case since you are dealing with numbers, convert the input into int
number = int(number)
number_list.append(number)
This should work:
your_list.append(int(input("Enter Number:")))
The append()
adds to the end of your_list
.
The input()
requests a number from the user. It will be converted to an integer.
Note: the code does not checks the user gave you an actual number.
Try this:
my_list = ['number', 6] # a list
user_input = input("Type something: ")
my_list.append(user_input)
print(my_list) # Output: ['number', 6, user_input]