文章目录
一、前言
"""
输入M和N 计算C(M,N)
"""
m = int(input('m = '))
n = int(input('n = '))
fm = 1
for num in range(1, m + 1):
fm *= num
fn = 1
for num in range(1, n + 1):
fn *= num
fmn = 1
for num in range(1, m - n + 1):
fmn *= num
print(fm // fn // fmn)
二、函数的作用
将计算阶乘的功能封装到一个称之为"函数"的模块中,在需要计算的地方,调用即可。
三、定义函数
使用def
来定义函数
将上述的代码重构
"""
输入M和N 计算C(M,N)
"""
def factorial(num):
"""
求阶乘
"""
result = 1
for n in range(1, num + 1):
result *= n
return result
m = int(input('m = '))
n = int(input('n = '))
print(factorial(m) //factorial(n) // factorial(m-n))
当然factorial函数已经在math模块中有了
直接调用就可以了
import math
m = int(input('m = '))
n = int(input('n = '))
print(math.factorial(m) //math.factorial(n) // math.factorial(m-n))
四、函数的参数
1.函数参数说明
函数的参数可以有默认值,也支持使用可变参数
例子:
from random import randint
def roll_dice(n=2):
total = 0
for _ in range(n):
total += randint(1, 6)
return total
def add(a=0, b=0, c=0):
return a + b + c
# 如果没有指定参数那么使用默认摇两颗色子
print(roll_dice())
# 摇三颗色子
print(roll_dice(3))
print(add())
print(add(1))
print(add(1, 2))
print(add(1, 2, 3))
print(add(c=50, a=100, b=200))
在不知被传了所少个参数时,可以用*args
*kwargs
: 多少个关键字
def add(*args):
total = 0
for val in args:
total += val
return total
print(add())
print(add(1))
print(add(1, 2))
print(add(1, 2, 3))
print(add(1, 3, 5, 7, 9))
2.函数参数类型与参数传递
2.1 可变参数与可变参数传递
传递可变对象:指传递了对选哪个,在函数体被重新赋值后原来的值也发生了改变。
例子:
#!/usr/bin/env python
#coding:utf-8
def updateList(ls):
ls.append("world")
return ls
list = ["hello"]
updateList(list)
print(list)
原来的列表的值也被修改了。
如果不想改变原来的值,使用[:]
,传递切片副本
例子:
def updateList(ls):
ls.append("world")
return ls
list = ["hello"]
updateList(list[:])
print(list)
2.2 缺省参数与参数传递
缺省参数:表示调用函数的时候是可以不传递当前参数值,而使用默认参数值的
例子:
#!/usr/bin/env python
#coding:utf-8
def show_info(name, sex="男", age=18):
print("姓名: %s\t性别: %s\t年龄: %d" % (name, sex, age))
show_info(name="小明")
show_info(name="小明", age=19)
show_info(name="小红", sex="女", age=19)
有默认值的参数一定要放在无默认值参数的后面
2.3 关键字参数与关键字参数传递
可以指定参数的名称,从而可以不管参数的位置顺序
例子:
def show_info(name, sex="男", age=18):
print("姓名: %s\t性别: %s\t年龄: %d" % (name, sex, age))
show_info(name="小红", sex="女",age=19)
show_info(age=20, name="阿玮", sex="男")
2.4 不定长参数与不定长参数传递
不定参数使用*参数名
表示
例子:
def doPrint(name, *list):
print(name)
for item in list:
print(item)
doPrint("小明", "你好")
doPrint("小明", "你好", "大家好")
同时存在缺省参数和不定参数例子:
def doPrint(name, age=18, *list):
print("姓名: %s 年龄: %d" % (name, age))
for item in list:
print(item)
doPrint("小明", 19, "hello", "world")
五、用模块管理函数
例子:
def foo():
print('hello, world!')
def foo():
print('goodbye, world!')
foo()
给他们加上输出id,查看原因
def foo():
print('hello, world!')
print(id(foo))
def foo():
print('goodbye, world!')
print(id(foo))
foo()
会发现二者的id不同,前面的函数被后面的所覆盖了。
这时候就要用到模块,
test256.py
def liuyifei(word):
print(word,'心动')
test257.py
def liuyifei(word):
print(word,'心动个鬼')
test0226.py
from test256 import liuyifei
# 输出 刘亦菲 心动
liuyifei()
from test257 import liuyifei
# 输出 老王 心动个鬼
liuyifei()
也可以这样
import test256 as a1
import test257 as a2
a1.liuyifei('刘亦菲')
a2.liuyifei('老王')
m2.foo()