[转载] python函数分为哪几种_python常用函数

参考链接: Python中的等分算法函数bisect

Python常用函数

 python中函数以两种形式呈现:一是可以自己定义的函数function,比如最常用的print()函数;另外一种是作为类的方法method调用,比如turtle.shapesize()。这两种形式本质上是相同的,不过是叫法不同,背后的语法实现细节我们没有必要深入研究。

 无论是作为function还是method存在的函数,我们都是可以自定义的。首先我会给大家介绍常见函数的使用,最后以python中的turtle绘图为例向大家讲解python中函数的自定义及其蕴含的抽象思想,并且通过绘图的例子来向大家展示利用函数逐步进行抽象的过程。

 函数的存在,大大提高了编程的效率,与传统的命令式编程相比,可以有效的降低代码数量,通过合理的定义函数,合理的使用函数参数,可以让程序更加简洁。python中的函数定义比较简单,但是函数参数的位置参数,关键字参数,默认参数、可变参数等理解起来比较困难。

 下面介绍常用函数的使用

 Print

 print函数可以说是python中常用的函数,然而正是因为print是最常用的函数,大家往往在使用print函数的时候,忽视了print函数的强大功能

 基础用法

 print("Hello World!") # 这可能是print最简单的用法了,学习任何一门语言我们习惯上都会说Hello World!

 Hello World!

 在上面的例子中,我们直接调用了print函数,这样就可以在控制台输出内容,请注意,print是方法的名称后面跟着括号;括号里是要打印的内容,这里打印的 是字符串。如果想要打印多个字符串可以用逗号分隔要打印的内容。

 print("Wanderfull", "qingdao", "IT Teacher")

 Wanderfull qingdao IT Teacher

 可以看到,我们用逗号分隔了要打印的字符串。print还可以直接输出数字:

 print("Hello world!", 123)

 Hello world! 123

 我们还可以在print中输出变量值

 name = 'langxm'

 age = '28'

 corp = "NetEase"

 print("hello my name is", name, " i am ", age, " i worked at ", corp)

 hello my name is langxm i am 28 i worked at NetEase

 可以看到通过逗号分隔的方式,print完整的输出了一句话,但是这并非最简单的方式,这里就要用到格式化字符串的方法了format了嘛

 name = 'langxm'

 age = '28'

 corp = "NetEase"

 print("hello my name is {} i am {} i worked at {}".format(name, age, corp))

 hello my name is langxm i am 28 i worked at NetEase

 可以看到print输出了跟上面一样的句子。format函数的使用大大的简化了格式化字符串的输出,这就是最常用的用法了;其实print函数的强大远不止如此

 就像c语言中的printf函数一样,print有强大的格式控制功能,感兴趣的老师可以参考http://blog.csdn.net/wchoclate/article/details/42297173

 str函数和int函数

 str函数的作用是把数字等类型换换为字符串

 int函数的作用是把字符串转为数字

 type(1) # type函数的作用查看变量或者值的具体类型,我们可以看到1的类型是int

 int

 type('1')

 str

 可以看到type函数返回的类型是str也就是字符串类型,用途是什么呢?比如我们要做一个猜数字或者答数学题的程序,我们通过input函数获取的用户的输入,其实是字符串类型,我们需要转化为数字才能进行运算的

 a = input()

 b = input()

 print("a的类型是{}".format(type(a)))

 print("b的类型是{}".format(type(b)))

 print(a + b)

 2

 3

 a的类型是

 b的类型是

 23

 我们可以看到利用input函数得到的用户输入的类型是字符串类型,字符串相加跟数值相加运算是不同的,我们预期的结果是2 + 3 = 5 然而实际上程序的结果是23,很明显程序出问题了,那么正确的做法是什么呢?正确的做法是转换变量类型。

 a = input()

 b = input()

 print("a的类型是{}".format(type(a)))

 print("b的类型是{}".format(type(b)))

 print(int(a) + int(b))

 2

 3

 a的类型是

 b的类型是

 5

 可以看到虽然输入的仍然是str类型,但是我们在求和的时候把字符串类型的变量a和b转换为了整数类型,保证了运算结果的准确性。但是大家要注意的是a和b的类型其实还是字符串

 a = input()

 b = input()

 print("a的类型是{}".format(type(a)))

 print("b的类型是{}".format(type(b)))

 print(int(a) + int(b))

 print("a的类型是{}".format(type(a)))

 print("b的类型是{}".format(type(b)))

 2

 3

 a的类型是

 b的类型是

 5

 a的类型是

 b的类型是

 既然a和b的类型没变为什么结果是正确的呢,因为我们是分别把a和b转换成了整数,其实这时候int(a)和int(b)与a和b是不同的变量了,我们实际进行加法运算的并非a和b而是int(a)和int(b),因为在python中基础的数值,字符串等都是不可变类型,我们不可以在变量本身做更改的。

 拓展

 a = int(input())

 b = int(input())

 print("a的类型是{}".format(type(a)))

 print("b的类型是{}".format(type(b)))

 print(a + b)

 print("a的类型是{}".format(type(a)))

 print("b的类型是{}".format(type(b)))

 2

 3

 a的类型是

 b的类型是

 5

 a的类型是

 b的类型是

 仔细观察上面的代码与之前代码的区别,体会那种写法更方便,如果小数相加应该怎么办呢?要用到float函数了。

 数学常用函数

 上面介绍了最基本的常用函数,那么下面我们来介绍一下python中的数学常用函数。

 python是一门胶水语言,有着丰富的第三方库,而在python中,很多常用的功能都成为了python本身的标准模块,也就是说python内置了很多函数供我们使用,这些函数放在不同的模块里,我们使用的时候只需要导入就可以了。使用函数,首先理解函数本身的含义,和参数的意思,然后直接调用就可以了,不过调用的方法有两种,下面分别介绍

 通过模块调用

 在介绍数学模块的使用之前,我们简单介绍下import的导入,这就好比我们有很多工具箱,数学的,绘图的,网络的,我们import数学,就是把数学这个工具箱拿过来,然后用里面的工具,在用的是很好,我们要说明我们要用数学工具箱里面的某某函数,比如求绝对值,求平方等等。

 下面我们来看看数学工具箱都有什么

 import math # 导入math模块

 help(math) # help方法可以查看模块都有哪些方法,建议大家在命令行运行这个代码

 Help on built-in module math:

 NAME

 math

 DESCRIPTION

 This module is always available. It provides access to the

 mathematical functions defined by the C standard.

 FUNCTIONS

 acos(...)

 acos(x)

 Return the arc cosine (measured in radians) of x.

 help()可以帮助我们查看任意函数的用法,比如

 import math

 help(math.floor)

 Help on built-in function floor in module math:

 floor(...)

 floor(x)

 Return the floor of x as an Integral.

 This is the largest integer <= x.

 可以看到,通过help方法,我们看到了math模块的floor方法的详细使用说明。返回小于等于x参数的最大整数

 import math

 a = math.floor(2.3)

 b = math.floor(2.7)

 print(a, b)

 2 2

 可以看到2.3 2.7调用不小于floor的最大整数返回的都是2,这些math函数是通用的,在不同的语言中变量名基本上相同的

 import math

 print(dir(math)) # 我们可以通过dir方法查看任意模块所具有的的全部方法

 # 想要查看具体方法或者函数的使用只需要用help方法查看方法的文档就是了

 help(math.sin)

 ['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']

 Help on built-in function sin in module math:

 sin(...)

 sin(x)

 Return the sine of x (measured in radians).

 结合dir和help方法,我们可以方便的查看模块所具有的函数,和函数的使用方法,对于还是不理解的可以百度、谷歌一下,讲真,python中的函数千千万,很难说哪些更常用,可是你掌握了查看函数使用办法的方法,你就能够快速的找到函数的使用方法了。

 第二种使用math模块中函数的方法

 from math import *

 print(floor(2.7))

 print(pow(2, 3))

 2

 8.0

 可以看到我用from math import * 的方式导入了math中所有的函数,在使用floor函数的时候不再需要通过math来访问,这就好比,我们找了一个工具箱,并且把工具箱里的工具都倒在工具台上了,用的时候直接拿,而不需要考虑是在哪个箱子里,这样子固然方便,但是有的时候容易造成函数名重复,引发意想不到的效果。我们也可以精确的指定我们想要用的函数。

 from math import floor

 print(floor(2.7))

 2

 通过这种方法,我们明确的指定,我们要用的是math模块中的floor函数,而其他方法因为没有导入是不能够调用的。

 随机数的使用

 import random

 print(dir(random))

 ['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 'TWOPI', '_BuiltinMethodType', '_MethodType', '_Sequence', '_Set', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_acos', '_bisect', '_ceil', '_cos', '_e', '_exp', '_inst', '_itertools', '_log', '_pi', '_random', '_sha512', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 'choice', 'choices', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', 'getstate', 'lognormvariate', 'normalvariate', 'paretovariate', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform', 'vonmisesvariate', 'weibullvariate']

 可以看到我们导入了随机数模块random,并且打印了random中所有的函数,感兴趣的老师可以逐一用help方法查看这些方法的使用,我们这里介绍几个常见函数的使用。

 from random import *

 for x in range(10):

 print(random() * 10)

 5.851263602624135

 4.3548128855203805

 3.9194585868297738

 8.363122526904013

 0.4411989438772934

 3.7153545545043154

 5.204593592135844

 8.996636199418665

 1.7990990007428609

 3.29425328764919

 上述代码的用途是生成了10在1-10之间的随机数,random()函数的用途是生成0到1之间的随机数,我们乘以10就是生成0-10的随机数,如果想要生成20-30之间的随机数怎么办呢?

 random() * 10 + 20

 29.221714029521486

 choice函数

 choice函数的作用是从一堆列表中随机选择出一个,类似于洗牌,抽奖,随机点名,随机姓名等等。

 students = ['langxm', 'zhagnsan ', 'lisi', 'wangwu', 'zhouliu']

 choice(students) # 注意因为前面我已经from random import *了所以这里就不需要导入了

 for x in range(10):

 print(choice(students))

 langxm

 zhouliu

 langxm

 langxm

 lisi

 zhouliu

 zhagnsan

 lisi

 zhagnsan

 langxm

 可以看到,上面是我抽奖10次的结果,当然,如果要抽奖,大家需要了解python中list列表的操作,每次随机抽到一个学生之后,把学生从列表中删除,才能够保证抽奖的公平性,上课随机点名,也可以用这种算法的。

 关于list常用方法的使用,大家可以在学习list的时候使用,不外乎增删改查元素,访问元素等等,list实际上是一个数组

 print(dir(list))

 ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

 list所有的方法就在上面了,同时需要知道的无论是数组还是字符串在python访问长度的方法你都是len,跟list函数列表里的len魔术方法是存在一定的关联的,感兴趣的老师可以参考《流畅的python》一书。

 len(students)

 5

 len("hello world")

 11

 print(students)

 students.pop()

 print(students)

 ['langxm', 'zhagnsan ', 'lisi', 'wangwu', 'zhouliu']

 ['langxm', 'zhagnsan ', 'lisi', 'wangwu']

 students.reverse() # 翻转数组

 print(students)

 ['wangwu', 'lisi', 'zhagnsan ', 'langxm']

 students.append('lagnxm') # 在数组添加一个名字"lagnxm"

 print(students) # 打印当前的字符串数组

 print(len(students)) # 打印舒服的长度

 print(students.count("lagnxm")) # 查找 lagnxm 数量

 ['wangwu', 'lisi', 'zhagnsan ', 'langxm', 'lagnxm', 'lagnxm', 'lagnxm', 'lagnxm', 'lagnxm']

 9

 5

 字符串函数

 字符串的使用在python中相当频繁所以掌握字符串的使用对于python来说是相当重要的

 print(dir(str))

 ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

 可以看到str有非常多的方法,下面简单介绍结果例子

 demo = "Hello world, elangxm!"

 help(str.count)

 demo.count("el") # 计算字符串中出现的字符的数量,运行后出现了2次,

 demo.count("l")

 demo.title() # 调用title方法,字符串中,所以单词开头的字幕都大写

 Help on method_descriptor:

 count(...)

 S.count(sub[, start[, end]]) -> int

 Return the number of non-overlapping occurrences of substring sub in

 string S[start:end]. Optional arguments start and end are

 interpreted as in slice notation.

 'Hello World, Elangxm!'

 我们利用count函数统计了字符串demo中的l字母出现的次数,在函数中中括号意味着可选参数,所以除了要查找的字符串之外都是可选参数,查找范围是通过start和end指定的。

 print("abc".isdigit()) # 判断abc是否数字

 print("12".isdigit()) # 判断12是否数组整数

 # python没有内置判断是否是小数的方法

 False

 True

 range

 返回一个数组,多用在for循环,range([start],[stop],[step]) 返回一个可迭代对象,起始值为start,结束值为stop-1,start默认为0,step步进默认为1

 可以看到上面这个很奇怪,在很多种情况下,range()函数返回的对象的行为都很像一个列表,但是它确实不是一个列表,它只是在迭代的情况下返回指定索引的值,但是它并不会在内存中真正产生一个列表对象,这样也是为了节约内存空间。

 list(range(10))

 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

 list(range(10,20,3))

 [10, 13, 16, 19]

 list(range(20, 10, -3))

 [20, 17, 14, 11]

 for x in range(20, 10, -3):

 print(x)

 20

 17

 14

 11

 上面的代码演示了range的用法,并且把range函数返回的可迭代对象利用list函数转换为数组,然后展示了range在for中的运算

 内置函数

 上面列了常见的模块,然后是内置函数的使用,下面介绍常见的函数:

 abs函数

 返回绝对值

 abs(-2)

 2

 sum函数

 对给定的数字或者列表求和

 a = [1, 3, 5, 7, 8]

 sum(a)

 24

 sum(a, 3) # 在对列表a求和之后,再加3

 27

 sum(a, 6) # 列表求和之后,加6

 30

 max和min函数

 返回一系列数字的max和min的数值

 max(1, 2, 3, 4)

 4

 min(1, 2, 4, 5)

 1

 用python生成简单的web服务器

 在命令行输入

 python -m http.server

 [图片上传失败...(image-1bc76e-1519367750645)]

 python logo绘图

 import turtle

 print(dir(turtle))

 ['Canvas', 'Pen', 'RawPen', 'RawTurtle', 'Screen', 'ScrolledCanvas', 'Shape', 'TK', 'TNavigator', 'TPen', 'Tbuffer', 'Terminator', 'Turtle', 'TurtleGraphicsError', 'TurtleScreen', 'TurtleScreenBase', 'Vec2D', '_CFG', '_LANGUAGE', '_Root', '_Screen', '_TurtleImage', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__forwardmethods', '__func_body', '__loader__', '__methodDict', '__methods', '__name__', '__package__', '__spec__', '__stringBody', '_alias_list', '_make_global_funcs', '_screen_docrevise', '_tg_classes', '_tg_screen_functions', '_tg_turtle_functions', '_tg_utilities', '_turtle_docrevise', '_ver', 'addshape', 'back', 'backward', 'begin_fill', 'begin_poly', 'bgcolor', 'bgpic', 'bk', 'bye', 'circle', 'clear', 'clearscreen', 'clearstamp', 'clearstamps', 'clone', 'color', 'colormode', 'config_dict', 'deepcopy', 'degrees', 'delay', 'distance', 'done', 'dot', 'down', 'end_fill', 'end_poly', 'exitonclick', 'fd', 'fillcolor', 'filling', 'forward', 'get_poly', 'get_shapepoly', 'getcanvas', 'getmethparlist', 'getpen', 'getscreen', 'getshapes', 'getturtle', 'goto', 'heading', 'hideturtle', 'home', 'ht', 'inspect', 'isdown', 'isfile', 'isvisible', 'join', 'left', 'listen', 'lt', 'mainloop', 'math', 'mode', 'numinput', 'onclick', 'ondrag', 'onkey', 'onkeypress', 'onkeyrelease', 'onrelease', 'onscreenclick', 'ontimer', 'pd', 'pen', 'pencolor', 'pendown', 'pensize', 'penup', 'pos', 'position', 'pu', 'radians', 'read_docstrings', 'readconfig', 'register_shape', 'reset', 'resetscreen', 'resizemode', 'right', 'rt', 'screensize', 'seth', 'setheading', 'setpos', 'setposition', 'settiltangle', 'setundobuffer', 'setup', 'setworldcoordinates', 'setx', 'sety', 'shape', 'shapesize', 'shapetransform', 'shearfactor', 'showturtle', 'simpledialog', 'speed', 'split', 'st', 'stamp', 'sys', 'textinput', 'tg_screen_functions', 'tilt', 'tiltangle', 'time', 'title', 'towards', 'tracer', 'turtles', 'turtlesize', 'types', 'undo', 'undobufferentries', 'up', 'update', 'width', 'window_height', 'window_width', 'write', 'write_docstringdict', 'xcor', 'ycor']

 from turtle import *

 pensize()

 forward()

 backward()

 right()

 left()

 shape()

 shapesize()

 pencolor()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值