在Python中使用递归在列表中添加数字
给定的模板是:在Python中使用递归在列表中添加数字,python,recursion,Python,Recursion,给定的模板是: def total(lst): return ( #### YOUR CODE HERE #### #### DO NOT WRITE CODE OUTSIDE OF THIS #### #### RETURN STATEMENT #### ) def getValue(): try: return int(input()) except: return No
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))
我得到了这个:
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))
输入为:
1.
2.
3.
4.
5.
它应该打印所有数字的总和。
但这给了我一个错误:
File "main.py", line 3
if lst ==1:
^
SyntaxError: invalid syntax
请帮我找出我做错了什么!谢谢 在返回表达式中放入if语句。将语句放入表达式中是语法错误。改用if表达式,例如
return (
lst[0] if lst == 1 else lst[0] + total(lst[0:])
)
由于只允许在表达式中编写代码,因此需要对
if
-语句使用稍微不同的语法
if len(lst) == 1:
lst[0]
else:
lst[0]+total(lst[0:])
可以作为单个语句编写,如下所示:
lst[0] if len(lst) == 1 else lst[0]+total(lst[0:])
(假设您想检查列表的长度,而不是与int进行比较,int总是会为false)谢谢。这对我帮助很大!