運算符是一些符号,它告訴 Python 解釋器去做一些數學或邏輯操作。一些基本的數學操作符如下所示:
>>> a=8+9
>>> a
17
>>> b=1/3
>>> b
0.3333333333333333
>>> c=3*5
>>> c
15
>>> 4%3
1
下面是一個計算天數的腳本
#/usr/bin/env python3
#coding:utf8
days = int(input("please enter days:"))
mouth = days // 30
day0 = days %30
print "You enter %s days"%days
print("Total is {} mouths and {} days".format(mouth,day0))
root@zwjfdisk2016:~/file/1# python days.python
please enter days:1000
You enter 1000 days
Total 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 python3
days = int(input("Enter Days:"))
print("Total is {} mouths and {} days".format(*divmod(days,30)))
oot@zwjfdisk2016:~/file/1# python3 daysv2.py
Enter Days:100
Total 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 == 1
True
>>> 2 > 3
False
>>> 23 == 24
False
>>> 34 != 35
True
邏輯運算符
對于邏輯 與,或,非,我們使用 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 3
3
>>> 0 and 2
0
>>> False or 4 or 5
4
>>> 2 > 1 and not 3 > 5 or 4
True
>>> False and 3
False
>>> False and 4
False
簡寫運算符
>>> a = 3
>>> a += 20
>>> a
23
>>> a /= 1
>>> a
23.0
>>> a /= 2
>>> a
11.5