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!
Python3基础-函数实例学习的更多相关文章
- Python3基础 函数 关键字参数 的示例
镇场诗: 诚听如来语,顿舍世间名与利.愿做地藏徒,广演是经阎浮提. 愿尽吾所学,成就一良心博客.愿诸后来人,重现智慧清净体.-------------------------------------- ...
- Python3基础 函数名.__doc__显示一个函数的单行与多行函数文档
镇场诗: 诚听如来语,顿舍世间名与利.愿做地藏徒,广演是经阎浮提. 愿尽吾所学,成就一良心博客.愿诸后来人,重现智慧清净体.-------------------------------------- ...
- Python3基础 函数 递归 阶乘与斐波那契数列
Python : 3.7.0 OS : Ubuntu 18.04.1 LTS IDE : PyCharm 2018.2.4 Conda ...
- Python3基础 函数 函数名赋值操作
Python : 3.7.3 OS : Ubuntu 18.04.2 LTS IDE : pycharm-community-2019.1.3 ...
- Python3基础 函数 参数为list 使用+=会影响到外部的实参
Python : 3.7.3 OS : Ubuntu 18.04.2 LTS IDE : pycharm-community-2019.1.3 ...
- Python3基础 函数 参数 多个参数都有缺省值,需要指定参数进行赋值
Python : 3.7.3 OS : Ubuntu 18.04.2 LTS IDE : pycharm-community-2019.1.3 ...
- Python3基础——函数
ython 函数 函数是组织好的,可重复使用的,用来实现单一,或相关联功能的代码段. 函数能提高应用的模块性,和代码的重复利用率.你已经知道Python提供了许多内建函数,比如print().但你也可 ...
- Python3基础 函数 收集参数+普通参数 的示例
镇场诗: 诚听如来语,顿舍世间名与利.愿做地藏徒,广演是经阎浮提. 愿尽吾所学,成就一良心博客.愿诸后来人,重现智慧清净体.-------------------------------------- ...
- Python3基础 函数 默认值参数示例
镇场诗: 诚听如来语,顿舍世间名与利.愿做地藏徒,广演是经阎浮提. 愿尽吾所学,成就一良心博客.愿诸后来人,重现智慧清净体.-------------------------------------- ...
随机推荐
- springmvc和structs2的区别
1.从安全性角度分析spring mvc和struts2的区别: spring mvc:controller 1.spring mvc 默认controller是单实例(通过注解@Scope(“pro ...
- [PHP]算法-队列结构的PHP实现
题目描述 用两个栈来实现一个队列,完成队列的Push和Pop操作. 队列中的元素为int类型. 思路: 1.php数组完全就能实现 2.array_push 从尾部往里压入元素 3.array_shi ...
- FastJson序列化Json自定义返回字段,普通类从spring容器中获取bean
前言: 数据库的字段比如:price:1 ,返回需要price:1元. 这时两种途径修改: ① 比如sql中修改或者是在实体类转json前遍历修改. ②返回json,序列化时候修改.用到的是fastj ...
- 6.2 小表驱动大表(exists的应用)
1. 优化原则:小表驱动大表,即小数据集驱动大数据集. select * from A where id in (select id from B) 等价于: for select id from B ...
- 修改tomcat命令黑窗口的名字
一.为什么要修改tomcat黑窗口的名字 同时启动多个tomcat时,不好区分,而给tomcat的命令窗口取名区分是个不错的选择,例如下面这个效果. 二.修改的方法 1.找到tomcat的bin目录下 ...
- dubbo+zookeeper+springBoot框架整合与dubbo泛型调用演示
dubbo + zookeeper + spring Boot框架整合与dubbo泛型调用演示 By:客 授客 QQ:1033553122 欢迎加入全国软件测试交流 QQ 群:7156436 ...
- 1.写页面 2.css的继承属性有哪些 3.margin对布局的影响
1. sparent 透明的 2. placeholder 提示语 写页面 1.搞清结构层次 2. 保证模块化 让它们之间不能收到影响. (1) 元素性质 (2)标准流 浮动带来的脱离文档流撑不起父级 ...
- 如何处理Express异常?
译者按:根据墨菲定律:“有可能出错的事情,就会出错”.那么,既然代码必然会出错,我们就应该处理好异常. 原文: How to handle errors in Express 译者:Fundebug ...
- CodeMirror 使用
codemirror是一款在线代码编辑器,官网:https://codemirror.net/doc/manual.html#overview 使用说明 第一步 安装: npm install cod ...
- mybatis加载属性
1): <dataSource>的<property>标签加载属性 在 properties 元素体内定义的属性首先被读取 然后会读取 properties 元素中 resou ...