简体   繁体   English

如何要求用户提供新商品并将其添加到列表(Python)

[英]How to ask user for new item and add this to list (Python)

I am learning python and already know how to add new items to a list by myself with append. 我正在学习python,并且已经知道如何使用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 在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. 但是请记住一件重要的事情,即您从中得到的任何东西都将是str类型的,因此请确保您根据用例进行转换。

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 . append()添加到your_list The input() requests a number from the user. input()向用户请求一个数字。 It will be converted to an integer. 它将被转换为整数。

Note: the code does not checks the user gave you an actual number. 注意:该代码不会检查用户给您的实际号码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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