Python(3)——函数
来源:互联网 发布:cpu故障检测软件 编辑:程序博客网 时间:2024/06/06 20:23
/============================
以下所有内容,均来自 廖雪峰 的官方网站,
Python 教程。
链接地址:http://www.liaoxuefeng.com
============================/
在 JavaScript 中我们经常做的就是将实现一个功能的所有代码封装进一个函数里面,只留出参数接口,供调用者自定义。python 中的函数也是一样,而且 python 同样内置了很多有用的函数,可供直接调用。
1、调用函数
内置函数的调用:
abs() 函数的作用是取绝对值,我们使用只需要 abs(12.34)。
自定义函数调用:
#!/usr/bin/python# -*- coding: utf-8 -*-# 引入数学模块中的方法from math import sqrtfrom math import tan'''高阶函数应用,返回一个数字不同方法计算结果'''def same(num, *kw): # 参数检查 if not isinstance(num, (int, float)): raise TypeError('bad operand type') # 初始化结果字典 rel = {} # 循环计算可变参数 for func in kw: try: rel[func.__name__] = func(num) except ValueError: rel[func.__name__] = 'None' # 返回结果字典 return rel# 函数调用result = same(-10.5, sqrt, abs, tan)# 结果输出print(result)
same( )
就是一个定义的函数,result = same(-10.5, sqrt, abs, tan)
是函数调用。
2、定义函数
def calc(numbers): sum = 0 for n in numbers: sum = sum + n*n return sum# list数组print(calc([1,2,3]))# tuple元祖print(calc((1,2,3)))
def calc(numbers):表示定义一个函数
函数体内部的语句在执行时,一旦执行到return时,函数就执行完毕,并将结果返回。因此,函数内部通过条件判断和循环可以实现非常复杂的逻辑。
3、函数的参数
普通参数:
def calc(numbers): sum = 0 for n in numbers: sum = sum + n*n return sum# list数组print(calc([1,2,3]))# tuple元祖print(calc((1,2,3)))
结果:14 14
可变参数:
# 可变参数def calc1(*numbers): sum = 0 for n in numbers: sum = sum + n*n return sumprint(calc1(1,2,3,4))
结果:30
关键字参数:
# 关键字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)data = { 'Adam Lee': 99, 'Lisa S': 88, 'F.Bart': 77}print_scores(**data)
结果:
Name Score------------------ Adam 99 Bart 77 Lisa 88 Name Score------------------ Lisa S 88 Adam Lee 99 F.Bart 77
key 可以参入 dict 键值对形式的参数。
4、递归函数
def fact(n): if n==1: return 1 return n*fact(n-1)n = input('请输入n:')n = int(n)print(fact(n))
结果:
请输入n:103628800
如果我们计算fact(5),可以根据函数定义看到计算过程如下:
===> fact(5)===> 5 * fact(4)===> 5 * (4 * fact(3))===> 5 * (4 * (3 * fact(2)))===> 5 * (4 * (3 * (2 * fact(1))))===> 5 * (4 * (3 * (2 * 1)))===> 5 * (4 * (3 * 2))===> 5 * (4 * 6)===> 5 * 24===> 120
0 0
- Python(3)——函数
- python——函数
- Python——函数
- Python—定义函数
- Python函数—基础
- Python函数—参数
- Python初学(6)——Python的函数
- Python学习笔记(六)——Python 函数
- Python(3)————函数
- Python笔记(3)——控制语句和函数
- 兄弟连学python(3)——函数文档
- Python笔记3——函数
- Python——随机函数(random)
- Python学习(四)——函数
- python基础(04)——函数
- Python学习笔记(六)— 函数
- 兄弟连学Python(1)— 函数
- 【Python】【3】Python之——从HelloWorld开始(四则运算,简单函数以及简单模块)
- Grails
- 利用Base64编码加密解密文本
- teechart Pro Activex control V8摸索
- Ambari离线部署Hadoop集群踩到的坑
- dapper关联关系查询小测试
- Python(3)——函数
- Android:数据存储之SQLite
- Collections类方法
- B树、B+树
- linux ./configure 的参数详解
- 【Django】-- django.db.migrations.exceptions.InconsistentMigrationHistory
- onCreateView 与onActivityCreated 的区别
- 二叉树先序遍历(包含递归和非递归(2种方法))
- selectionSort