python学习(8)函数
2016-10-24 12:48
120 查看
网站:http://docs.python.org/3/library/functions.html#abs
一、一些内置函数
1、绝对值函数abs()
abs(-20) //20
如果传的参数不是数字,将会报错
2、max函数,求最大值
max(1,2,3,4,2) //4
max([1,2,3,4,2]) //4
3、hex()函数求数字的16进制
hex(255) //0xff
二、数据类型转换
int('123') //123
int('12.3') //12
float('12.3') //12.3
str(123) //'123'
bool(1) // True
bool('') // False
传入无法转换的数,就会报错
函数名其实就是指向一个函数对象的引用,完全可以把函数名赋给一个变量,相当于给这个函数起了一个“别名”:
a = abs;
a(-1) //1
三、定义函数
def a(x):
return x;
如果为return则返回None
1、空函数
pass语句
def nop():
pass
其实pass语句什么都没有做,占位符
2、参数检查
数据类型的检查可以用内置的isinstance(),抛出异常
3、返回多个值
返回一个tuple
一、一些内置函数
1、绝对值函数abs()
abs(-20) //20
如果传的参数不是数字,将会报错
2、max函数,求最大值
max(1,2,3,4,2) //4
max([1,2,3,4,2]) //4
3、hex()函数求数字的16进制
hex(255) //0xff
二、数据类型转换
int('123') //123
int('12.3') //12
float('12.3') //12.3
str(123) //'123'
bool(1) // True
bool('') // False
传入无法转换的数,就会报错
函数名其实就是指向一个函数对象的引用,完全可以把函数名赋给一个变量,相当于给这个函数起了一个“别名”:
a = abs;
a(-1) //1
三、定义函数
def a(x):
return x;
如果为return则返回None
1、空函数
pass语句
def nop():
pass
其实pass语句什么都没有做,占位符
2、参数检查
def my_abs(x): if not isinstance(x, (int, float)): raise TypeError('bad operand type') if x >= 0: return x else: return -x
数据类型的检查可以用内置的isinstance(),抛出异常
3、返回多个值
import math def move(x, y, step, angle=0): nx = x + step * math.cos(angle) ny = y - step * math.sin(angle) return nx, ny
>>> r = move(100, 100, 60, math.pi / 6) >>> print(r) (151.96152422706632, 70.0)
返回一个tuple
相关文章推荐
- Python函数学习笔记
- Python 学习笔记:需要仔细阅读一个函数
- Python模块学习之os常用函数
- Learn Python The Hard Way学习(35) - 分支和函数
- Learn Python The Hard Way学习(21) - 函数可以返回信息
- Python 学习笔记 - 9.函数(Function)
- Dive Into Python 学习记录3-getattr 介绍/过滤列表/and or/lambda 函数
- python学习之模块函数
- python学习--使用 lambda 函数
- Dive Into Python 学习记录1-函数/模块导入/字典/列表/元组/字符串分割、连接、格式化/映射list/
- Python学习手记 pt4 函数
- Python学习(五) -- 函数
- 我的python学习之路----函数
- Python学习:def函数的定义、使用及参数传递
- Python学习笔记整理(十二)Python的函数
- Python函数学习笔记
- python学习--函数使用
- Python:通过计算阶乘来学习lambda和reduce这两个函数的使用
- Learn Python The Hard Way学习(19) - 函数和变量
- Dive Into Python 学习记录2-自省/info 函数 /str / type /callable 函数