如何在python中向List添加元素?

Hen*_*Dev 5 python python-3.x

我正在python中完成这个任务,但我不确定我是否正确地将这些元素添加到列表中.所以基本上我假设创建一个create_list函数,它获取列表的大小并提示用户输入那么多值并将每个值存储到列表中.create_list函数应该返回这个新创建的列表.最后,main()函数应该提示用户输入的值的数量,将该值传递给create_list函数以设置列表,然后调用get_total函数来打印列表的总和.请告诉我我错过了什么或做错了什么.非常感谢你提前.

def main():
    # create a list
    myList = []

    number_of_values = input('Please enter number of values: ')

    # Display the total of the list  elements.
    print('the list is: ', create_list(number_of_values))
    print('the total is ', get_total(myList))

    # The get_total function accepts a list as an
    # argument returns the total sum of the values in
    # the list

def get_total(value_list):

    total = 0

    # calculate the total of the list elements
    for num in value_list:
        total += num

    #Return the total.
    return total

def create_list(number_of_values):

    myList = []
    for num in range(number_of_values):
        num = input('Please enter number: ')
        myList.append(num)

    return myList

main()
Run Code Online (Sandbox Code Playgroud)

Mik*_*mov 9

main您创建的空列表中,但没有为其分配create_list结果.您还应该将用户输入转换为int:

def main():
    number_of_values = int(input('Please enter number of values: '))  # int

    myList = create_list(number_of_values)  # myList = function result
    total = get_total(myList)

    print('the list is: ', myList)
    print('the total is ', total)

def get_total(value_list):
    total = 0
    for num in value_list:
        total += num
    return total

def create_list(number_of_values):
    myList = []
    for _ in range(number_of_values):  # no need to use num in loop here
        num = int(input('Please enter number: '))  # int
        myList.append(num)
    return myList

if __name__ == '__main__':  # it's better to add this line as suggested
    main()
Run Code Online (Sandbox Code Playgroud)