Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add elements to a List in python?

I'm working on this task in python, but I'm not sure if I'm adding the elements to a list the right way. So basically I'm suppose to create a create_list function the takes the size of the list and prompt the user for that many values and store each value into the list. The create_list function should return this newly created list. Finally the main() function should prompt the user for the number of values to be entered, pass that value to the create_list function to set up the list, and then call the get_total function to print the total of the list. Please tell me what I'm missing or doing wrong. Thank you so much in advance.

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()
like image 224
HenryDev Avatar asked Mar 20 '16 00:03

HenryDev


2 Answers

In main you created empty list, but didn't assign create_list result to it. Also you should cast user input to 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()
like image 144
Mikhail Gerasimov Avatar answered Oct 06 '22 18:10

Mikhail Gerasimov


You must convert inputs to integer. input() returns a string object. Just do

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

And with every input you want to use as integer.

like image 41
Mr. E Avatar answered Oct 06 '22 18:10

Mr. E