1. 程式人生 > >運算符、流程控制

運算符、流程控制

put 分享 als 9.png 算數 種類 分鐘 item 建議

一、運算符

運算按種類可分為算數運算、比較運算、邏輯運算、賦值運算、成員運算、身份運算、位運算。

算數運算

以下假設變量:a=10,b=2

技術分享圖片

比較運算

以下假設變量:a=10,b=20

技術分享圖片

賦值運算

以下假設變量:a=10,b=20(其中=,+=,-=用得比較多)

技術分享圖片

邏輯運算

技術分享圖片

重點:

首先,‘and’、‘or’和‘not’的優先級是not>and>or。

and :x and y 返回的結果是決定表達式結果的值。如果 x 為真,則 y 決定結果,返回 y ;如果 x 為假,x 決定了結果為假,返回 x。

or :x or y 跟 and 一樣都是返回決定表達式結果的值。

not : 返回表達式結果的“相反的值”。如果表達式結果為真,則返回false;如果表達式結果為假,則返回true。

>>> 4 and 3
3
>>> 3 and 4
4
>>> 4 or 3
4
>>> 3 or 4
3
>>> True or False and False
True
>>> (True or False) and False
False

二、流程控制

if...else 語句

if 條件:
    滿足條件執行代碼
else:
    if條件不滿足就走這段

AgeOfOldboy = 48

if AgeOfOldboy > 50 :
    print("Too old, time to retire..
") else: print("還能折騰幾年!")

多分支

age_of_oldboy = 48

guess = int(input(">>:"))

if guess > age_of_oldboy :
    print("猜的太大了,往小裏試試...")

elif guess < age_of_oldboy :
    print("猜的太小了,往大裏試試...")

else:
    print("恭喜你,猜對了...")

重點:

Python的縮進有以下幾個原則:

1、頂級代碼必須頂行寫,即如果一行代碼本身不依賴於任何條件,那它必須不能進行任何縮進

2、同一級別的代碼,縮進必須一致

3、官方建議縮進用4個空格

While 循環

count = 0 
while count <= 100 : #只要count<=100就不斷執行下面的代碼
   print("loop ", count )
   count +=1  #每執行一次,就把count+1,要不然就變成死循環,因為count一直是0

結果:

loop  0
loop  1
loop  2
loop  3
....
loop  98
loop  99
loop  100

註意:避免出現死循環,while 是只要後邊條件成立(也就是條件結果為真)就一直執行。

循環中止語句(continue , break)

break用於完全結束一個循環,跳出循環體執行循環後面的語句

count = 0
while count <= 100 : #只要count<=100就不斷執行下面的代碼
    print("loop ", count)
    if count == 5:
        break
    count +=1 #每執行一次,就把count+1,要不然就變成死循環,因為count一直是0

print("-----out of while loop ------")
輸出
loop  0
loop  1
loop  2
loop  3
loop  4
loop  5
-----out of while loop ------

continue和break有點類似,區別在於continue只是終止本次循環,接著還執行後面的循環,break則完全終止循環

count = 0
while count <= 100 : 
    count += 1
    if count > 5 and count < 95: #只要count在6-94之間,就不走下面的print語句,直接進入下一次loop
        continue 
    print("loop ", count)
print("-----out of while loop ------")
輸出
loop  1
loop  2
loop  3
loop  4
loop  5
loop  95
loop  96
loop  97
loop  98
loop  99
loop  100
loop  101
-----out of while loop ------

while ... else ..

當while 循環正常執行完,中間沒有被break 中止的話,就會執行else後面的語句

count = 0
while count <= 5 :
    count += 1
    print("Loop",count)

else:
    print("循環正常執行完")
print("-----out of while loop ------")
輸出
Loop 1
Loop 2
Loop 3
Loop 4
Loop 5
Loop 6
循環正常執行完
-----out of while loop ------

如果執行過程中被break啦,就不會執行else的語句。

for循環

 for循環主要用於循環取值
student=[egon,虎老師,lxxdsb,alexdsb,wupeiqisb]

i=0
while i < len(student):
     print(student[i])
     i+=1

for item in student:
    print(item)

for item in hello:
    print(item)

dic={x:444,y:333,z:555}
for k in dic: 
    print(k,dic[k])


for i in range(1,10,3):
    print(i)

for i in range(10):
    print(i)

student=[egon,虎老師,lxxdsb,alexdsb,wupeiqisb]
for item in student:
    print(item)

for i in range(len(student)):
    print(i,student[i])

運算符、流程控制