算術操做符ide
+ spa
-內存
*input
/it
%io
**class
//循環
>>> a = 5程序
>>> a = a + 3方法
>>> a =+ 3
>>> b=3
>>> b -= 1
>>> b
2
>>> a
3
>>> a = b = c = d = 10
>>> a += 1
>>> b -= 3
>>> c *= 10
>>> d /= 8
>>> a
11
>>> b
7
>>> c
100
>>> d
1.25
>>>
>>> 10 // 8
1
>>> 3.0 // 2
1.0
>>>
>>> 5 % 2
1
>>> 11 % 2
1
>>> 2 ** 3
8
>>> 3 ** 2
9
>>>
優先級問題
>>> -3 * 2 + 5 / -2 - 4
-12.5
>>> (3 < 4) and (4 < 5)
True
>>> -3 ** 2
-9
>>> -(3 ** 2)
-9
>>> 3 ** -2
0.1111111111111111
>>> 3 ** (-2)
0.1111111111111111
>>>
比較操做符
<
<=
>
>=
==
!=
邏輯操做符
and
or
not
True \ False
>>> not True
False
>>> not False
True
>>> not 0
True
>>> not 4
False
>>> 3 < 4 < 5
True
>>>
又是優先級問題
冪運算 **
正負號 +x -x
算術操做符 * / // + -
比較操做符 < <= > >= == !=
邏輯運算符 not and or
了不得的分支和循環
加載背景音樂
播放背景音樂(設置單曲循環)
我方飛機誕生
interval = 0
while True:
if 用戶是否點擊了關閉按鈕:
退出程序
interval += 1
if interval == 50:
interval = 0
小飛機誕生
小飛機移動一個位置
屏幕刷新
if 用戶鼠標產生移動:
我方飛機中心位置 = 用戶鼠標位置
屏幕刷新
if 我方飛機與小飛機發生肢體衝突:
我方掛,播放撞機音樂
修改我方飛機圖案
打印「Game over」
中止背景音樂,最好淡出
了不得的分支和循環2
按照100分制,90分以上成績爲A,80到90爲B,60到80爲C,60如下爲D,寫一個程序,當用戶輸入分數,自動轉換爲ABCD的形式打印。
解題方案:
method1.py
method2.py
method3.py
method1.py:
score = int(input('請輸入一個分數:'))
if 100 >= score >= 90:
print('A')
if 90 > score >= 80:
print('B')
if 80 > score >= 60:
print('C')
if 60 > score >= 0:
print('D')
if score < 0 or score > 100:
print('輸入錯誤!')
method2.py:
score = int(input('請輸入您的分數:'))
if 100 >= score >= 90:
print('A')
else:
if 90 > score >= 80:
print('B')
else:
if 80 > score >= 60:
print('C')
else:
if 60 > score >= 0:
print('D')
else:
print('輸入錯誤!')
method3.py:
score = int(input('請輸入一個分數:'))
if 100 >= score >= 90:
print('A')
elif 90 > score >= 80:
print('B')
elif 80 > score >= 60:
print('C')
elif 60 > score >= 0:
print('D')
else:
print('輸入錯誤!')
那一種方法好:第一個都會執行(佔內存),第二個和第三個都只執行相應。
Python能夠有效避免「懸掛else」
什麼叫「懸掛else」?
咱們舉個例子,初學C語言的朋友可能很容易被如下代碼欺騙:
if ( hi > 2 )
if( hi > 7 )
printf(「好棒!好棒!」);
else
printf(「切~」);
條件表達式(三元操做符)
有了這個三元操做符的條件表達式,你能夠使用一條語句來完成如下的條件判斷和賦值操做:
x, y = 4, 5
if x < y:
small = x
else:
small = y
例子能夠改進爲:
small = x if x < y else y
斷言(assert)
assert這個關鍵字咱們稱之爲「斷言」,當這個關鍵字後邊的條件爲假的時候,程序自動崩潰並拋出AssertionError的異常。
舉個例子:
>>> assert 3 > 4
通常來講咱們能夠用Ta再程序中置入檢查點,當須要確保程序中的某個條件必定爲真才能讓程序正常工做的話,assert關鍵字就很是有用了。