python基礎學習(四) 條件和分支

2021-07-31 18:26:01 字數 1605 閱讀 7761

1.成績分類三種方法的區別

根據成績,進行分類abcde

法1:score=int(input("請輸入分數:"));

if 100>= score>= 90:

print("a")

if 90>score>=80:

print("b")

if 80>score>=70:

print("c")

if 70>score>=60:

print("d")

if 60>score>=0:

print("e")

if score<0 or score>100:

print('d')

法二:score=int(input("請輸入分數:"));

if 100>= score>= 90:

print("a")

else:

if 90>score>=80:

print("b")

else:

if 80>score>=70:

print("c")

else:

if 70>score>=60:

print("d")

else:

if 60>score>=0:

print("e")

else:

print('輸入錯誤')

法三:score = int(input("請輸入分數:"));

if 100 >= score>= 90:

print("a")

elif 90 > score >= 80:

print("b")

elif 80 > score >= 70:

print("c")

elif 70 >score >= 60:

print("d")

elif 60 > score >= 0:

print("e")

else:

print('輸入錯誤')

2.三元操作符(和c語言對比)

i=a if a>b else b

>>> a=8

>>> b=9

>>> i=a if a>b else b

>>> i

93.斷言 關鍵字assert

當這個關鍵字後面的條件為假時,程式自動崩潰並丟擲assertionerror的異常。

一般可以用它在程式中置入檢查點,當需要確保程式某個條件一定為真時才能讓程式正常工作時,assert就顯得很重要了。

4.for迴圈(計數迴圈):for i(引數) in 引數:

range([start],stop,[step=1])和for迴圈配合使用

這個bif有三個引數,分別是起始,終止和步長,有括號的引數表示可以省略,

>>> range(5)

range(0, 5)

>>> list(range(5))

[0, 1, 2, 3, 4]

當只有乙個引數(如5)則預設起始為0,步長為1的五個數。

5.shell換行輸入

(1)在條件語句輸完後按tab建再enter換行

(2)或者直接加『\』後再enter換行。

6.break和continue

Python基礎(四) 條件語句

1.if語句if 條件 行 必須放到乙個語句塊中 語句塊就是組合在一起的一組程式語句 在python中,空白 tab或空格 是有意義的!處於同一位置 縮排相同 的 組成乙個 塊!如果你在python互動環境下敲 還要特別留意縮排,並且退出縮排需要多敲一行回車 用於條件的符號 定義符號 等於 不等於 ...

python基礎(四)條件判斷

1.輸入使用者年齡,根據年齡列印不同的內容 age 20 if age 18 print your age is age print adult 再新增乙個else語句 age 3 if age 18 print your age is age print adult else print your...

Python 四 條件判斷和迴圈

1 if 2 if else 3 if elif 4 if elif else 注意不要少寫了冒號 if判斷條件還可以簡寫,比如寫 if x print true 只要x是非零數值 非空字串 非空list等,就判斷為true,否則為false。因為input 返回的資料型別是str,str不能直接和...