实例讲解Python中函数的调用与定义


Posted in Python onMarch 14, 2016

调用函数:

#!/usr/bin/env python3 
# -*- coding: utf-8 -*- 
 
# 函数调用 
>>> abs(100) 
100 
>>> abs(-110) 
110 
>>> abs(12.34) 
12.34 
>>> abs(1, 2) 
Traceback (most recent call last): 
 File "<stdin>", line 1, in <module> 
TypeError: abs() takes exactly one argument (2 given) 
>>> abs('a') 
Traceback (most recent call last): 
 File "<stdin>", line 1, in <module> 
TypeError: bad operand type for abs(): 'str' 
>>> max(1, 2) 
2 
>>> max(2, 3, 1, -5) 
3 
>>> int('123') 
123 
>>> int(12.34) 
12 
>>> str(1.23) 
'1.23' 
>>> str(100) 
'100' 
>>> bool(1) 
True 
>>> bool('') 
False 
>>> a = abs # 变量a指向abs函数,相当于引用 
>>> a(-1) # 所以也可以通过a调用abs函数 
1 
 
>>> n1 = 255 
>>> n2 = 1000 
>>> print(hex(n1)) 
0xff 
>>> print(hex(n2)) 
0x3e8

定义函数:

#!/usr/bin/env python3 
# -*- coding: utf-8 -*- 
 
#函数定义 
def myAbs(x): 
 if x >= 0: 
  return x 
 else: 
  return -x 
 
a = 10 
myAbs(a) 
 
def nop(): # 空函数 
 pass

pass语句什么都不做 。
实际上pass可以用来作为占位符,比如现在还没想好怎么写函数代码,就可以先写一个pass,让代码运行起来。  
  

if age >= 18: 
 pass 
#缺少了pass,代码就会有语法错误 
>>> if age >= 18: 
... 
 File "<stdin>", line 2 
 
 ^ 
IndentationError: expected an indented block 
 
>>> myAbs(1, 2) 
Traceback (most recent call last): 
 File "<stdin>", line 1, in <module> 
TypeError: myAbs() takes 1 positional argument but 2 were given 
>>> myAbs('A') 
Traceback (most recent call last): 
 File "<stdin>", line 1, in <module> 
 File "<stdin>", line 2, in myAbs 
TypeError: unorderable types: str() >= int() 
>>> abs('A') 
Traceback (most recent call last): 
 File "<stdin>", line 1, in <module> 
TypeError: bad operand type for abs(): 'str' 
 
def myAbs(x): 
 if not isinstance(x, (int, float)): 
  raise TypeError('bad operand type') 
 if x >= 0: 
  return x 
 else: 
  return -x 
 
>>> myAbs('A') 
Traceback (most recent call last): 
 File "<stdin>", line 1, in <module> 
 File "<stdin>", line 3, in myAbs 
TypeError: bad operand type

 
返回两个值?  

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(x, y) 
151.96152422706632 70.0

 
其实上面只是一种假象,Python函数返回的仍然是单一值 。

>>> r = move(100, 100, 60, math.pi / 6) 
>>> print(r) 
(151.96152422706632, 70.0)

实际上返回的是一个tuple! 
但是,语法上,返回一个tuple可以省略括号,  而多个变量可以同时接受一个tuple,按位置赋给对应的值。 
所以,Python的函数返回多值实际就是返回一个tuple,但是写起来更方便。  
  函数执行完毕也没有return语句时,自动return None。 
 
练习  :

import math 
def quadratic(a, b, c): 
 x1 = (-b + math.sqrt(b * b - 4 * a * c)) / (2 * a) 
 x2 = (-b - math.sqrt(b * b - 4 * a * c)) / (2 * a) 
 return x1, x2 
 
x1, x2 = quadratic(2, 5, 1) 
print(x1, x2) 
 
>>> import math 
>>> def quadratic(a, b, c): 
...  x1 = (-b + math.sqrt(b * b - 4 * a * c)) / (2 * a) 
...  x2 = (-b - math.sqrt(b * b - 4 * a * c)) / (2 * a) 
...  return x1, x2 
... 
>>> x1, x2 = quadratic(2, 5, 1) 
>>> print(x1, x2) 
-0.21922359359558485 -2.2807764064044154
Python 相关文章推荐
python实现支持目录FTP上传下载文件的方法
Jun 03 Python
Python中顺序表的实现简单代码分享
Jan 09 Python
python 地图经纬度转换、纠偏的实例代码
Aug 06 Python
python pandas实现excel转为html格式的方法
Oct 23 Python
详解爬虫被封的问题
Apr 23 Python
关于不懂Chromedriver如何配置环境变量问题解决方法
Jun 12 Python
python 读取修改pcap包的例子
Jul 23 Python
Python日志处理模块logging用法解析
May 19 Python
Pytest单元测试框架如何实现参数化
Sep 05 Python
python判断all函数输出结果是否为true的方法
Dec 03 Python
Python基于argparse与ConfigParser库进行入参解析与ini parser
Feb 02 Python
Python爬虫基础之初次使用scrapy爬虫实例
Jun 26 Python
Python使用multiprocessing实现一个最简单的分布式作业调度系统
Mar 14 #Python
简单讲解Python中的字符串与字符串的输入输出
Mar 13 #Python
深入解析Python中的list列表及其切片和迭代操作
Mar 13 #Python
Python中的列表生成式与生成器学习教程
Mar 13 #Python
jupyter安装小结
Mar 13 #Python
Ubuntu下安装PyV8
Mar 13 #Python
Python连接MySQL并使用fetchall()方法过滤特殊字符
Mar 13 #Python
You might like
PHP新手上路(九)
2006/10/09 PHP
PHP魔术方法使用方法汇总
2016/02/14 PHP
浅谈PHP中如何实现Hook机制
2017/11/14 PHP
通过百度地图获取公交线路的站点坐标的js代码
2012/05/11 Javascript
Javascript跨域请求的4种解决方式
2013/03/17 Javascript
页面加载完成后再执行JS的jquery写法以及区别说明
2014/02/22 Javascript
jQuery使用after()方法在元素后面添加多项内容的方法
2015/03/26 Javascript
js生成随机数的过程解析
2015/11/24 Javascript
使用Node.js处理前端代码文件的编码问题
2016/02/16 Javascript
分分钟学会vue中vuex的应用(入门教程)
2017/09/14 Javascript
ios设备中angularjs无法改变页面title的解决方法
2018/09/13 Javascript
微信小程序实现登录注册tab切换效果
2020/12/29 Javascript
微信小程序 调用远程接口 给全局数组赋值代码实例
2019/08/13 Javascript
vue商城中商品“筛选器”功能的实现代码
2020/07/01 Javascript
Vue实现todo应用的示例
2021/02/20 Vue.js
[01:10]3.19DOTA2发布会 三代刀塔人第一代
2014/03/25 DOTA
用Python写冒泡排序代码
2016/04/12 Python
浅析Python中MySQLdb的事务处理功能
2016/09/21 Python
Python常见MongoDB数据库操作实例总结
2018/07/24 Python
python简单鼠标自动点击某区域的实例
2019/06/25 Python
python3.x+pyqt5实现主窗口状态栏里(嵌入)显示进度条功能
2019/07/04 Python
Python定时任务工具之APScheduler使用方式
2019/07/24 Python
Python 在OpenCV里实现仿射变换—坐标变换效果
2019/08/30 Python
Python pyautogui模块实现鼠标键盘自动化方法详解
2020/02/17 Python
详解css3 flex弹性盒自动铺满写法
2020/09/17 HTML / CSS
html5 canvas绘制矩形和圆形的实例代码
2016/06/16 HTML / CSS
阿联酋航空假期:Emirates Holidays
2018/03/20 全球购物
英国办公家具网站:Furniture At Work
2019/10/07 全球购物
2014年党务公开实施方案
2014/02/27 职场文书
厨房管理计划书
2014/04/27 职场文书
建筑结构施工求职信
2014/07/11 职场文书
工伤事故赔偿协议书(标准)
2014/09/29 职场文书
CSS3实现模糊背景的三种效果示例
2021/03/30 HTML / CSS
自定义函数实现单词排序并运用于PostgreSQL(实现代码)
2021/04/22 PostgreSQL
浅谈python中的多态
2021/06/15 Python
十大最强岩石系宝可梦,怪颚龙实力最强,第七破坏力很强
2022/03/18 日漫