-3

I want to all the values to add up but the total value comes out to be none. please help.

def main():

    #local variable
    number = 0
    num_list = []

    #user inputs numb3er
    number = int(input('Enter number: '))
    num_list.append(number)
    print_num(number)
    print('The total value of the list is: ', sum_list(num_list))


def print_num(n):
    num_list = []
    if n > 1:
        print_num(n - 1)
        num_list.append(n)

        print(n)
    return num_list

def sum_list(num_list):
    if not num_list:
        return 0

    return num_list[0] + sum_list(num_list[1:])


main()

i currently adjusted what was recommended but it still doesn't sum up the values

1 Answers1

1

num_list is never changed. So call to sum_list() returns None as you asked in

def sum_list(num_list): 
    if not num_list:
        return

Just add a num_list.append(number) after the user input. Take care by the way, the end of your sum_list() function is badly indented, it should be:

def sum_list(num_list): 
    if not num_list:
        return

    return num_list[0] + sum_list(num_list[1:])
Tim
  • 2,052
  • 21
  • 30
  • hey Tim i'm new to python im a bit confused where i should be adding num_list.append(number) thank you – Tadeo Ayala Nov 23 '19 at 20:14
  • I said after the user input. That means before the first `print()` :) – Tim Nov 23 '19 at 20:28
  • ok so i added a num_list.appends(number) but it jsut returns the value of the number i entered i want it to sum all the values the give me a total. – Tadeo Ayala Nov 23 '19 at 20:31
  • Return `0` in `sum_list()`. – Tim Nov 23 '19 at 20:37
  • You have multiple syntax errors by the way. Remove the `, sep =' '` in your print. – Tim Nov 23 '19 at 20:39
  • Last, your code ask for a single user input. Your number list will always get a single number. Consider adding a loop which wraps the user inputs and `list.append()`. – Tim Nov 23 '19 at 20:41
  • You are trying to reinvent the wheel with this code. Why not use Python's `sum()` to reduce your list, as in `sum(num_list)`? – Tim Nov 23 '19 at 20:44
  • ok thank you i will give it a shot. – Tadeo Ayala Nov 23 '19 at 20:51
  • i also edited the code above – Tadeo Ayala Nov 23 '19 at 20:52
  • You should not edit the code. Now the code is working so your question does not make sense anymore, so my answers neither. Please leave your original code untouched to respect your answerers work ;) please mark my answer as accepted instead. – Tim Nov 24 '19 at 06:43