简体   繁体   English

在python中追加列表+输入数据的验证

[英]Appending a list in python + Validation of inputted data

I'm having trouble adding items to a list from a user's input, I think you can see what I'm trying to do here, I want the user to be able to add items to a list, and have it displayed afterwards. 我在通过用户输入将项目添加到列表时遇到问题,我想您可以在这里看到我要执行的操作,希望用户能够将项目添加到列表中,然后将其显示出来。 Criteria: It must contain a FOR loop and some form of data validation. 准则:它必须包含一个FOR循环和某种形式的数据验证。

def main():
    num=int(input("How many values would you like in your list?"))
    for x in range(num)
        myList=[]
        newValue=input("Enter the text you would like to add")
        myList.append(newValue)
    print(myList)

The problem 问题

You are initializing the list every time as myList = [] inside the loop. 每次在循环内使用myList = []初始化列表。 Whatever data you appended is lost. 您添加的所有数据都会丢失。

Also, : is missing after range(num) . 另外, :range(num)之后丢失。

Solution

Simply initialize it outside the loop. 只需在循环外对其进行初始化。

def main():
    num=int(input("How many values would you like in your list?"))
    myList=[] # This needs to be initialized outside the loop 
    for x in range(num):
        newValue=input("Enter the text you would like to add")
        myList.append(newValue)
    print(myList)

if __name__ == '__main__':
    main()

try this! 尝试这个!

def main():
    num=int(raw_input("How many values would you like in your list? "))
    myList=[]
    for x in range(num):
        newValue = raw_input("Enter the text you would like to add ")
        myList.append(newValue)
    print(myList)

One problem in your code is that for needs : at the end. 您的代码中的一个问题是需求:最后。

But the main one is that you are reseting your myList to an empty list at the start of each iteration... as a result, anything you input is going to be appended in an empty list (so the result of a single-valued list). 但是最主要的是,您要在每次迭代开始时将myList重置为一个空列表……结果,您输入的任何内容都将被追加到一个空列表中(因此,单值列表的结果)。

Well, you have multiple mistakes: 好吧,您有多个错误:

  • You are missing a colon in the for loop 您在for循环中缺少冒号

  • Since you reassign myList to an empty list every single iteration of the for loop, the list will only have one value in the end 由于您在for循环的每一次迭代中都将myList重新分配给一个空列表,因此该列表最后只会有一个值

  • You actually need to call the function 您实际上需要调用该函数

Thus the code becomes: 因此,代码变为:

def main():
    num=int(input("How many values would you like in your list?"))
    myList = []               # Create the list here instead
    for x in range(num):      # Colon is needed
        newValue = raw_input("Enter the text you would like to add: ")
        myList.append(newValue)
    print(myList)

main()                        # Call the function

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

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