11

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()
HenryDev
  • 4,685
  • 5
  • 27
  • 64
  • 1
    you should call main with `if __name__ == '__main__': main()` – Jules G.M. Mar 20 '16 at 00:19
  • how to do that? I'm still new to python. Thanks! – HenryDev Mar 20 '16 at 00:20
  • 1
    Why do you think that you might be doing something wrong? You give no indication of what you think the problem might be, or how the current behavior is different from the expected behavior. – DaoWen Mar 20 '16 at 00:20
  • just replace the `main()` with `if __name__ == '__main__': main()` – Jules G.M. Mar 20 '16 at 00:21
  • @DaoWen when I know I'm doing something wrong because when I run the program I get the message "Please enter a number of values" and after entering the number I get an error message and not sure why – HenryDev Mar 20 '16 at 00:21
  • aside from that, you don't need to actually save the values to add them to the total (unless that's what your homework is asking you to do). – Jules G.M. Mar 20 '16 at 00:22
  • 4
    "I get an error message and not sure why" **then include the error message in question** – Tadhg McDonald-Jensen Mar 20 '16 at 00:22
  • @Julius - if you're going to give advice like that to someone who's obviously new to python (and probably programming in general), you should really explain *why* they should do what you suggest, or at least link to an explanation. – DaoWen Mar 20 '16 at 00:22
  • @Julius I just did what you suggested but didnt work – HenryDev Mar 20 '16 at 00:22
  • please include include the error message – Jules G.M. Mar 20 '16 at 00:23
  • for my other suggestion : http://stackoverflow.com/questions/419163/what-does-if-name-main-do – Jules G.M. Mar 20 '16 at 00:24
  • @TadhgMcDonald-Jensen my issue was that I needed to make user user' input is an integer by doing: number_of_values = int(input('Please enter number of values: ')) – HenryDev Mar 20 '16 at 00:26
  • 1
    @xpng - You missed the point of our comments. If you got an error message, then you should have included that in the question so that people are better able to help you. What you did is like going to the doctor and saying, "Please give me medicine!" but not bothering to tell the doctor that your ear is hurting. Yes, the doctor will probably eventually figure out what's wrong, but describing the *symptoms* that you've noticed makes it a lot easier! Same thing here. – DaoWen Mar 20 '16 at 00:30
  • @DaoWen, do you mind If I link to that for other posters that do not include error message? – Tadhg McDonald-Jensen Mar 20 '16 at 00:31
  • @DaoWen I'll take your advice for future question. Thanks DaoWen! – HenryDev Mar 20 '16 at 00:31
  • 1
    @TadhgMcDonald-Jensen - I officially release my comments on this question into the public domain. Feel free to copy and paste it—using it modified or modified—without attribution. (That's probably easier than trying to link back here, and I don't care about getting credit for the analogy. I'm just glad someone found it useful!) – DaoWen Mar 20 '16 at 00:34

7 Answers7

11

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()
Mikhail Gerasimov
  • 36,989
  • 16
  • 116
  • 159
2

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.

Mr. E
  • 2,070
  • 11
  • 23
  • your answer is so close :). I dont get any more errors, but for the total sum I get 0. Any ideas why? – HenryDev Mar 20 '16 at 00:25
  • Cause `myList` should be a global variable in `create_list` to actually modify it. Also `myList` should be declared outside `main()` – Mr. E Mar 20 '16 at 00:30
  • 1
    or you could catch the return value as a local like in the other answers, keeping `myList` a global variable is another implementation. – Tadhg McDonald-Jensen Mar 20 '16 at 00:33
1

First Problem is you are not passing myList to create_list function, so myList inside of main is not going to get updated.

If you want to create a list inside the function and return it, and then get a total for that list, you need to first store the list somewhere. parse the inputs as integer, also, always do if __name__ == '__main__':. The Following code should work and print the correct result :)

def main():
    number_of_values = int(input('Please enter number of values: '))
    myList = create_list(number_of_values)
    print('the list is: ', myList)
    print('the total is ', get_total(myList))

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

def create_list(number_of_values):
    myList = []
    for num in range(number_of_values):
        num = int(input('Please enter number: '))
        myList.append(num)
    return myList
if __name__ == '__main__':
    main()
Namit Singal
  • 1,506
  • 12
  • 26
1

An alternative method to the posted solutions could be to have one function that creates your said list and finds the total of that list. In the solution, the map function goes through all the values given to it and only keeps the integers (The split method is used to remove commas and spaces from the values). This solution will print your list and values, but will not return any said value, so it will produce a NoneType, if you were to examine the function at the end.

    def main():
        aListAndTotal()

        #Creates list through finding the integers and removing the commas
        #For loop iterates through list and finds the total
        #Does not return a value, but prints what's stored in the variables

    def aListAndTotal():
        myList = map(int, input("Please enter number of values: ").split(","))
        total = 0
        for num in myList:
            total += num
        print ("The list is: ", myList)
        print ("The total is: ", total)

    if __name__ == "__main__":
        main()
1
List is one of the most important data structure in python where you can add any type of element to the list.

a=[1,"abc",3.26,'d']

To add an element to the list, we can use 3 built in functions:
a) insert(index,object)
This method can be used to insert the object at the preferred index position.For eg, to add an element '20' at the index 1:
     a.index(1,20)
Now , a=[1,20,'abc',3.26,'d']

b)append(object)
This will add the object at the end of the list.For eg, to add an element "python" at the end of the list:
    a.append("python")
Now, a=[1,20,'abc',3.26,'d','python']

c)extend(object/s)
This is used to add the object or objects to the end of the list.For eg, to add a tuple of elements to the end of the list:
b=(1.2, 3.4, 4.5)
a.extend(b)
Now , a=[1,20,'abc',3.26,'d','python',1.2, 3.4, 4.5]

If in the above case , instead of using extend, append is used ,then:
a.append(b)
Now , a=[1,20,'abc',3.26,'d','python',(1.2, 3.4, 4.5)]
Because append takes only one object as argument and it considers the above tuple to be a single argument that needs to be appended to the end of the list.
Akhil Rao
  • 11
  • 1
0

You need to assign the return value of create_list() to a variable and pass that into get_total()

myList = create_list()
total = get_total(myList)

print("list " + str(myList))
print("total " + str(total))
Phuo
  • 221
  • 2
  • 5
0

Adding an element to an existing list in python is trivial. Assume who have a list names list1

>>> list1 = ["one" , "two"]

>>> list1 = list1 + "three"

this last command will add the element "three" to the list. This is really simple, because lists are objects in python. When you print list1 you get:

["one" , "two" , "three"]

Done

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Alex
  • 1