当前位置: 移动技术网 > IT编程>脚本编程>Python > Python3基础-函数实例学习

Python3基础-函数实例学习

2018年11月24日  | 移动技术网IT编程  | 我要评论

全球玻璃网,暗黑之日汉化,万珂

内置函数

绝对值函数

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!

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网