讀古今文學網 > 父與子的編程之旅:與小卡特一起學Python > 第3章 >

第3章

測試題

1. Python 使用 *(星號)表示乘法。

2. Python 會得出結果 8/3=2。因為 8 和 3 都是整數,所以 Python 2 會把答案向下取整為最接近的整數。(注意,在 Python 3 中,你會得出結果 2.66666666667,因為 Python 3 不像 Python 2 那樣對整數默認做整除運算。)

3. 要得到餘數,可以使用取余操作符:8 % 3

4. 要得到 8/3 的小數結果,需要把其中一個數改為小數:8.0/38/3.0。(注意,在 Python 3 中,會自動得出小數結果。)

5. Python 中計算 6 * 6 * 6 * 6 的另一種做法是什麼? 6 ** 4

6. 17 000 000 採用 E 記法要寫作 1.7e7

7. 4.56e-5 就是 0.000 045 6

動手試一試

解決這些問題還有其他方法。你可能會提出不同的方法來做這些事情。

1.

(a) 計算每個人在餐廳要付多少錢:

>>> print 35.27 * 1.15 / 3>>> 13.5201666667  

把它四捨五入,每個人應當付 $13.52。

(b) 計算一個矩形的面積和周長:

length = 16.7width = 12.5Perimeter = 2 * length + 2 * widthArea = length * widthprint 'Length = ', length, ' Width = ', widthprint "Area = ", Areaprint "Perimeter = ", Perimeter  

下面是運行這個程序的示例輸出:

Length = 16.7 Width = 12.5Area = 208.75Perimeter = 58.4  

2. 下面是一個把華式度轉換為攝氏度的程序:

fahrenheit = 75celsius  = 5.0/9 * (fahrenheit - 32)print "Fahrenheit  = ", fahrenheit, "Celsius =", celsius  

3. 計算以某個速度行駛一定距離需要花多長時間:

distance = 200speed = 80.0time = distance / speedprint "time =", time  

(要記住,除法中至少有一個數是小數,除非答案會向下取整為一個整數)。