python常用函數(shù)

Python常用函數(shù)

python中函數(shù)以兩種形式呈現(xiàn):一是可以自己定義的函數(shù)function,比如最常用的print()函數(shù);另外一種是作為類的方法method調(diào)用,比如turtle.shapesize()。這兩種形式本質(zhì)上是相同的,不過是叫法不同,背后的語法實現(xiàn)細節(jié)我們沒有必要深入研究。
無論是作為function還是method存在的函數(shù),我們都是可以自定義的。首先我會給大家介紹常見函數(shù)的使用,最后以python中的turtle繪圖為例向大家講解python中函數(shù)的自定義及其蘊含的抽象思想,并且通過繪圖的例子來向大家展示利用函數(shù)逐步進行抽象的過程。
函數(shù)的存在,大大提高了編程的效率,與傳統(tǒng)的命令式編程相比,可以有效的降低代碼數(shù)量,通過合理的定義函數(shù),合理的使用函數(shù)參數(shù),可以讓程序更加簡潔。python中的函數(shù)定義比較簡單,但是函數(shù)參數(shù)的位置參數(shù),關(guān)鍵字參數(shù),默認參數(shù)、可變參數(shù)等理解起來比較困難。
下面介紹常用函數(shù)的使用

Print

print函數(shù)可以說是python中常用的函數(shù),然而正是因為print是最常用的函數(shù),大家往往在使用print函數(shù)的時候,忽視了print函數(shù)的強大功能

基礎(chǔ)用法

print("Hello World!") # 這可能是print最簡單的用法了,學習任何一門語言我們習慣上都會說Hello World!
Hello World!

在上面的例子中,我們直接調(diào)用了print函數(shù),這樣就可以在控制臺輸出內(nèi)容,請注意,print是方法的名稱后面跟著括號;括號里是要打印的內(nèi)容,這里打印的 是字符串。如果想要打印多個字符串可以用逗號分隔要打印的內(nèi)容。

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

可以看到,我們用逗號分隔了要打印的字符串。print還可以直接輸出數(shù)字:

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函數(shù)的使用大大的簡化了格式化字符串的輸出,這就是最常用的用法了;其實print函數(shù)的強大遠不止如此
就像c語言中的printf函數(shù)一樣,print有強大的格式控制功能,感興趣的老師可以參考http://blog.csdn.net/wchoclate/article/details/42297173

str函數(shù)和int函數(shù)

str函數(shù)的作用是把數(shù)字等類型換換為字符串
int函數(shù)的作用是把字符串轉(zhuǎn)為數(shù)字

type(1) # type函數(shù)的作用查看變量或者值的具體類型,我們可以看到1的類型是int
int
type('1')
str

可以看到type函數(shù)返回的類型是str也就是字符串類型,用途是什么呢?比如我們要做一個猜數(shù)字或者答數(shù)學題的程序,我們通過input函數(shù)獲取的用戶的輸入,其實是字符串類型,我們需要轉(zhuǎn)化為數(shù)字才能進行運算的

a = input()
b = input()
print("a的類型是{}".format(type(a)))
print("b的類型是{}".format(type(b)))

print(a + b)
2
3
a的類型是<class 'str'>
b的類型是<class 'str'>
23

我們可以看到利用input函數(shù)得到的用戶輸入的類型是字符串類型,字符串相加跟數(shù)值相加運算是不同的,我們預期的結(jié)果是2 + 3 = 5 然而實際上程序的結(jié)果是23,很明顯程序出問題了,那么正確的做法是什么呢?正確的做法是轉(zhuǎn)換變量類型。

a = input()
b = input()
print("a的類型是{}".format(type(a)))
print("b的類型是{}".format(type(b)))

print(int(a) + int(b))
2
3
a的類型是<class 'str'>
b的類型是<class 'str'>
5

可以看到雖然輸入的仍然是str類型,但是我們在求和的時候把字符串類型的變量a和b轉(zhuǎn)換為了整數(shù)類型,保證了運算結(jié)果的準確性。但是大家要注意的是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的類型是<class 'str'>
b的類型是<class 'str'>
5
a的類型是<class 'str'>
b的類型是<class 'str'>

既然a和b的類型沒變?yōu)槭裁唇Y(jié)果是正確的呢,因為我們是分別把a和b轉(zhuǎn)換成了整數(shù),其實這時候int(a)和int(b)與a和b是不同的變量了,我們實際進行加法運算的并非a和b而是int(a)和int(b),因為在python中基礎(chǔ)的數(shù)值,字符串等都是不可變類型,我們不可以在變量本身做更改的。

拓展

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的類型是<class 'int'>
b的類型是<class 'int'>
5
a的類型是<class 'int'>
b的類型是<class 'int'>

仔細觀察上面的代碼與之前代碼的區(qū)別,體會那種寫法更方便,如果小數(shù)相加應該怎么辦呢?要用到float函數(shù)了。

數(shù)學常用函數(shù)

上面介紹了最基本的常用函數(shù),那么下面我們來介紹一下python中的數(shù)學常用函數(shù)。
python是一門膠水語言,有著豐富的第三方庫,而在python中,很多常用的功能都成為了python本身的標準模塊,也就是說python內(nèi)置了很多函數(shù)供我們使用,這些函數(shù)放在不同的模塊里,我們使用的時候只需要導入就可以了。使用函數(shù),首先理解函數(shù)本身的含義,和參數(shù)的意思,然后直接調(diào)用就可以了,不過調(diào)用的方法有兩種,下面分別介紹

通過模塊調(diào)用

在介紹數(shù)學模塊的使用之前,我們簡單介紹下import的導入,這就好比我們有很多工具箱,數(shù)學的,繪圖的,網(wǎng)絡(luò)的,我們import數(shù)學,就是把數(shù)學這個工具箱拿過來,然后用里面的工具,在用的是很好,我們要說明我們要用數(shù)學工具箱里面的某某函數(shù),比如求絕對值,求平方等等。
下面我們來看看數(shù)學工具箱都有什么

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()可以幫助我們查看任意函數(shù)的用法,比如

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參數(shù)的最大整數(shù)

import math
a = math.floor(2.3)
b = math.floor(2.7)
print(a, b)
2 2

可以看到2.3 2.7調(diào)用不小于floor的最大整數(shù)返回的都是2,這些math函數(shù)是通用的,在不同的語言中變量名基本上相同的

import math
print(dir(math)) # 我們可以通過dir方法查看任意模塊所具有的的全部方法
# 想要查看具體方法或者函數(shù)的使用只需要用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).

結(jié)合dir和help方法,我們可以方便的查看模塊所具有的函數(shù),和函數(shù)的使用方法,對于還是不理解的可以百度、谷歌一下,講真,python中的函數(shù)千千萬,很難說哪些更常用,可是你掌握了查看函數(shù)使用辦法的方法,你就能夠快速的找到函數(shù)的使用方法了。

第二種使用math模塊中函數(shù)的方法

from math import *
print(floor(2.7))
print(pow(2, 3))
2
8.0

可以看到我用from math import * 的方式導入了math中所有的函數(shù),在使用floor函數(shù)的時候不再需要通過math來訪問,這就好比,我們找了一個工具箱,并且把工具箱里的工具都倒在工具臺上了,用的時候直接拿,而不需要考慮是在哪個箱子里,這樣子固然方便,但是有的時候容易造成函數(shù)名重復,引發(fā)意想不到的效果。我們也可以精確的指定我們想要用的函數(shù)。

from math import floor
print(floor(2.7))
2

通過這種方法,我們明確的指定,我們要用的是math模塊中的floor函數(shù),而其他方法因為沒有導入是不能夠調(diào)用的。

隨機數(shù)的使用

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']

可以看到我們導入了隨機數(shù)模塊random,并且打印了random中所有的函數(shù),感興趣的老師可以逐一用help方法查看這些方法的使用,我們這里介紹幾個常見函數(shù)的使用。

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之間的隨機數(shù),random()函數(shù)的用途是生成0到1之間的隨機數(shù),我們乘以10就是生成0-10的隨機數(shù),如果想要生成20-30之間的隨機數(shù)怎么辦呢?

random() * 10 + 20
29.221714029521486

choice函數(shù)

choice函數(shù)的作用是從一堆列表中隨機選擇出一個,類似于洗牌,抽獎,隨機點名,隨機姓名等等。

students = ['langxm', 'zhagnsan ', 'lisi', 'wangwu', 'zhouliu']
choice(students) # 注意因為前面我已經(jīng)from random import *了所以這里就不需要導入了
for x in range(10):
    print(choice(students))
langxm
zhouliu
langxm
langxm
lisi
zhouliu
zhagnsan 
lisi
zhagnsan 
langxm

可以看到,上面是我抽獎10次的結(jié)果,當然,如果要抽獎,大家需要了解python中l(wèi)ist列表的操作,每次隨機抽到一個學生之后,把學生從列表中刪除,才能夠保證抽獎的公平性,上課隨機點名,也可以用這種算法的。

關(guān)于list常用方法的使用,大家可以在學習list的時候使用,不外乎增刪改查元素,訪問元素等等,list實際上是一個數(shù)組

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所有的方法就在上面了,同時需要知道的無論是數(shù)組還是字符串在python訪問長度的方法你都是len,跟list函數(shù)列表里的len魔術(shù)方法是存在一定的關(guān)聯(lián)的,感興趣的老師可以參考《流暢的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() # 翻轉(zhuǎn)數(shù)組
print(students)
['wangwu', 'lisi', 'zhagnsan ', 'langxm']
students.append('lagnxm') # 在數(shù)組添加一個名字"lagnxm"
print(students) # 打印當前的字符串數(shù)組
print(len(students)) # 打印舒服的長度
print(students.count("lagnxm")) # 查找 lagnxm 數(shù)量

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

https://www.cnblogs.com/diege/archive/2012/10/01/2709790.html 參考文檔

字符串函數(shù)

字符串的使用在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有非常多的方法,下面簡單介紹結(jié)果例子

demo = "Hello world, elangxm!"
help(str.count)
demo.count("el") # 計算字符串中出現(xiàn)的字符的數(shù)量,運行后出現(xiàn)了2次,
demo.count("l")
demo.title() # 調(diào)用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函數(shù)統(tǒng)計了字符串demo中的l字母出現(xiàn)的次數(shù),在函數(shù)中中括號意味著可選參數(shù),所以除了要查找的字符串之外都是可選參數(shù),查找范圍是通過start和end指定的。

print("abc".isdigit()) # 判斷abc是否數(shù)字
print("12".isdigit())  # 判斷12是否數(shù)組整數(shù)
# python沒有內(nèi)置判斷是否是小數(shù)的方法
False
True

range

返回一個數(shù)組,多用在for循環(huán),range([start],[stop],[step]) 返回一個可迭代對象,起始值為start,結(jié)束值為stop-1,start默認為0,step步進默認為1
可以看到上面這個很奇怪,在很多種情況下,range()函數(shù)返回的對象的行為都很像一個列表,但是它確實不是一個列表,它只是在迭代的情況下返回指定索引的值,但是它并不會在內(nèi)存中真正產(chǎn)生一個列表對象,這樣也是為了節(jié)約內(nèi)存空間。

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函數(shù)返回的可迭代對象利用list函數(shù)轉(zhuǎn)換為數(shù)組,然后展示了range在for中的運算

內(nèi)置函數(shù)

上面列了常見的模塊,然后是內(nèi)置函數(shù)的使用,下面介紹常見的函數(shù):

abs函數(shù)

返回絕對值

abs(-2)
2

sum函數(shù)

對給定的數(shù)字或者列表求和

a = [1, 3, 5, 7, 8]
sum(a)
24
sum(a, 3) # 在對列表a求和之后,再加3
27
sum(a, 6) # 列表求和之后,加6
30

max和min函數(shù)

返回一系列數(shù)字的max和min的數(shù)值

max(1, 2, 3, 4)
4
min(1, 2, 4, 5)
1

用python生成簡單的web服務(wù)器

在命令行輸入
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()

http://www.itdecent.cn/p/7118a1784f46 參考文獻

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容