调用函数
Python内置了很多有用的函数,我们可以直接调用。
请利用Python内置的hex()函数把一个整数转换成十六进制表示的字符串:
n1 = 255
n2 = 1000
print(hex(n1))
print(hex(n2))
定义函数
在Python中,定义一个函数要使用def语句,依次写出函数名、括号、括号中的参数和冒号:,然后,在缩进块中编写函数体,函数的返回值用return语句返回。
1.自定义一个求绝对值的my_abs函数:
def my_abs(x):
if x >= 0:
return x
else:
return -x
print(my_abs(-99))
2.请定义一个函数quadratic(a, b, c),接收3个参数,返回一元二次方程:
ax2 + bx + c = 0的两个解。
提示:计算平方根可以调用math.sqrt()函数:
import math
math.sqrt(2)
1.4142135623730951
import math
def quadratic(a, b, c):
if a == 0:
print('函数无解。')
else:
dert = b * b - 4 * a * c
x1 = (- b + math.sqrt ( dert )) / ( 2 * a )
x2 = (- b - math.sqrt ( dert )) / ( 2 * a )
return x1,x2
if __name__ == '__main__':
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 ( '测试成功' )
函数的参数
默认参数一定要用不可变对象,如果是可变对象,程序运行时会有逻辑错误。
*args是可变参数,args接收的是一个tuple;
**kw是关键字参数,kw接收的是一个dict。
可变参数既可以直接传入:func(1, 2, 3),又可以先组装list或tuple,再通过args传入:func((1, 2, 3));
关键字参数既可以直接传入:func(a=1, b=2),又可以先组装dict,再通过*kw传入:func({‘a’: 1, ‘b’: 2})。*
使用*args和**kw是Python的习惯写法,当然也可以用其他参数名,但最好使用习惯用法。
命名的关键字参数是为了限制调用者可以传入的参数名,同时可以提供默认值。
定义命名的关键字参数在没有可变参数的情况下不要忘了写分隔符*,否则定义的将是位置参数。
# 位置参数
def power(x, n):
s = 1
while(n>0):
n = n-1
s = s*x
return (s)
# 默认参数
def enroll(name, gender, age = 6, city = 'taiyuan'):
print('name:', name )
print('gender:', gender )
print('age:', age )
print('city:', city )
def add_end(L=None):
if L is None:
L = []
L.append('END')
return L
# 可变参数 (list [] tuple ())
def calc(*numbers):
sum = 0
for n in numbers:
sum = sum + n * n
return sum
# 关键字参数
def person1(name, age, **kw):
print('name:', name, 'age:', age, 'other:', kw)
# 命名关键字参数
def person2(name, age, *, city, job):
print(name, age, city, job)
if __name__ == '__main__':
print(power(5,2))
print(enroll('小明',7))
print(enroll('小明',7,7))
print(add_end())
print(add_end())
print(calc(1,2,3,4))
nums = [1,5,9]
print(calc(*nums))
numss = (1, 5, 9)
print(calc(*numss))
print(person1('Bob', 35, city='Beijing'))
extra = {'city': 'Beijing', 'job': 'Engineer'}
print(person1('Jack',20,city = extra['city'],job = extra['job']))
print(person1('jack',20,**extra))
print(person2('Jack', 24, city='Beijing', job='gongzuo'))
print(person2('Jack', 24, city='Beijing', job='Engineer'))
以下函数允许计算两个数的乘积,请稍加改造,变成可接收一个或多个数并计算乘积:
def product(*L): #*L表示把L这个tuple的所有元素作为可变参数传进去
sum = 1
for i in L:
sum = sum * i
return sum
if __name__ == '__main__':
print('product(5) =', product(5))
print('product(5, 6) =', product(5, 6))
print('product(5, 6, 7) =', product(5, 6, 7))
print('product(5, 6, 7, 9) =', product(5, 6, 7, 9))
if product(5) != 5:
print('测试失败!')
elif product(5, 6) != 30:
print('测试失败!')
elif product(5, 6, 7) != 210:
print('测试失败!')
elif product(5, 6, 7, 9) != 1890:
print('测试失败!')
else:
print('测试成功!')
递归函数
如果一个函数在内部调用自身本身,这个函数就是递归函数。
汉诺塔的移动可以用递归函数非常简单地实现。
请编写move(n, a, b, c)函数,它接收参数n,表示3个柱子A、B、C中第1个柱子A的盘子数量,然后打印出把所有盘子从A借助B移动到C的方法,例如:
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 )
if __name__ == '__main__':
print(move ( 3 , 'A' , 'B' , 'C' ))
算法介绍:
当盘子的个数为n时,移动的次数应等于2^n – 1(有兴趣的可以自己证明试试看)。后来一位美国学者发现一种出人意料的简单方法,只要轮流进行两步操作就可以了。首先把三根柱子按顺序排成品字型,把所有的圆盘按从大到小的顺序放在柱子A上,根据圆盘的数量确定柱子的排放顺序:若n为偶数,按顺时针方向依次摆放 A B C;
若n为奇数,按顺时针方向依次摆放 A C B。
⑴按顺时针方向把圆盘1从现在的柱子移动到下一根柱子,即当n为偶数时,若圆盘1在柱子A,则把它移动到B;若圆盘1在柱子B,则把它移动到C;若圆盘1在柱子C,则把它移动到A。
⑵接着,把另外两根柱子上可以移动的圆盘移动到新的柱子上。即把非空柱子上的圆盘移动到空柱子上,当两根柱子都非空时,移动较小的圆盘。这一步没有明确规定移动哪个圆盘,你可能以为会有多种可能性,其实不然,可实施的行动是唯一的。
⑶反复进行⑴⑵操作,最后就能按规定完成汉诺塔的移动。
所以结果非常简单,就是按照移动规则向一个方向移动金片:
如3阶汉诺塔的移动:A→C,A→B,C→B,A→C,B→A,B→C,A→C