<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                合規國際互聯網加速 OSASE為企業客戶提供高速穩定SD-WAN國際加速解決方案。 廣告
                # Python常用函數 python中函數以兩種形式呈現:一是可以自己定義的函數function,比如最常用的```print()```函數;另外一種是作為類的方法method調用,比如```turtle.shapesize()```。這兩種形式本質上是相同的,不過是叫法不同,背后的語法實現細節我們沒有必要深入研究。 無論是作為function還是method存在的函數,我們都是可以自定義的。首先我會給大家介紹常見函數的使用,最后以python中的turtle繪圖為例向大家講解python中函數的自定義及其蘊含的抽象思想,并且通過繪圖的例子來向大家展示利用函數逐步進行抽象的過程。 函數的存在,大大提高了編程的效率,與傳統的命令式編程相比,可以有效的降低代碼數量,通過合理的定義函數,合理的使用函數參數,可以讓程序更加簡潔。python中的函數定義比較簡單,但是函數參數的位置參數,關鍵字參數,默認參數、可變參數等理解起來比較困難。 下面介紹常用函數的使用 ## Print print函數可以說是python中常用的函數,然而正是因為print是最常用的函數,大家往往在使用print函數的時候,忽視了print函數的強大功能 ### 基礎用法 ```python print("Hello World!") # 這可能是print最簡單的用法了,學習任何一門語言我們習慣上都會說Hello World! ``` Hello World! 在上面的例子中,我們直接調用了print函數,這樣就可以在控制臺輸出內容,請注意,print是方法的名稱后面跟著括號;括號里是要打印的內容,這里打印的 是字符串。如果想要打印多個字符串可以用逗號分隔要打印的內容。 ```python print("Wanderfull", "qingdao", "IT Teacher") ``` Wanderfull qingdao IT Teacher 可以看到,我們用逗號分隔了要打印的字符串。print還可以直接輸出數字: ```python print("Hello world!", 123) ``` Hello world! 123 我們還可以在print中輸出變量值 ```python 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了嘛 ```python 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函數的作用是把字符串轉為數字 ```python type(1) # type函數的作用查看變量或者值的具體類型,我們可以看到1的類型是int ``` int ```python type('1') ``` str 可以看到type函數返回的類型是str也就是字符串類型,用途是什么呢?比如我們要做一個猜數字或者答題的程序,我們通過input函數獲取的用戶的輸入,其實是字符串類型,我們需要轉化為數字才能進行運算的 ```python 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函數得到的用戶輸入的類型是字符串類型,字符串相加跟數值相加運算是不同的,我們預期的結果是2 + 3 = 5 然而實際上程序的結果是23,很明顯程序出問題了,那么正確的做法是什么呢?正確的做法是轉換變量類型。 ```python 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轉換為了整數類型,保證了運算結果的準確性。但是大家要注意的是a和b的類型其實還是字符串 ```python 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的類型沒變為什么結果是正確的呢,因為我們是分別把a和b轉換成了整數,其實這時候int(a)和int(b)與a和b是不同的變量了,我們實際進行加法運算的并非a和b而是int(a)和int(b),因為在python中基礎的數值,字符串等都是不可變類型,我們不可以在變量本身做更改的。 #### 拓展 ```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的類型是<class 'int'> b的類型是<class 'int'> 5 a的類型是<class 'int'> b的類型是<class 'int'> > 仔細觀察上面的代碼與之前代碼的區別,體會那種寫法更方便,如果小數相加應該怎么辦呢?要用到float函數了。 ## 數學常用函數 上面介紹了最基本的常用函數,那么下面我們來介紹一下python中的數學常用函數。 python是一門膠水語言,有著豐富的第三方庫,而在python中,很多常用的功能都成為了python本身的標準模塊,也就是說python內置了很多函數供我們使用,這些函數放在不同的模塊里,我們使用的時候只需要導入就可以了。使用函數,首先理解函數本身的含義,和參數的意思,然后直接調用就可以了,不過調用的方法有兩種,下面分別介紹 ### 通過模塊調用 在介紹數學模塊的使用之前,我們簡單介紹下import的導入,這就好比我們有很多工具箱,數學的,繪圖的,網絡的,我們import數學,就是把數學這個工具箱拿過來,然后用里面的工具,在用的是很好,我們要說明我們要用數學工具箱里面的某某函數,比如求絕對值,求平方等等。 下面我們來看看數學工具箱都有什么 ```python 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. acosh(...) acosh(x) Return the inverse hyperbolic cosine of x. sqrt(...) sqrt(x) Return the square root of x. tan(...) tan(x) Return the tangent of x (measured in radians). tanh(...) tanh(x) Return the hyperbolic tangent of x. trunc(...) trunc(x:Real) -> Integral Truncates 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 (built-in) help()可以幫助我們查看任意函數的用法,比如 ```python 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參數的最大整數 ```python import math a = math.floor(2.3) b = math.floor(2.7) print(a, b) ``` 2 2 可以看到2.3 2.7調用不小于floor的最大整數返回的都是2,這些math函數是通用的,在不同的語言中變量名基本上相同的 ```python 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模塊中函數的方法 ```python from math import * print(floor(2.7)) print(pow(2, 3)) ``` 2 8.0 可以看到我用from math import * 的方式導入了math中所有的函數,在使用floor函數的時候不再需要通過math來訪問,這就好比,我們找了一個工具箱,并且把工具箱里的工具都倒在工具臺上了,用的時候直接拿,而不需要考慮是在哪個箱子里,這樣子固然方便,但是有的時候容易造成函數名重復,引發意想不到的效果。我們也可以精確的指定我們想要用的函數。 ```python from math import floor print(floor(2.7)) ``` 2 通過這種方法,我們明確的指定,我們要用的是math模塊中的floor函數,而其他方法因為沒有導入是不能夠調用的。 ## 隨機數的使用 ```python 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方法查看這些方法的使用,我們這里介紹幾個常見函數的使用。 ```python 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之間的隨機數怎么辦呢? ```python random() * 10 + 20 ``` 29.221714029521486 ### choice函數 choice函數的作用是從一堆列表中隨機選擇出一個,類似于洗牌,抽獎,隨機點名,隨機姓名等等。 ```python 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實際上是一個數組 ```python 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》一書。 ```python len(students) ``` 5 ```python len("hello world") ``` 11 ```python print(students) students.pop() print(students) ``` ['langxm', 'zhagnsan ', 'lisi', 'wangwu', 'zhouliu'] ['langxm', 'zhagnsan ', 'lisi', 'wangwu'] ```python students.reverse() # 翻轉數組 print(students) ``` ['wangwu', 'lisi', 'zhagnsan ', 'langxm'] ```python 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 https://www.cnblogs.com/diege/archive/2012/10/01/2709790.html 參考文檔 ## 字符串函數 字符串的使用在python中相當頻繁所以掌握字符串的使用對于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有非常多的方法,下面簡單介紹結果例子 ```python 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指定的。 ```python 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()函數返回的對象的行為都很像一個列表,但是它確實不是一個列表,它只是在迭代的情況下返回指定索引的值,但是它并不會在內存中真正產生一個列表對象,這樣也是為了節約內存空間。 ```python list(range(10)) ``` [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] ```python list(range(10,20,3)) ``` [10, 13, 16, 19] ```python list(range(20, 10, -3)) ``` [20, 17, 14, 11] ```python for x in range(20, 10, -3): print(x) ``` 20 17 14 11 上面的代碼演示了range的用法,并且把range函數返回的可迭代對象利用list函數轉換為數組,然后展示了range在for中的運算 ## 內置函數 上面列了常見的模塊,然后是內置函數的使用,下面介紹常見的函數: ### abs函數 返回絕對值 ```python abs(-2) ``` 2 ### sum函數 對給定的數字或者列表求和 ```python a = [1, 3, 5, 7, 8] sum(a) ``` 24 ```python sum(a, 3) # 在對列表a求和之后,再加3 ``` 27 ```python sum(a, 6) # 列表求和之后,加6 ``` 30 ### max和min函數 返回一系列數字的max和min的數值 ```python max(1, 2, 3, 4) ``` 4 ```python min(1, 2, 4, 5) ``` 1 ## 用python生成簡單的web服務器 在命令行輸入 ```python -m http.server``` ![image.png](attachment:image.png) ## python logo繪圖 ```python 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'] ```python from turtle import * pensize() forward() backward() right() left() shape() shapesize() pencolor() ``` https://www.jianshu.com/p/7118a1784f46 參考文獻
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看