Python3基礎-函數實例學習
阿新 • • 發佈:2018-11-24
函數 github ins 絕對值 amp 數學庫 abs raise person
內置函數
絕對值函數
x = abs(100)
y = abs(-20)
print('x=100的絕對值為:{}'.format(x))
print('y=-20的絕對值為:{}'.format(y))
x=100的絕對值為:100
y=-20的絕對值為:20
求最大值、最小值、求和函數
print("(1, 2, 3, 4)中最大max的元素為:{}".format(max(1, 2, 3, 4))) print("(1, 2, 3, 4)中最小min的元素為:{}".format(min(1, 2, 3, 4))) print("(1, 2, 3, 4)中最元素累加和sum為:{}".format(sum([1, 2, 3, 4])))
(1, 2, 3, 4)中最大max的元素為:4
(1, 2, 3, 4)中最小min的元素為:1
(1, 2, 3, 4)中最元素累加和sum為:10
模塊中的函數
import random
char_set = "abcdefghijklmnopqrstuvwxyz0123456789"
print("char_set長度{}".format(len(char_set)))
char_set[random.randint(0, 35)]
char_set長度36
'j'
自定義函數
自定義絕對值函數
def my_abs(x): "判斷x的類型,如果不是int和float,則出現類型錯誤。" if not isinstance(x, (int, float)): raise TypeError('bad operand type') # 判斷x的正負 if x >= 0: return x else: return -x print("自定義絕對值函數的調用:采用-函數名()的形式 my_abs(-20) = {}".format(my_abs(-20)))
自定義絕對值函數的調用:采用-函數名()的形式 my_abs(-20) = 20
自定義移動函數
import math # 導入數學庫 def move(x, y, step, angle=0): nx = x + step * math.cos(angle) ny = y + step * math.sin(angle) return nx, ny x, y = move(100, 100, 60, math.pi/6) print("原始坐標(100, 100),沿著x軸逆時針pi/6移動60後的坐標為:新坐標 (x, y) = ({}, {})".format(x, y))
原始坐標(100, 100),沿著x軸逆時針pi/6移動60後的坐標為:新坐標 (x, y) = (151.96152422706632, 130.0)
自定義打印函數
# 該函數傳入的參數需要解析字典形式
def print_scores(**kw):
print(' Name Score')
print('------------------')
for name, score in kw.items():
print('%10s %d' % (name, score))
print()
# 用賦值方式傳參
print_scores(Adam=99, Lisa=88, Bart=77)
Name Score
------------------
Adam 99
Lisa 88
Bart 77
data = {
'Adam Lee': 99,
'Lisa S': 88,
'F.Bart': 77
}
# 用字典形式傳參,需要解析,用兩個*
print_scores(**data)
Name Score
------------------
Adam Lee 99
Lisa S 88
F.Bart 77
# 各種混合參數的形式定義的函數,一般遵行一一對應
def print_info(name, *, gender, city='Beijing', age):
print('Personal Info')
print('---------------')
print(' Name: %s' % name)
print(' Gender: %s' % gender)
print(' City: %s' % city)
print(' Age: %s' % age)
print()
print_info('Bob', gender='male', age=20)
print_info('Lisa', gender='female', city='Shanghai', age=18)
Personal Info
---------------
Name: Bob
Gender: male
City: Beijing
Age: 20
Personal Info
---------------
Name: Lisa
Gender: female
City: Shanghai
Age: 18
遞歸階乘函數
# 利用遞歸函數計算階乘
# N! = 1 * 2 * 3 * ... * N
def fact(n):
if n == 1:
return 1
return n * fact(n-1)
print('fact(1) =', fact(1))
print('fact(5) =', fact(5))
print('fact(10) =', fact(10))
fact(1) = 1
fact(5) = 120
fact(10) = 3628800
遞歸函數移動漢諾塔
def move(n, a, b, c):
if n == 1:
print('move', a, '-->', c)
else:
move(n-1, a, c, b)
move(1, a, b, c)
move(n-1, b, a, c)
move(4, 'A', 'B', 'C')
move A --> B
move A --> C
move B --> C
move A --> B
move C --> A
move C --> B
move A --> B
move A --> C
move B --> C
move B --> A
move C --> A
move B --> C
move A --> B
move A --> C
move B --> C
混合參數函數
def hello(greeting, *args):
if (len(args)==0):
print('%s!' % greeting)
else:
print('%s, %s!' % (greeting, ', '.join(args)))
hello('Hi') # => greeting='Hi', args=()
hello('Hi', 'Sarah') # => greeting='Hi', args=('Sarah')
hello('Hello', 'Michael', 'Bob', 'Adam') # => greeting='Hello', args=('Michael', 'Bob', 'Adam')
names = ('Bart', 'Lisa')
hello('Hello', *names) # => greeting='Hello', args=('Bart', 'Lisa')
Hi!
Hi, Sarah!
Hello, Michael, Bob, Adam!
Hello, Bart, Lisa!
參考
Python3基礎-函數實例學習