测试传递不可变对象时,不可变对象包含的子对象是可变的
#传递不可变对象时,不可变对象包含的子对象是可变的
a = (10,20,[5,6])
print('a:',id(a))
def test01(m):
print('m:',id(m))
m[2][0] = 888
print(m)
print('m:',id(m))
test01(a)
print(a)
运行结果:
a: 2379961110888
m: 2379961110888
(10, 20, [888, 6])
m: 2379961110888
(10, 20, [888, 6])
函数参数测试
#测试位置参数
def f0(a,b,c,d):
print(a,b,c,d)
f0(10,20,30,40)
print()
print('$$$$$$$$$$$$')
#测试默认值参数
def f1(a,b,c=10,d=20):
print(a,b,c,d)
f1(8,9)
f1(8,9,19)
f1(8,9,19,29)
print()
print('$$$$$$$$$$$$$$$$$$$')
#测试命名参数
def f2(a,b,c):
print(a,b,c)
f2(8,9,19)
f2(c=10,a=20,b=30)
运行结果:
10 20 30 40
$$$$$$$$$$$$
8 9 10 20
8 9 19 20
8 9 19 29
$$$$$$$$$$$$$$$$$$$
8 9 19
20 30 10
测试可变对象
#测试可变对象
def f1(a,b,*c):
print(a,b,c)
f1(8,9,19,20)
print('$$$$$$$$$$$$$$$$$')
def f2(a,b,**c):
print(a,b,c)
f2(8,9,name='gaoqi',age=18)
print('$$$$$$$$$$$$$$$$$')
def f3(a,b,*c,**d):
print(a,b,c,d)
f3(8,9,20,30,name='gaoqi',age=18)
#测试强制命名参数
print('$$$$$$$$$$$$$$$$$')
def f4(*a,b,c):
print(a,b,c)
f4(2,b=3,c=4)
运行结果:
8 9 (19, 20)
$$$$$$$$$$$$$$$$$
8 9 {'name': 'gaoqi', 'age': 18}
$$$$$$$$$$$$$$$$$
8 9 (20, 30) {'name': 'gaoqi', 'age': 18}
$$$$$$$$$$$$$$$$$
(2,) 3 4
lamda表达式和匿名函数
#lamda表达式和匿名函数
f1 = lambda a,b,c:a+b+c
print(f1)
print(f1(1,2,3))
print('$$$$$$$$$$$$$$$$')
g = [lambda a:a*2,lambda b:b*3,lambda c:c*3]
print(g[0](6),g[1](7))
运行结果:
<function <lambda> at 0x0000021D4F6AC268>
6
$$$$$$$$$$$$$$$$
12 21
测试eval()函数
#测试eval()函数
s = "print('abcd')"
eval(s)
a = 10
b = 20
c = eval("a+b")
print(c)
dict1 = dict(a=100,b=200)
d = eval("a+b",dict1)
print(d)
运行结果:
abcd
30
300
测试递归函数的基本原理
#测试递归函数的基本原理
def test01():
print("test01")
test01()
def test02():
print("test02")
test01()
运行结果:
Traceback (most recent call last):
File "D:/Program Files/mypro_func/mypy15.py", line 9, in <module>
test01()
File "D:/Program Files/mypro_func/mypy15.py", line 4, in test01
test01()
File "D:/Program Files/mypro_func/mypy15.py", line 4, in test01
test01()
File "D:/Program Files/mypro_func/mypy15.py", line 4, in test01
test01()
[Previous line repeated 993 more times]
File "D:/Program Files/mypro_func/mypy15.py", line 3, in test01
print("test01")
RecursionError: maximum recursion depth exceeded while calling a Python object
最后会因超出最大迭代次数而终止运算
使用递归计算阶乘
#使用递归计算阶乘
def factorial(n):
if n == 1:
return 1
else:
return n*factorial(n-1)
result = factorial(5)
print(result)
运行结果:
120