3 . 注釋 comments在python中以‘#’字符hash character開頭,一直到這一行的結束。注釋可以出現在一行的開始,或者在代碼的后邊空閑部分。但是不能出現在一個字面字符串string中。在字符串中,‘#’僅僅是一個‘#’字符。
# this is the first commentspam = 1 # and this is the second comment# ... and now a third!text = "# This is not a comment because it's inside quotes."
3.1. python用作計算器
3.1.1. 數字
  翻譯器就像一個簡單的計算器,你可以計算任何表達式,運算符就象其他語言中一樣,‘+’‘-’‘*’‘/’ 。括號可以分組。
>>> 2 + 24>>> 50 - 5*620>>> (50 - 5.0*6) / 45.0>>> 8 / 5.01.6
除法‘/’運算的返回類型取決于它的操作數的類型。如果兩個操作數都是int型的,floor division就會執行然后返回一個int型。
< floor division就是數學除法然后取小于此數的最接近的整數。floordivision的操作符是‘//’,例子,11 // 4 得到2而不是2.75,注意(-11) // 4得到-3因為小于-2.75的整數是-3。>
如果除法中有一個操作數為 float型,classic division就會執行然后返回一個float型。
‘ // ’不管操作數是什么,都是做floor division計算。
余數可以由‘ % ’計算出來 。
>>> 17 / 3 # int / int -> int5>>> 17 / 3.0 # int / float -> float5.666666666666667>>> 17 // 3.0 # explicit floor division discards the fractional part5.0>>> 17 % 3 # the % Operator returns the remainder of the division2>>> 5 * 3 + 2 # result * divisor + remainder17
在python中可以由‘ ** ’來計算冪函數。
>>> 5 ** 2 # 5 squared25>>> 2 ** 7 # 2 to the power of 7128
在python的交互模式中,最后一個打印的表達式賦值給變量‘ _ ’這就意味著在使用python作為計算器時,可以輕松的繼續下一步計算。當然這個變量‘ - ’只能作為只讀使用,不要給他明確的賦值,否則你會創建一個同名的獨立本地變量掩蓋住這個內建的具有特殊功能變量。
1 >>> tax = 12.5 / 1002 >>> PRice = 100.503 >>> price * tax4 12.56255 >>> price + _6 113.06257 >>> round(_, 2)8 113.06
新聞熱點
疑難解答