当前位置:   article > 正文

python函数递归求和详解_Python函数中多类型传值和冗余参数及函数的递归调用

def fun(x,y): if x>=y: else: return print(fun(1,10)

1.多类型传值和冗余参数

多类型传值:

def fun(x,y):

return x +y

print fun(3,5)

8

print fun(*t)

3

def fun(x,y,z):

return x + y + z

t1 = (1,2,3)

fun(*t1)

6

fun(*(2,4,5))

11

fun(1,*t)

4

print t

(1, 2)

fun(x=1,y=3,z=5)

9

>>> dic = {'x':1,'y':3,'z':6}

>>> fun(**dic)

10

冗余参数:

>>> def fun(x,*args,**kwargs):

... print x

... print args

... print kwargs

...

>>> fun(1)

1

()

{}

>>> fun(1,2)

1

(2,)

{}

>>> fun(1,2,3)

1

(2, 3)

{}

>>> t

(1, 2)

>>> fun(1,2,3,'a',[1,2],*t,a=3,**{'t':11,'p':22})

1

(2, 3, 'a', [1, 2], 1, 2)

{'a': 3, 'p': 22, 't': 11}

2.函数的递归调用

递归的注意事项:

必须有最后的默认结果:

if n == 0

递归参数必须向默认结果收敛的:

factorial(n-1)

阶乘脚本:

#!/usr/bin/env python

# -*- coding:utf-8 -*-

# @Time: 2018/1/4 11:57

# @Author: Feng Xiaoqing

# @File: jiecheng.py

# ======================

def factorial(n):

sum = 0

for i in range(1,n+1):

sum += i

return sum

print factorial(100)

另外一种方法:

def factorial(n):

if n == 0:

return 1

else:

return n * factorial(n-1)

print factorial(5)

求1-100相加的和:

def factorial(n):

if n == 0:

return 0

else:

return n + factorial(n-1)

print factorial(100)

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/116212
推荐阅读
相关标签
  

闽ICP备14008679号