Python3基础-函数实例学习

内置函数

绝对值函数

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!

参考

posted @ 2018-11-24 00:46  既生喻何生亮  阅读(674)  评论(0编辑  收藏  举报