關於python入門語法的一些總結(未完)
阿新 • • 發佈:2021-10-08
python程式設計快速上手--讓繁瑣工作自動化
-
常用資料結構
資料型別 例子 整型 0,1 浮點型 0.0,1.0 字串 'hello, world!','I am Li Hua' -
常用操作符
操作符 操作 例子 求值為 備註 ** 指數 2**3 8 % 取模/取餘數 22%8 6 // 整除/商數取整 22//8 2 / 除法 22/8 2.75 * 乘法 3*5 15 str * int(字串複製), str + str(字串連線) - 減法 5-2 3 + 加法 2+2 4 -
常用函式
- print(_string) 將引數字串_string顯示在螢幕上
- input() 將使用者輸入的任何字串返回
- len(_string) 返回引數字串_string的長度
- str() 將輸入轉化為字串string後返回
- int() 將輸入轉化為整型int後返回
- float() 將輸入轉化為浮點型float後返回
-
附錄
-
round()函式
-
round(number, digit),四捨五入函式
-
python2與python3的說明文件解釋不同:
在python2.7的doc中,round()的最後寫著,"Values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done away from 0." 保留值將保留到離上一位更近的一端(四捨六入),如果距離兩端一樣遠,則保留到離0遠的一邊。所以round(0.5)會近似到1,而round(-0.5)會近似到-1。
但是到了python3.5的doc中,文件變成了"values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done toward the even choice." 如果距離兩邊一樣遠,會保留到偶數的一邊。比如round(0.5)和round(-0.5)都會保留到0,而round(1.5)會保留到2。
-
規則(說法一)
- _digit≤4,捨去
- _digit=5,且舍入位後面無數,捨去
- _digit=5,且舍入位後面有數,進位
- _digit≥6,進位
-
規則(說法二)
round()對浮點數的取捨遵循的是“四捨六入五平分”,“五平分”就是根據取捨的位數前的小數奇偶性來判斷,奇偶平分,符合公平性原則(四捨五入不是公平的)。
- 當取捨位非5時,屬於正常情況,四捨五入
- 當取捨位是5,且取捨位前一位是奇數,舍
- 當取捨位是5,且取捨位前一位是偶數,入
-
實際檢驗,感覺就是簡單的四捨五入,不像上述規則說的那麼複雜?不過正如說明文件說的,慎用round()!
-
-
-
常用控制流語句
- 條件控制語句
- if語句
- else語句
- elif語句
- 迴圈控制語句
- while迴圈語句
- for迴圈語句
- range()函式,左閉右開 [start, end)
- range(start)
- range(start, end)
- range(start, end, step)
- 迴圈關鍵字
- break語句
- continue語句
- 模組匯入語句
- import _module(後續呼叫模組函式仍需要字首)
- from _module import *(後續呼叫模組函式不需要字首)
- 條件控制語句
-
關鍵詞引數
- print()
- end關鍵詞引數(字串結尾)
- sep關鍵詞引數(分隔字串)
- print()
-
異常處理
- try和except語句