標籤:python
運算子是一些符號,它告訴 Python 解譯器去做一些數學或邏輯操作。一些基本的數學操作符如下所示:
>>> a=8+9>>> a17>>> b=1/3>>> b0.3333333333333333>>> c=3*5>>> c15>>> 4%31
下面是一個計算天數的指令碼
#/usr/bin/env python3#coding:utf8days = int(input("please enter days:"))mouth = days // 30day0 = days %30print "You enter %s days"%daysprint("Total is {} mouths and {} days".format(mouth,day0))
[email protected]:~/file/1# python days.pythonplease enter days:1000You enter 1000 daysTotal is 33 Mouths and 10 Days
也可以用divmod函數實現,divmod(num1, num2) 返回一個元組,這個元組包含兩個值,第一個是 num1 和 num2 相整除得到的值,第二個是 num1 和 num2 求餘得到的值,然後我們用 * 運算子拆封這個元組,得到這兩個值。
>>> import sys>>> c=divmod(100,30)>>> c(3, 10)
#!/usr/bin/env python3days = int(input("Enter Days:"))print("Total is {} mouths and {} days".format(*divmod(days,30)))[email protected]:~/file/1# python3 daysv2.py Enter Days:100Total is 3 mouths and 10 days
效果是一樣的
關係運算子
| Operator |
Meaning |
| < |
Is less than #小於 |
| <= |
Is less than or equal to #小於等於 |
| > |
Is greater than#大於 |
| >= |
Is greater than or equal to#大於等於 |
| == |
Is equal to #等於 |
| != |
Is not equal to#不等於 |
>>> 1 == 1True>>> 2 > 3False>>> 23 == 24False>>> 34 != 35True
邏輯運算子
對於邏輯 與,或,非,我們使用 and,or,not 這幾個關鍵字。
邏輯運算子 and 和 or 也稱作短路運算子:它們的參數從左向右解析,一旦結果可以確定就停止。例如,如果 A 和 C 為真而 B 為假,A and B and C 不會解析 C 。作用於一個普通的非邏輯值時,短路運算子的傳回值通常是能夠最先確定結果的那個運算元。
關係運算可以通過邏輯運算子 and 和 or 組合,比較的結果可以用 not 來取反意。邏輯運算子的優先順序又低於關係運算子,在它們之中,not 具有最高的優先順序,or 優先順序最低,所以 A and not B or C 等於 (A and (notB)) or C。當然,括弧也可以用於比較運算式。
>>> 4 and 33>>> 0 and 20>>> False or 4 or 54>>> 2 > 1 and not 3 > 5 or 4True>>> False and 3False>>> False and 4False
簡寫運算子
x op= expression 為簡寫運算的文法形式。其等價於 x = x op expression
>>> a = 3>>> a += 20>>> a23>>> a /= 1>>> a23.0>>> a /= 2>>> a11.5
本文出自 “有志者,事竟成” 部落格,請務必保留此出處http://wuxinglai.blog.51cto.com/9136815/1882009
循序漸進-python-03