一、调用函数
1、调用函数
调用函数的时候,如果传入的参数数量不对,会报TypeError的错误。
如果传入的参数数量是对的,但参数类型不能被函数所接受,也会报TypeError的错误,并且给出错误信息
2、数据类型转换
【练习】请利用Python内置的hex()函数把一个整数转换成十六进制表示的字符串:
# -*- coding: utf-8 -*-
n1 = 255
print (hex(n1))
Run: 0xff
二、定义函数
【练习】请定义一个函数quadratic(a, b, c),接收3个参数,返回一元二次方程
a
x
2
ax^2
ax2+bx+c=0 的两个解。提示:一元二次方程的求根公式为:
x=
−
b
±
b
2
−
4
a
c
2
a
\frac{-b\pm\sqrt{b^2-4ac}}{2a}
2a−b±b2−4ac
计算平方根可以调用math.sqrt()
函数
# -*- coding: utf-8 -*-
import math
def quadratic(a, b, c):
if b*b > 4*a*c:
result1=(-b + math.sqrt(b*b-4*a*c))/(2*a)
result2=(-b - math.sqrt(b*b-4*a*c))/(2*a)
return result1,result2
elif b*b < 4*a*c:
print("该方程无解")
else:
print("该方程只有一个解")
result=(-b + math.sqrt(b*b-4*a*c))/(2*a)
return result
# 测试:
print('quadratic(2, 3, 1) =', quadratic(2, 3, 1))
print('quadratic(1, 3, -4) =', quadratic(1, 3, -4))
if quadratic(2, 3, 1) != (-0.5, -1.0):
print('测试失败')
elif quadratic(1, 3, -4) != (1.0, -4.0):
print('测试失败')
else:
print('测试成功')
Run:
quadratic(2, 3, 1) = (-0.5, -1.0)
quadratic(1, 3, -4) = (1.0, -4.0)
测试成功
三、函数的参数
1、位置参数
power(x, n)
函数有两个参数:x和n,这两个参数都是位置参数,调用函数时,传入的两个值按照位置顺序依次赋给参数x和n。
2、默认参数
定义默认参数要牢记一点:默认参数必须指向不变对象!
def add_end(L=None):
if L is None:
L = []
L.append('END')
return L
3、可变参数
定义可变参数和定义一个list或tuple参数相比,仅仅在参数前面加了一个*号。在函数内部,参数numbers接收到的是一个tuple,因此,函数代码完全不变。但是,调用该函数时,可以传入任意个参数,包括0个参数。
def calc(*numbers):
sum = 0
for n in numbers:
sum = sum + n * n
return sum
4、关键字参数
而关键字参数允许你传入0个或任意个含参数名的参数,这些关键字参数在函数内部自动组装为一个dict。关键字参数可以扩展函数的功能。比如,在person函数里,我们保证能接收到name和age这两个参数,但是,如果调用者愿意提供更多的参数,我们也能收到。
def person(name, age, **kw):
print('name:', name, 'age:', age, 'other:', kw)
5、命名关键字参数
6、参数组合
【练习】以下函数允许计算两个数的乘积,请稍加改造,变成可接收一个或多个数并计算乘积:
# -*- coding: utf-8 -*-
def mul(product, *numbers):
for n in numbers:
product *= n
return product
或
def mul(firstnum, *numbers):
product = firstnum
for n in numbers:
product *= n
return product
Test:
#测试
print('mul(5) =', mul(5))
print('mul(5, 6) =', mul(5, 6))
print('mul(5, 6, 7) =', mul(5, 6, 7))
print('mul(5, 6, 7, 9) =', mul(5, 6, 7, 9))
if mul(5) != 5:
print('测试失败!')
elif mul(5, 6) != 30:
print('测试失败!')
elif mul(5, 6, 7) != 210:
print('测试失败!')
elif mul(5, 6, 7, 9) != 1890:
print('测试失败!')
else:
try:
mul()
print('测试失败!')
except TypeError:
print('测试成功!')
Python异常处理
Run:
mul(5) = 5
mul(5, 6) = 30
mul(5, 6, 7) = 210
mul(5, 6, 7, 9) = 1890
测试成功!
【学习记录】
当初始没有参数时,不会报错。不符合要求。
def mul(*numbers):
product = 1
for n in numbers:
product = product * n
return product
# Tests that pass
assert mul(5) == 5
assert mul(5, 6) == 30
# Tests that fail!
try:
mul()
assert false, "Expected a TypeError exception to be raised"
except TypeError:
pass
原因:
Your initial implementation of mul()
will accept a call with no arguments.
https://stackoverflow.com/questions/66702157/function-to-calculate-the-product-of-several-numbers
四、递归函数
【练习】汉诺塔的移动
# -*- coding: utf-8 -*-
def move(n, a, b, c):
if n == 1:
print(a, '-->', c)
else:
move(n - 1, a, c, b)
print(a, '-->', c)
move(n - 1, b, a, c)
move(3, 'A', 'B', 'C')
Run:
A --> C
A --> B
C --> B
A --> C
B --> A
B --> C
A --> C