每种编程语言中,都需要函数的参与,python同样也不例外。函数是集成的子程序,是算法实现的最小方法单位,是完成基本操作的手段的集合。编程中能够灵活应用函数,提高程序设计的简单化;实现代码应用的复用化;提升代码阅读的清晰化;加强代码开发的强健化;加快代码开发的效率化;增强团队开发的便利化;降低程序理解的复杂化;减少代码存储的减少化。总之,函数就是为实现功能或操作的独立功能块,可以返回也可以不返回值,可以返回一个值,可以返回多个值等。

  一、使用内置函数:

  1、简单内置函数的应用:

  查看帮助,获取函数的功能和函数的参数等信息,例如想查看abs的函数信息

  首先:通过命令终端输入python进入python交互模式

  接着:使用help函数,参数为abs获取帮助,输入help(abs)

  然后:查看帮助信息,本例中具体为  

  1. Help on built-in function abs in module builtins:
  2.  
  3. abs(x, /)
  4. Return the absolute value of the argument.
  5. (END)

  意思很简单,具体为:返回参数的绝对值

  最后:使用函数,本例中如果:

  1. >>> abs(9, -2)
  2. Traceback (most recent call last):
  3. File "<stdin>", line 1, in <module>
  4. TypeError: abs() takes exactly one argument (2 given)
  5. >>> abs(-2)
  6. 2

  如果输入的参数有两个,则出现错误,否则就是正确的。

  2、稍微复杂内置函数的应用:  

  查看帮助,获取函数的功能和函数的参数等信息,例如想查看max的函数信息

  首先:通过命令终端输入python进入python交互模式

  接着:导入math模块,使用help函数,参数为max获取帮助,输入help(max)

  然后:查看帮助信息,本例中具体为

  1. Help on built-in function max in module builtins:
  2.  
  3. max(...)
  4. max(iterable, *[, default=obj, key=func]) -> value
  5. max(arg1, arg2, *args, *[, key=func]) -> value
  6.  
  7. With a single iterable argument, return its biggest item. The
  8. default keyword-only argument specifies an object to return if
  9. the provided iterable is empty.
  10. With two or more arguments, return the largest argument.
  11. (END)

  意思很简单,具体为:返回参数的最大值

  最后:使用函数,本例中如果:

  1. >>> import math
  2. >>> print('45, 23, 36, 21, 9, 99中最大的数为:', max(45, 23, 36, 21, 9, 99))
  3. 45, 23, 36, 21, 9, 99中最大的数为: 99

  可以查看模块帮助:

  1. Help on module math:
  2.  
  3. NAME
  4. math
  5.  
  6. MODULE REFERENCE
  7. https://docs.python.org/3.8/library/math
  8.  
  9. The following documentation is automatically generated from the Python
  10. source files. It may be incomplete, incorrect or include features that
  11. are considered implementation detail and may vary between Python
  12. implementations. When in doubt, consult the module reference at the
  13. location listed above.
  14.  
  15. DESCRIPTION
  16. This module provides access to the mathematical functions
  17. defined by the C standard.
  18.  
  19. FUNCTIONS
  20. acos(x, /)
  21. Return the arc cosine (measured in radians) of x.
  22.  
  23. acosh(x, /)
  24. Return the inverse hyperbolic cosine of x.
  25.  
  26. asin(x, /)
  27. Return the arc sine (measured in radians) of x.
  28.  
  29. asinh(x, /)
  30. Return the inverse hyperbolic sine of x.
  31.  
  32. atan(x, /)
  33. Return the arc tangent (measured in radians) of x.
  34.  
  35. atan2(y, x, /)
  36. Return the arc tangent (measured in radians) of y/x.
  37.  
  38. Unlike atan(y/x), the signs of both x and y are considered.
  39.  
  40. atanh(x, /)
  41. Return the inverse hyperbolic tangent of x.
  42.  
  43. ceil(x, /)
  44. Return the ceiling of x as an Integral.
  45.  
  46. This is the smallest integer >= x.
  47.  
  48. comb(n, k, /)
  49. Number of ways to choose k items from n items without repetition and without order.
  50.  
  51. Evaluates to n! / (k! * (n - k)!) when k <= n and evaluates
  52. to zero when k > n.
  53.  
  54. Also called the binomial coefficient because it is equivalent
  55. to the coefficient of k-th term in polynomial expansion of the
  56. expression (1 + x)**n.
  57.  
  58. Raises TypeError if either of the arguments are not integers.
  59. Raises ValueError if either of the arguments are negative.
  60.  
  61. copysign(x, y, /)
  62. Return a float with the magnitude (absolute value) of x but the sign of y.
  63.  
  64. On platforms that support signed zeros, copysign(1.0, -0.0)
  65. returns -1.0.
  66.  
  67. cos(x, /)
  68. Return the cosine of x (measured in radians).
  69.  
  70. cosh(x, /)
  71. Return the hyperbolic cosine of x.
  72.  
  73. degrees(x, /)
  74. Convert angle x from radians to degrees.
  75.  
  76. dist(p, q, /)
  77. Return the Euclidean distance between two points p and q.
  78.  
  79. The points should be specified as sequences (or iterables) of
  80. coordinates. Both inputs must have the same dimension.
  81.  
  82. Roughly equivalent to:
  83. sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))
  84.  
  85. erf(x, /)
  86. Error function at x.
  87.  
  88. erfc(x, /)
  89. Complementary error function at x.
  90.  
  91. exp(x, /)
  92. Return e raised to the power of x.
  93.  
  94. expm1(x, /)
  95. Return exp(x)-1.
  96.  
  97. This function avoids the loss of precision involved in the direct evaluation of exp(x)-1 for small x.
  98.  
  99. fabs(x, /)
  100. Return the absolute value of the float x.
  101.  
  102. factorial(x, /)
  103. Find x!.
  104.  
  105. Raise a ValueError if x is negative or non-integral.
  106.  
  107. floor(x, /)
  108. Return the floor of x as an Integral.
  109.  
  110. This is the largest integer <= x.
  111.  
  112. fmod(x, y, /)
  113. Return fmod(x, y), according to platform C.
  114.  
  115. x % y may differ.
  116.  
  117. frexp(x, /)
  118. Return the mantissa and exponent of x, as pair (m, e).
  119.  
  120. m is a float and e is an int, such that x = m * 2.**e.
  121. If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0.
  122.  
  123. fsum(seq, /)
  124. Return an accurate floating point sum of values in the iterable seq.
  125.  
  126. Assumes IEEE-754 floating point arithmetic.
  127.  
  128. gamma(x, /)
  129. Gamma function at x.
  130.  
  131. gcd(x, y, /)
  132. greatest common divisor of x and y
  133.  
  134. hypot(...)
  135. hypot(*coordinates) -> value
  136.  
  137. Multidimensional Euclidean distance from the origin to a point.
  138.  
  139. Roughly equivalent to:
  140. sqrt(sum(x**2 for x in coordinates))
  141.  
  142. For a two dimensional point (x, y), gives the hypotenuse
  143. using the Pythagorean theorem: sqrt(x*x + y*y).
  144.  
  145. For example, the hypotenuse of a 3/4/5 right triangle is:
  146.  
  147. >>> hypot(3.0, 4.0)
  148. 5.0
  149.  
  150. isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)
  151. Determine whether two floating point numbers are close in value.
  152. rel_tol
  153. maximum difference for being considered "close", relative to the
  154. magnitude of the input values
  155. abs_tol
  156. maximum difference for being considered "close", regardless of the
  157. magnitude of the input values
  158.  
  159. Return True if a is close in value to b, and False otherwise.
  160.  
  161. For the values to be considered close, the difference between them
  162. must be smaller than at least one of the tolerances.
  163.  
  164. -inf, inf and NaN behave similarly to the IEEE 754 Standard. That
  165. is, NaN is not close to anything, even itself. inf and -inf are
  166. only close to themselves.
  167.  
  168. isfinite(x, /)
  169. Return True if x is neither an infinity nor a NaN, and False otherwise.
  170.  
  171. isinf(x, /)
  172. Return True if x is a positive or negative infinity, and False otherwise.
  173.  
  174. isnan(x, /)
  175. Return True if x is a NaN (not a number), and False otherwise.
  176.  
  177. isqrt(n, /)
  178. Return the integer part of the square root of the input.
  179.  
  180. ldexp(x, i, /)
  181. Return x * (2**i).
  182.  
  183. This is essentially the inverse of frexp().
  184.  
  185. lgamma(x, /)
  186. Natural logarithm of absolute value of Gamma function at x.
  187.  
  188. log(...)
  189. log(x, [base=math.e])
  190. Return the logarithm of x to the given base.
  191.  
  192. If the base not specified, returns the natural logarithm (base e) of x.
  193.  
  194. log10(x, /)
  195. Return the base 10 logarithm of x.
  196.  
  197. log1p(x, /)
  198. Return the natural logarithm of 1+x (base e).
  199.  
  200. The result is computed in a way which is accurate for x near zero.
  201.  
  202. log2(x, /)
  203. Return the base 2 logarithm of x.
  204.  
  205. modf(x, /)
  206. Return the fractional and integer parts of x.
  207.  
  208. Both results carry the sign of x and are floats.
  209.  
  210. perm(n, k=None, /)
  211. Number of ways to choose k items from n items without repetition and with order.
  212.  
  213. Evaluates to n! / (n - k)! when k <= n and evaluates
  214. to zero when k > n.
  215.  
  216. If k is not specified or is None, then k defaults to n
  217. and the function returns n!.
  218.  
  219. Raises TypeError if either of the arguments are not integers.
  220. Raises ValueError if either of the arguments are negative.
  221.  
  222. pow(x, y, /)
  223. Return x**y (x to the power of y).
  224.  
  225. prod(iterable, /, *, start=1)
  226. Calculate the product of all the elements in the input iterable.
  227.  
  228. The default start value for the product is 1.
  229.  
  230. When the iterable is empty, return the start value. This function is
  231. intended specifically for use with numeric values and may reject
  232. non-numeric types.
  233.  
  234. radians(x, /)
  235. Convert angle x from degrees to radians.
  236.  
  237. remainder(x, y, /)
  238. Difference between x and the closest integer multiple of y.
  239.  
  240. Return x - n*y where n*y is the closest integer multiple of y.
  241. In the case where x is exactly halfway between two multiples of
  242. y, the nearest even value of n is used. The result is always exact.
  243.  
  244. sin(x, /)
  245. Return the sine of x (measured in radians).
  246.  
  247. sinh(x, /)
  248. Return the hyperbolic sine of x.
  249.  
  250. sqrt(x, /)
  251. Return the square root of x.
  252.  
  253. tan(x, /)
  254. Return the tangent of x (measured in radians).
  255.  
  256. tanh(x, /)
  257. Return the hyperbolic tangent of x.
  258.  
  259. trunc(x, /)
  260. Truncates the Real x to the nearest Integral toward 0.
  261.  
  262. Uses the __trunc__ magic method.
  263.  
  264. DATA
  265. e = 2.718281828459045
  266. inf = inf
  267. nan = nan
  268. pi = 3.141592653589793
  269. tau = 6.283185307179586
  270.  
  271. FILE
  272. /usr/lib/python3.8/lib-dynload/math.cpython-38-aarch64-linux-gnu.so

  一下子可以查看模块中的所有函数。

  3、随机函数需要导入random

  1. print('return item from list:', random.choice(['spring', 'summer','autumn', 'winter']))
  2. return item from list: autumn
  3. >>> print('return item from list:', random.choice((27, 95, 68, 75,44)))
  4. return item from list: 27
  5. >>> print('return item from list:', random.choice('hello world!'))
  6. return item from list: o
  7. >>> print('return item from list:', random.sample(['spring', 'summer','autumn', 'winter'], 2))
  8. return item from list: ['spring', 'summer']
  9. >>> print('return item from list:', random.sample((27, 95, 68, 75,44),2))
  10. return item from list: [44, 75]
  11. >>> print('return item from list:', random.sample('hello world!', 5))
  12. return item from list: ['r', '!', 'o', 'w', 'o']
  13. >>> print('return item from list:', random.randint(1, 100))
  14. return item from list: 29
  15. >>> print('return item from list:', random.randint(50, 100))
  16. return item from list: 55
  17. >>> print('return item from list:', random.uniform(50, 100))
  18. return item from list: 57.86905642417648
  19. print('return item from list:', random.random())return item from list: 0.059261740874653634
  20. >>> random.seed(1000)
  21. >>> print('return item from list:', random.random())
  22. return item from list: 0.7773566427005639
  23. >>> random.seed('helloworld', 2)
  24. >>> print('return item from list:', random.random())
  25. return item from list: 0.7513369593825964

  4、三角函数需要导入math

  1. >>> print('acos(0.5):', math.acos(0.5))
  2. acos(0.5): 1.0471975511965979
  3. >>> print('cos(math.pi/4):', math.cos(math.pi/4))
  4. cos(math.pi/4): 0.7071067811865476
  5. >>> print('sin(math.pi/4):', math.sin(math.pi/4))
  6. sin(math.pi/4): 0.7071067811865475
  7. >>> print('tan(math.pi/4):', math.tan(math.pi/4))
  8. tan(math.pi/4): 0.9999999999999999
  9. >>> print('atan(1):', math.atan(1))
  10. atan(1): 0.7853981633974483

  5、字符串函数需要导入不用导入

python中的函数---函数应用的更多相关文章

  1. python --- Python中的callable 函数

    python --- Python中的callable 函数 转自: http://archive.cnblogs.com/a/1798319/ Python中的callable 函数 callabl ...

  2. python中使用zip函数出现<zip object at 0x02A9E418>

    在Python中使用zip函数,出现<zip object at 0x02A9E418>错误的原因是,你是用的是python2点多的版本,python3.0对python做了改动 zip方 ...

  3. [转载]python中multiprocessing.pool函数介绍

    原文地址:http://blog.sina.com.cn/s/blog_5fa432b40101kwpi.html 作者:龙峰 摘自:http://hi.baidu.com/xjtukanif/blo ...

  4. Python 中的isinstance函数

    解释: Python 中的isinstance函数,isinstance是Python中的一个内建函数 语法: isinstance(object, classinfo) 如果参数object是cla ...

  5. Python中的map()函数和reduce()函数的用法

    Python中的map()函数和reduce()函数的用法 这篇文章主要介绍了Python中的map()函数和reduce()函数的用法,代码基于Python2.x版本,需要的朋友可以参考下   Py ...

  6. python中multiprocessing.pool函数介绍_正在拉磨_新浪博客

    python中multiprocessing.pool函数介绍_正在拉磨_新浪博客     python中multiprocessing.pool函数介绍    (2010-06-10 03:46:5 ...

  7. 举例详解Python中的split()函数的使用方法

    这篇文章主要介绍了举例详解Python中的split()函数的使用方法,split()函数的使用是Python学习当中的基础知识,通常用于将字符串切片并转换为列表,需要的朋友可以参考下   函数:sp ...

  8. python中的生成器函数是如何工作的?

    以下内容基于python3.4 1. python中的普通函数是怎么运行的? 当一个python函数在执行时,它会在相应的python栈帧上运行,栈帧表示程序运行时函数调用栈中的某一帧.想要获得某个函 ...

  9. python中的map()函数

    MapReduce的设计灵感来自于函数式编程,这里不打算提MapReduce,就拿python中的map()函数来学习一下. 文档中的介绍在这里: map(function, iterable, .. ...

  10. 揭秘 Python 中的 enumerate() 函数

    原文:https://mp.weixin.qq.com/s/Jm7YiCA20RDSTrF4dHeykQ 如何以去写以及为什么你应该使用Python中的内置枚举函数来编写更干净更加Pythonic的循 ...

随机推荐

  1. IDEA和Eclipse启动优化

    昨天对比了下IDEA和Eclipse的启动速度,发现IDEA启动真的是好慢啊!!! 电脑配置:8G win7 IDEA启动配置 -Xms1024m -Xmx1024m -Xmn500m -XX:Met ...

  2. IntelliJ idea鼠标移动到类上显示文档document(javadoc)内容

    IntelliJ idea鼠标移动到类上显示文档document(javadoc)内容 Step 1:设置鼠标移动到类上自动显示Javadoc文档 step2:为jdk下载javadoc Step3: ...

  3. cs/bs架构的区别

    Client/Server是建立在局域网的基础上的,基于客户端/服务器,安全,响应快,维护难度大,不易拓展,用户面固定,需要相同的操作系统. Browser/Server是建立在广域网的基础上的,基于 ...

  4. CI隐藏入口文件index.php

    1.需要apache打开rewrite_module,然后修改httpd.conf的AllowOverride none 为AllowOverride All(里面,不同的环境目录不同) 2.在CI的 ...

  5. CentOS 7 - 修改时区为上海时区

    1.查看时间各种状态: timedatectl Local time: 四 2014-12-25 10:52:10 CSTUniversal time: 四 2014-12-25 02:52:10 U ...

  6. 关闭linux命令行屏幕保护

    # setterm -blank 0

  7. idea2018.3导入grails项目,无法正常使用问题解决

    注:作者的grails版本为2.0.4,grails3版本以上的导入方式为gradle方式 一.导入grails项目 1.启动新项目向导.如果IntelliJ IDEA目前没有打开任何项目,请在欢迎屏 ...

  8. php 文件包含 include、include_once、require、require_once

    简言之,include某文件:把某文件的代码粘过来,如果该文件不存在,也继续执行下面的代码,带_once的是看看之前引用过没,引用过就不引用了(_once这行代码的心里活动:“之后引用过没有我不关心, ...

  9. C程序中的内存分布

    一个典型的C程序存储分区包含以下几类: Text段 已初始化数据段 未初始化数据段 栈 堆 进程运行时的典型内存布局 1. Text段 Text段通常也称为代码段,由可执行指令构成,是程序在目标文件或 ...

  10. python+BeautifulSoup+多进程爬取糗事百科图片

    用到的库: import requests import os from bs4 import BeautifulSoup import time from multiprocessing impor ...