Skip to content

Commit 1aac93f

Browse files
committed
add function examples
1 parent 1780a43 commit 1aac93f

4 files changed

Lines changed: 68 additions & 0 deletions

File tree

py3/function/call_func.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
x = abs(100)
5+
y = abs(-20)
6+
print(x, y)
7+
print('max(1, 2, 3) =', max(1, 2, 3))
8+
print('min(1, 2, 3) =', min(1, 2, 3))
9+
print('sum([1, 2, 3]) =', sum([1, 2, 3]))

py3/function/def_func.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
import math
5+
6+
def my_abs(x):
7+
if not isinstance(x, (int, float)):
8+
raise TypeError('bad operand type')
9+
if x >= 0:
10+
return x
11+
else:
12+
return -x
13+
14+
def move(x, y, step, angle=0):
15+
nx = x + step * math.cos(angle)
16+
ny = y - step * math.sin(angle)
17+
return nx, ny
18+
19+
n = my_abs(-20)
20+
print(n)
21+
22+
x, y = move(100, 100, 60, math.pi / 6)
23+
print(x, y)
24+
25+
# TypeError: bad operand type:
26+
my_abs('123')

py3/function/params.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
def power(x, n=2):
5+
return x ** n
6+
7+
print('power(5) =', power(5))
8+
print('power(5, 2) =', power(5, 2))
9+
print('power(5, 4) =', power(5, 4))

py3/function/recur.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
# 利用递归函数计算阶乘
5+
# N! = 1 * 2 * 3 * ... * N
6+
def fact(n):
7+
if n == 1:
8+
return 1
9+
return n * fact(n-1)
10+
11+
print('fact(1) =', fact(1))
12+
print('fact(5) =', fact(5))
13+
print('fact(10) =', fact(10))
14+
15+
# 利用递归函数移动汉诺塔:
16+
def move(n, a, b, c):
17+
if n == 1:
18+
print('move', a, '-->', c)
19+
return
20+
move(n-1, a, c, b)
21+
print('move', a, '-->', c)
22+
move(n-1, b, a, c)
23+
24+
move(4, 'A', 'B', 'C')

0 commit comments

Comments
 (0)