Anirudh Gottiparthy Anirudh Gottiparthy - 9 days ago 13
Python Question

Add numbers in a list using recursion in Python

The given template is:

def total(lst):
return (
#### YOUR CODE HERE ####
#### DO NOT WRITE CODE OUTSIDE OF THIS ####
#### RETURN STATEMENT ####
)

def getValue():
try:
return int(input())
except:
return None

v = getValue()
myLst = [v]
while v != None:
v = getValue()
if v != None:
myLst.append(v)
print(total(myLst))


I have gotten this:

def total(lst):
return (
if lst ==1:
lst[0]
else:
lst[0]+total(lst[0:])
)

def getValue():
try:
return int(input())
except:
return None

v = getValue()
myLst = [v]
while v != None:
v = getValue()
if v != None:
myLst.append(v)
print(total(myLst))


The input is:
1
2
3
4
5
It should print the sum of all the numbers.
But this gives me an error:

File "main.py", line 3
if lst ==1:
^
SyntaxError: invalid syntax


Please help me figure out what I did wrong! Thanks!

Answer

Since you're only allowed to write code inside an expression, you need to use a slightly different syntax for if-statements.

if len(lst) == 1:
    lst[0]
else:
    lst[0]+total(lst[0:])

can be written as a single statement as:

lst[0] if len(lst) == 1 else lst[0]+total(lst[0:])

(assuming you wanted to check the length of the list, rather than doing a compare against an int, which is always going to be false)

Comments