python運算符和表達式


 

 
 

運算符和表達式

在 Python 中你會寫大量的表達式。表達式由運算符和操作數組成。像 2+3 就是一個表達式。

知識點

  • 關系/邏輯運算
  • 表達式
  • 類型轉換

實驗步驟

1. 運算符

運算符是一些符號,它告訴 Python 解釋器去做一些數學或邏輯操作。一些基本的數學操作符如下所示:

>>> 2 + 3 5 >>> 23.0 - 3 20.0 >>> 22 / 12 1.8333333333333333 

只要有任意一個操作數是浮點數,結果就會是浮點數。

進行除法運算時若是除不盡,結果將會是小數,這很自然,如果要進行整除,使用 // 運算符,它將返回商的整數部分。

% 是求余運算符:

>>> 14 % 3 2 

1.1. 整數運算示例

代碼如下:

#!/usr/bin/env python3 days = int(input("Enter days: ")) months = days // 30 days = days % 30 print("Months = {} Days = {}".format(months, days)) 

運行程序:

此處輸入圖片的描述

在開始獲得用戶輸入的天數,然后獲得月份數和天數,最后把這些數打印出來。你可以使用更容易的辦法。

#!/usr/bin/env python3 days = int(input("Enter days: ")) print("Months = {} Days = {}".format(*divmod(days, 30))) 

divmod(num1, num2) 返回一個元組,這個元組包含兩個值,第一個是 num1 和 num2 相整除得到的值,第二個是 num1 和 num2 求余得到的值,然后我們用* 運算符拆封這個元組,得到這兩個值。

2. 關系運算符

你可以使用下面的運算符實現關系運算。

關系運算符

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 < 2 True >>> 3 > 34 False >>> 23 == 45 False >>> 34 != 323 True 

3. 邏輯運算符

對於邏輯 與,或,非,我們使用 andornot 這幾個關鍵字。

邏輯運算符 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。當然,括號也可以用於比較表達式。

下面是一些例子:

>>> 5 and 4 4 >>> 0 and 4 0 >>> False or 3 or 0 3 >>> 2 > 1 and not 3 > 5 or 4 True 

4. 簡寫運算符

x op= expression 為簡寫運算的語法形式。其等價於 x = x op expression ,舉例如下:

>>> a = 12 >>> a += 13 >>> a 25 >>> a /= 3 >>> a 8.333333333333334 >>> a += (26 * 32) >>> a 840.3333333333334 

shorthand.py 示例:

#!/usr/bin/env python3 N = 100 a = 2 while a < N: print(str(a)) a *= a 

運行之:

$ ./shorthand.py
2
4
16

5. 表達式

通常我們書寫表達式的時候,會在每一個運算符左右都放一個空格,這樣使代碼更可讀,如:

a = 234 * (45 - 56 / 34) 

一個用於展示表達式的例子,注意其中運算符的優先級。

#!/usr/bin/env python3 a = 9 b = 12 c = 3 x = a - b / 3 + c * 2 - 1 y = a - b / (3 + c) * (2 - 1) z = a - (b / (3 + c) * 2) - 1 print("X = ", x) print("Y = ", y) print("Z = ", z) 

運行之:

$ ./evaluationexp.py
X =  10
Y =  7
Z =  4

第一個計算的是 x,步驟如下:

9 - 12 / 3 + 3 * 2 -1 9 - 4 + 3 * 2 - 1 9 - 4 + 6 - 1 5 + 6 - 1 11 - 1 10 

由於括號的存在,y 和 z 的計算方式不同,你可以自己去驗證它們。

6. 類型轉換

我們可以手動的執行類型轉換。

類型轉換函數 轉換路徑
float(string) 字符串 -> 浮點值
int(string) 字符串 -> 整數值
str(integer) 整數值 -> 字符串
str(float) 浮點值 -> 字符串
>>> a = 8.126768 >>> str(a) '8.126768' 

7. 程序示例

7.1. evaluateequ.py

這個程序計算數列 1/x+1/(x+1)+1/(x+2)+ ... +1/n,我們設 x = 1,n = 10。

#!/usr/bin/env python3 sum = 0 for i in range(1, 11): sum += 1 / i print("{:2d} {:6.4f}".format(i , sum)) 

運行程序:

此處輸入圖片的描述

7.2. quadraticequation.py

這個程序用來求解二次方程式:

#!/usr/bin/env python3 import math a = int(input("Enter value of a: ")) b = int(input("Enter value of b: ")) c = int(input("Enter value of c: ")) d = b * b - 4 * a * c if d < 0: print("ROOTS are imaginary") else: root1 = (-b + math.sqrt(d)) / (2 * a) root2 = (-b - math.sqrt(d)) / (2 * a) print("Root 1 = ", root1) print("Root 2 = ", root2) 

運行程序:

此處輸入圖片的描述

7.3. salesmansalary.py

這個程序計算以為數碼相機銷售人員的工資。他的基本工資是 1500,每售出一台相機他可以得到 200 並且獲得 2% 的抽成。程序要求輸入相機數量及月銷售總額。

#!/usr/bin/env python3 basic_salary = 1500 bonus_rate = 200 commision_rate = 0.02 numberofcamera = int(input("Enter the number of inputs sold: ")) price = float(input("Enter the total prices: ")) bonus = (bonus_rate * numberofcamera) commision = (commision_rate * numberofcamera * price) print("Bonus = {:6.2f}".format(bonus)) print("Commision = {:6.2f}".format(commision)) print("Gross salary = {:6.2f}".format(basic_salary + bonus + commision)) 

運行程序:

此處輸入圖片的描述

總結

除了數值運算,關系和邏輯運算也是程序的重要組成部分。另外 Python 是強類型語言,所以必要的時候需要手動進行類型轉換。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM