python中的函数---函数应用
每种编程语言中,都需要函数的参与,python同样也不例外。函数是集成的子程序,是算法实现的最小方法单位,是完成基本操作的手段的集合。编程中能够灵活应用函数,提高程序设计的简单化;实现代码应用的复用化;提升代码阅读的清晰化;加强代码开发的强健化;加快代码开发的效率化;增强团队开发的便利化;降低程序理解的复杂化;减少代码存储的减少化。总之,函数就是为实现功能或操作的独立功能块,可以返回也可以不返回值,可以返回一个值,可以返回多个值等。
一、使用内置函数:
1、简单内置函数的应用:
查看帮助,获取函数的功能和函数的参数等信息,例如想查看abs的函数信息
首先:通过命令终端输入python进入python交互模式
接着:使用help函数,参数为abs获取帮助,输入help(abs)
然后:查看帮助信息,本例中具体为
- Help on built-in function abs in module builtins:
- abs(x, /)
- Return the absolute value of the argument.
- (END)
意思很简单,具体为:返回参数的绝对值
最后:使用函数,本例中如果:
- >>> abs(9, -2)
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- TypeError: abs() takes exactly one argument (2 given)
- >>> abs(-2)
- 2
如果输入的参数有两个,则出现错误,否则就是正确的。
2、稍微复杂内置函数的应用:
查看帮助,获取函数的功能和函数的参数等信息,例如想查看max的函数信息
首先:通过命令终端输入python进入python交互模式
接着:导入math模块,使用help函数,参数为max获取帮助,输入help(max)
然后:查看帮助信息,本例中具体为
- Help on built-in function max in module builtins:
- max(...)
- max(iterable, *[, default=obj, key=func]) -> value
- max(arg1, arg2, *args, *[, key=func]) -> value
- With a single iterable argument, return its biggest item. The
- default keyword-only argument specifies an object to return if
- the provided iterable is empty.
- With two or more arguments, return the largest argument.
- (END)
意思很简单,具体为:返回参数的最大值
最后:使用函数,本例中如果:
- >>> import math
- >>> print('45, 23, 36, 21, 9, 99中最大的数为:', max(45, 23, 36, 21, 9, 99))
- 45, 23, 36, 21, 9, 99中最大的数为: 99
可以查看模块帮助:
- Help on module math:
- NAME
- math
- MODULE REFERENCE
- https://docs.python.org/3.8/library/math
- The following documentation is automatically generated from the Python
- source files. It may be incomplete, incorrect or include features that
- are considered implementation detail and may vary between Python
- implementations. When in doubt, consult the module reference at the
- location listed above.
- DESCRIPTION
- This module provides access to the mathematical functions
- defined by the C standard.
- FUNCTIONS
- acos(x, /)
- Return the arc cosine (measured in radians) of x.
- acosh(x, /)
- Return the inverse hyperbolic cosine of x.
- asin(x, /)
- Return the arc sine (measured in radians) of x.
- asinh(x, /)
- Return the inverse hyperbolic sine of x.
- atan(x, /)
- Return the arc tangent (measured in radians) of x.
- atan2(y, x, /)
- Return the arc tangent (measured in radians) of y/x.
- Unlike atan(y/x), the signs of both x and y are considered.
- atanh(x, /)
- Return the inverse hyperbolic tangent of x.
- ceil(x, /)
- Return the ceiling of x as an Integral.
- This is the smallest integer >= x.
- comb(n, k, /)
- Number of ways to choose k items from n items without repetition and without order.
- Evaluates to n! / (k! * (n - k)!) when k <= n and evaluates
- to zero when k > n.
- Also called the binomial coefficient because it is equivalent
- to the coefficient of k-th term in polynomial expansion of the
- expression (1 + x)**n.
- Raises TypeError if either of the arguments are not integers.
- Raises ValueError if either of the arguments are negative.
- copysign(x, y, /)
- Return a float with the magnitude (absolute value) of x but the sign of y.
- On platforms that support signed zeros, copysign(1.0, -0.0)
- returns -1.0.
- cos(x, /)
- Return the cosine of x (measured in radians).
- cosh(x, /)
- Return the hyperbolic cosine of x.
- degrees(x, /)
- Convert angle x from radians to degrees.
- dist(p, q, /)
- Return the Euclidean distance between two points p and q.
- The points should be specified as sequences (or iterables) of
- coordinates. Both inputs must have the same dimension.
- Roughly equivalent to:
- sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))
- erf(x, /)
- Error function at x.
- erfc(x, /)
- Complementary error function at x.
- exp(x, /)
- Return e raised to the power of x.
- expm1(x, /)
- Return exp(x)-1.
- This function avoids the loss of precision involved in the direct evaluation of exp(x)-1 for small x.
- fabs(x, /)
- Return the absolute value of the float x.
- factorial(x, /)
- Find x!.
- Raise a ValueError if x is negative or non-integral.
- floor(x, /)
- Return the floor of x as an Integral.
- This is the largest integer <= x.
- fmod(x, y, /)
- Return fmod(x, y), according to platform C.
- x % y may differ.
- frexp(x, /)
- Return the mantissa and exponent of x, as pair (m, e).
- m is a float and e is an int, such that x = m * 2.**e.
- If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0.
- fsum(seq, /)
- Return an accurate floating point sum of values in the iterable seq.
- Assumes IEEE-754 floating point arithmetic.
- gamma(x, /)
- Gamma function at x.
- gcd(x, y, /)
- greatest common divisor of x and y
- hypot(...)
- hypot(*coordinates) -> value
- Multidimensional Euclidean distance from the origin to a point.
- Roughly equivalent to:
- sqrt(sum(x**2 for x in coordinates))
- For a two dimensional point (x, y), gives the hypotenuse
- using the Pythagorean theorem: sqrt(x*x + y*y).
- For example, the hypotenuse of a 3/4/5 right triangle is:
- >>> hypot(3.0, 4.0)
- 5.0
- isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)
- Determine whether two floating point numbers are close in value.
- rel_tol
- maximum difference for being considered "close", relative to the
- magnitude of the input values
- abs_tol
- maximum difference for being considered "close", regardless of the
- magnitude of the input values
- Return True if a is close in value to b, and False otherwise.
- For the values to be considered close, the difference between them
- must be smaller than at least one of the tolerances.
- -inf, inf and NaN behave similarly to the IEEE 754 Standard. That
- is, NaN is not close to anything, even itself. inf and -inf are
- only close to themselves.
- isfinite(x, /)
- Return True if x is neither an infinity nor a NaN, and False otherwise.
- isinf(x, /)
- Return True if x is a positive or negative infinity, and False otherwise.
- isnan(x, /)
- Return True if x is a NaN (not a number), and False otherwise.
- isqrt(n, /)
- Return the integer part of the square root of the input.
- ldexp(x, i, /)
- Return x * (2**i).
- This is essentially the inverse of frexp().
- lgamma(x, /)
- Natural logarithm of absolute value of Gamma function at x.
- log(...)
- log(x, [base=math.e])
- Return the logarithm of x to the given base.
- If the base not specified, returns the natural logarithm (base e) of x.
- log10(x, /)
- Return the base 10 logarithm of x.
- log1p(x, /)
- Return the natural logarithm of 1+x (base e).
- The result is computed in a way which is accurate for x near zero.
- log2(x, /)
- Return the base 2 logarithm of x.
- modf(x, /)
- Return the fractional and integer parts of x.
- Both results carry the sign of x and are floats.
- perm(n, k=None, /)
- Number of ways to choose k items from n items without repetition and with order.
- Evaluates to n! / (n - k)! when k <= n and evaluates
- to zero when k > n.
- If k is not specified or is None, then k defaults to n
- and the function returns n!.
- Raises TypeError if either of the arguments are not integers.
- Raises ValueError if either of the arguments are negative.
- pow(x, y, /)
- Return x**y (x to the power of y).
- prod(iterable, /, *, start=1)
- Calculate the product of all the elements in the input iterable.
- The default start value for the product is 1.
- When the iterable is empty, return the start value. This function is
- intended specifically for use with numeric values and may reject
- non-numeric types.
- radians(x, /)
- Convert angle x from degrees to radians.
- remainder(x, y, /)
- Difference between x and the closest integer multiple of y.
- Return x - n*y where n*y is the closest integer multiple of y.
- In the case where x is exactly halfway between two multiples of
- y, the nearest even value of n is used. The result is always exact.
- sin(x, /)
- Return the sine of x (measured in radians).
- sinh(x, /)
- Return the hyperbolic sine of x.
- sqrt(x, /)
- Return the square root of x.
- tan(x, /)
- Return the tangent of x (measured in radians).
- tanh(x, /)
- Return the hyperbolic tangent of x.
- trunc(x, /)
- Truncates the Real x to the nearest Integral toward 0.
- Uses the __trunc__ magic method.
- DATA
- e = 2.718281828459045
- inf = inf
- nan = nan
- pi = 3.141592653589793
- tau = 6.283185307179586
- FILE
- /usr/lib/python3.8/lib-dynload/math.cpython-38-aarch64-linux-gnu.so
一下子可以查看模块中的所有函数。
3、随机函数需要导入random
- print('return item from list:', random.choice(['spring', 'summer','autumn', 'winter']))
- return item from list: autumn
- >>> print('return item from list:', random.choice((27, 95, 68, 75,44)))
- return item from list: 27
- >>> print('return item from list:', random.choice('hello world!'))
- return item from list: o
- >>> print('return item from list:', random.sample(['spring', 'summer','autumn', 'winter'], 2))
- return item from list: ['spring', 'summer']
- >>> print('return item from list:', random.sample((27, 95, 68, 75,44),2))
- return item from list: [44, 75]
- >>> print('return item from list:', random.sample('hello world!', 5))
- return item from list: ['r', '!', 'o', 'w', 'o']
- >>> print('return item from list:', random.randint(1, 100))
- return item from list: 29
- >>> print('return item from list:', random.randint(50, 100))
- return item from list: 55
- >>> print('return item from list:', random.uniform(50, 100))
- return item from list: 57.86905642417648
- print('return item from list:', random.random())return item from list: 0.059261740874653634
- >>> random.seed(1000)
- >>> print('return item from list:', random.random())
- return item from list: 0.7773566427005639
- >>> random.seed('helloworld', 2)
- >>> print('return item from list:', random.random())
- return item from list: 0.7513369593825964
4、三角函数需要导入math
- >>> print('acos(0.5):', math.acos(0.5))
- acos(0.5): 1.0471975511965979
- >>> print('cos(math.pi/4):', math.cos(math.pi/4))
- cos(math.pi/4): 0.7071067811865476
- >>> print('sin(math.pi/4):', math.sin(math.pi/4))
- sin(math.pi/4): 0.7071067811865475
- >>> print('tan(math.pi/4):', math.tan(math.pi/4))
- tan(math.pi/4): 0.9999999999999999
- >>> print('atan(1):', math.atan(1))
- atan(1): 0.7853981633974483
5、字符串函数需要导入不用导入
python中的函数---函数应用的更多相关文章
- python --- Python中的callable 函数
python --- Python中的callable 函数 转自: http://archive.cnblogs.com/a/1798319/ Python中的callable 函数 callabl ...
- python中使用zip函数出现<zip object at 0x02A9E418>
在Python中使用zip函数,出现<zip object at 0x02A9E418>错误的原因是,你是用的是python2点多的版本,python3.0对python做了改动 zip方 ...
- [转载]python中multiprocessing.pool函数介绍
原文地址:http://blog.sina.com.cn/s/blog_5fa432b40101kwpi.html 作者:龙峰 摘自:http://hi.baidu.com/xjtukanif/blo ...
- Python 中的isinstance函数
解释: Python 中的isinstance函数,isinstance是Python中的一个内建函数 语法: isinstance(object, classinfo) 如果参数object是cla ...
- Python中的map()函数和reduce()函数的用法
Python中的map()函数和reduce()函数的用法 这篇文章主要介绍了Python中的map()函数和reduce()函数的用法,代码基于Python2.x版本,需要的朋友可以参考下 Py ...
- python中multiprocessing.pool函数介绍_正在拉磨_新浪博客
python中multiprocessing.pool函数介绍_正在拉磨_新浪博客 python中multiprocessing.pool函数介绍 (2010-06-10 03:46:5 ...
- 举例详解Python中的split()函数的使用方法
这篇文章主要介绍了举例详解Python中的split()函数的使用方法,split()函数的使用是Python学习当中的基础知识,通常用于将字符串切片并转换为列表,需要的朋友可以参考下 函数:sp ...
- python中的生成器函数是如何工作的?
以下内容基于python3.4 1. python中的普通函数是怎么运行的? 当一个python函数在执行时,它会在相应的python栈帧上运行,栈帧表示程序运行时函数调用栈中的某一帧.想要获得某个函 ...
- python中的map()函数
MapReduce的设计灵感来自于函数式编程,这里不打算提MapReduce,就拿python中的map()函数来学习一下. 文档中的介绍在这里: map(function, iterable, .. ...
- 揭秘 Python 中的 enumerate() 函数
原文:https://mp.weixin.qq.com/s/Jm7YiCA20RDSTrF4dHeykQ 如何以去写以及为什么你应该使用Python中的内置枚举函数来编写更干净更加Pythonic的循 ...
随机推荐
- 爬虫多次爬取时候cookie的存储用于登入
一.用requests模块自动保存(保存缓存中) 构建一个session对象session = requests.session() 用构建的session代替requests进行访问他就会自动存啦 ...
- 2019 讯飞java面试笔试题 (含面试题解析)
本人5年开发经验.18年年底开始跑路找工作,在互联网寒冬下成功拿到阿里巴巴.今日头条.讯飞等公司offer,岗位是Java后端开发,因为发展原因最终选择去了讯飞,入职一年时间了,也成为了面试官,之 ...
- 2019 新浪 java面试笔试题 (含面试题解析)
本人5年开发经验.18年年底开始跑路找工作,在互联网寒冬下成功拿到阿里巴巴.今日头条.新浪等公司offer,岗位是Java后端开发,因为发展原因最终选择去了新浪,入职一年时间了,也成为了面试官,之 ...
- 05、MySQL—字符集
1.字符编码概念 字符(Character)是各种文字和符号的总称,包括各国家文字.标点符号.图形符号.数字等. 在计算机中所看到的任何内容都是字符构成的. 字符编码(character code)是 ...
- 在Centos6.5上部署kvm虚拟化技术
KVM是什么? KVM 全称是 基于内核的虚拟机(Kernel-based Virtual Machine),它是一个 Linux 的一个内核模块,该内核模块使得 Linux 变成了一个 Hyperv ...
- 水泥caement单词
Caement英语单词,翻译为:水泥 中文名:水泥 外文名:caement 目录 释义 caement 读音:英 [sɪˈment] 美 [sɪˈmɛnt] Noun名词. 水泥; caement在英 ...
- 如何选择优秀的APS系统供应商?问自己这几个问题!
高级的计划和排程和生产排程软件的好处是巨大的.然而,生产排程软件不是商品,尚不能保证您选择的任何高级的计划和排程软件能满足您的所有需求. 那么,我们来谈谈如何选择适合你的公司最好的生产排程软件.这需要 ...
- MongoDB 目录分析、基础命令、参数设置
目录分析 1.整体目录 以msi默认的data.log路径安装,才会有data.log文件夹. 2.bin目录 3.log目录 基础命令 1.服务器端基础命令 net start MongoDB ...
- 关于MySQL数据库编码修复相关问题
本篇主要是本人在实际开发过程中遇到的MySQL字符编码等bug修复相关问题. 在使用下列语句在执行数据库表通过flask-sqlacodegen 进行ORM映射成模型类的时候发生的bug: flask ...
- admin端的教师管理功能测试
1 概述 1.1 测试范围 本次所测试的内容是admin端的教师管理功能. 1.2 测试方法 采用黑盒子方法进行集成测试. 1.3 测试环境 (1) 服务器l 操作系统:Windo ...