==========CH07-08 homework==========
0 if not (money < 100): 上邊這行代碼相當於?
Answer: 如果 money >= 100 執行…..
1 assert 的作用?
Answer: 斷言,如果關鍵字後的‘條件’爲假的時候,程序會崩潰,並告訴你 AssertionError。
做模塊測試比較有用。
2 假設有 x = 1,y = 2,z = 3,請問如何快速將三個變量的值互相交換?
Analysis: x-y, y-z, z-x. array? or other idea?
Answer: [x, y, z] = [y, z, x] or x, y, z = y, z, x
3 猜猜 (x < y and [x] or [y])[0] 實現什麼樣的功能?
Answer: 先化簡( ((x < y) and [x]) or [y] )[0]
其意思是:如果 x < y成立,則輸出 也就是x, 如果x>=y則輸出變成 也就是y
有點類似於C語言的三元運算符:表達式1?表達式2:表達式3
如果表達式1成立則輸出表達式2,反之輸出表達式3
我查了下Python的3元表達式:
a if a < b else b, 如果a<b,則輸出a,反之輸出b
4 你聽說過成員資格運算符嗎?
Answer: ‘in’ 用來檢查某一個值是否在list中,在則返回True,不在返回False
>>>a = [1, 2, 3, 4]
>>>b = 3
>>>b in a
False
Practice
0 視頻中小甲魚使用 if elif else 在大多數情況下效率要比全部使用 if 要高,
但根據一般的統計規律,一個班的成績一般服從正態分佈,也就是說平均成績一般集中在 70~80 >分之間,
因此根據統計規律,我們還可以改進下程序以提高效率。
idea: 先判斷是否在70~80
code:
score = int( input('請輸入分數:') )
if 80 >= score >= 70:
print('This score rank \'C\'')
elif 70 >= score >= 60:
print('This score rank \'D\'')
elif 90 >= score >= 80:
print('This score rank \'B\'')
elif 100 >= score >= 90:
print('This score rank \'A\'')
elif 60 > score >=0:
print('Unqualified')
else:
print('Sorry! the score', score, 'not in the range[0 100]!')
1 Python 的作者在很長一段時間不肯加入三元操作符就是怕跟C語言一樣搞出國際亂碼大賽,
蛋疼的複雜度讓初學者望而生畏,不過,如果你一旦搞清楚了三元操作符的使用技巧,
或許一些比較複雜的問題反而迎刃而解。
請將以下代碼修改爲三元操作符實現:
1. x, y, z = 6, 5, 4
2. if x < y:
3. small = x
4. if z < small:
5. small = z
6. elif y < z:
7. small = y
8. else:
9. small = z
code:
x, y, z = 6, 5, 4
small =x if (x < y and x < z) else (y if y < z else z)