繁体   English   中英

如何在 python 中设置 function 参数的数据类型?

[英]How to set the data type of a function parameter in python?


def recursiveSum(lst):
    if len(lst) == 0:
        return 0
    else:
        #print(str(type(lst))+'\n')    
        num = lst[len(lst)-1]
        return recursiveSum(lst.pop()) + num


size = int(input("How many number do you want to enter? = "))
lst=[]
for i in range(size):
    lst.append(input("Enter number "+str(i+1)+" = " ))
print(recursiveSum(lst))

在这段代码中,我试图递归地找到数字列表的总和,这是我第一次尝试递归,我认为我的方法和算法是正确的,当传递给recursiveSum() function 时,列表以某种方式使其在else部分中成为字符串, 执行时的注释行结束打印

class '列表'

class 'str'

我不明白 print 语句如何同时打印liststr

有人可以解释一下吗?

我认为您在输入时忘记将类型转换为 int:

lst.append(int(input("Enter number "+str(i+1)+" = " )))

两个问题:

  • 您不会将输入转换为数字/整数
  • 您使用弹出的元素而不是剩余的列表进行递归

使固定:

def recursiveSum(lst):
    if len(lst) == 0:
        return 0
    else:
        num = lst[0]   # use the first one 
        return recursiveSum(lst[1:]) + num   # and recurse on the remaining slice


size = int(input("How many number do you want to enter? = "))
lst=[]
for i in range(size):
    lst.append(int(input("Enter number "+str(i+1)+" = " )))
print(recursiveSum(lst))

list.pop()返回从列表中弹出的元素 - 而不是列表余数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM