一. 課上代碼
>>> 3 ** 2
9
>>> 3 ** 5
243
>>> 3 ** -2
0.1111111111111111
>>> not True
False
>>> not False
True
>>> not 0
True
>>> not 4
False
>>> 3 < 4 < 5
True
#優先級問題
冪運算(**)
正負號(+, -)
算數操作符(*, /, //, +, -)
比較操作符(<, <=, >, >=, ==, !=)
邏輯運算符(not, and, or)
二. 測試題
- 說出答案:not 1 or 0 and 1 or 3 and 4 or 5 and 6 or 7 and 8 and 9
#not or and的優先級是不同的:not > and > or
那么給題干加括號:
(not 1) or (0 and 1) or (3 and 4) or (5 and 6) or (7 and 8 and 9)
== 0 or 0 or 4 or 6 or 9
== 4
三. 動動手
- 請寫一個程序打印出0~100所有的奇數
#個人代碼
for i in range(0, 101):
if i % 2 == 1:
print(i)
#參考代碼
i = 0
while i <= 100:
if i % 2 != 0:
print(i, end = ' ')
i += 1
else:
i += 1
- 寫一個程序讓計算機崩潰
#個人代碼
while 1:
print("I love you.")
#參考代碼
print(2 ** 2 ** 32)
#那為何print((2 ** 2) ** 32)就可以計算出結果呢?
- 愛因斯坦出過一道數學題,有一個長梯子,若每步上2階,最后剩1階;若每步上3階,最后剩2階;若每步上5階,最后剩4階;若每步上6階,最后剩5階;只有每步上7階,最后剛好一階也不剩。求解該階梯至少有多少階?
#個人代碼
for i in range(1, 100):
k = 7 * i
if k % 2 == 1 and k % 3 == 2 and k % 5 == 4 and k % 6 == 5
print(k, end = '')
#此代碼不能求出最小值,只能求得范圍之內的所有值,有待改進
#參考代碼
x = 7
i = 1
flag = 0
while i <= 100:
if x % 2 == 1 and x % 3 == 2 and x % 5 == 4 and x % 6 == 5:
flag = 1
else:
x = 7 * (i + 1)
i += 1
if flag == 1:
print(x)
else:
print("There is no answer in this range.")