标签:set end lin inf arm tin 函数 字典 **kwargs
一、函数的类型
def sum_2(): ## 函数的定义
num1 = 10
num2 = 20
result = num1 + num2
print "%d + %d = %d" % (num1, num2, result)
sum_2() ## 函数的调用
2、有参函数(形参和是参之间的传递)
def sum_2_1(num1, num2):
result = num1 + num2
print "%d + %d = %d" % (num1, num2, result)
sum_2_1(7, 98)
3、collatz(number)函数,参数为偶数打印number//2;奇数打印3*number+1
方法一:
def collatz(number):
if number%2 == 0:
print number//2
else:
print 3*number+1
collatz(2)
方法二:print number // 2 if number % 2 == 0 else 3 * number + 1
二、函数的四大形参
2、默认参数
# def mypow(x, y=2):
# print x ** y # **为幂次方
#
# mypow(4, 3)
# 3、可变参数:形参的个数不确定
# def mysum(*args):
# print args # *args:是可变参数;args是元组类型的数据
# sum = 0
# for i in args:
# sum += i
# print sum
# mysum(1, 2, 3, 4)
# # 对list tuple,set解包时,只需要在变量面前加*
# nums = [1,3,5,7] # 列表类型,对列表或集合进行解包
# mysum(*nums)
# 4、关键字参数(**kwargs是一个字典,可以传递任意多的key-values)
def getStu(name, age, **kwargs):
print name, age
print kwargs
getStu(‘westos‘, ‘20‘, hobbies=[‘code‘, ‘runuing‘], gender=‘farman‘)
标签:set end lin inf arm tin 函数 字典 **kwargs
原文地址:https://www.cnblogs.com/uthnb/p/9581665.html