一. if語句和if esle語句
-
if語句
c = 20
if c>= 12:
print('c=',c) //c=20
-
if esle語句
使用格式
if 條件:
滿足條件執(zhí)行
else:
不滿足條件執(zhí)行
a = 10
if a <=20 :
print(a) //10
else:
print(a)
-
if elif else語句
使用格式
if xxx1:
事情1
elif xxx2:
事情2
elif xxx3:
事情3
demo1
d = 16
if d >= 17:
print('d=',d)
elif d < 19:
print('d=',d)
else:
print('d=',d) //d= 16
demo2
score = 80
if score>=90 and score<=100:
print('本次考試,等級為A')
elif score>=80 and score<90:
print('本次考試爬迟,等級為B')
elif score>=70 and score<80:
print('本次考試,等級為C')
elif score>=60 and score<70:
print('本次考試驹溃,等級為D')
elif score>=0 and score<60:
print('本次考試,等級為E')
輸出結(jié)果是:本次考試延曙,等級為B
二. input
input
讀取用戶的輸入豌鹤,這樣可以自己輸入,讓程序變得更有意思枝缔。一起來看下面一段程序
demo1
aa = input('aa:')
if aa < 200:
print("aa=",aa)
else:
print("aa=",aa)
demo2
age = input('請輸入你的年齡:')
aa = int(age)
if aa >= 18:
print("哥布疙,已成年,網(wǎng)吧可以去了")
else:
print("好好學(xué)習(xí)愿卸,天天向上")
** 有意思的來了**
這是因?yàn)閕nput()返回的數(shù)據(jù)類型是str灵临,str不能直接和整數(shù)比較,必須先把str轉(zhuǎn)換成整數(shù)趴荸。于是將類型轉(zhuǎn)換一下:
bb = input('aa:')
aa = int(bb)
if aa < 200:
print("aa=",aa)
else:
print("aa=",aa)
** 更有意思的來了**
如果輸入字符串呢儒溉?又會得到一個錯誤信息
原來int()函數(shù)發(fā)現(xiàn)一個字符串并不是合法的數(shù)字時(shí)就會報(bào)錯,程序就退出了发钝。
如何檢查并捕獲程序運(yùn)行期的錯誤呢顿涣?
么慌么燥讓我們一步一步來
總結(jié)
- 1.注意不要少學(xué)了冒號,冒號之前可以有空格
- 2.
elif
是else if
的縮寫酝豪,一條語句可以有多個elif
涛碑,格式如下
if <條件判斷1>:
<執(zhí)行1>
elif <條件判斷2>:
<執(zhí)行2>
elif <條件判斷3>:
<執(zhí)行3>
else:
<執(zhí)行4>
- 3.
if
語句的執(zhí)行順序是從上往下的,和其他語言相似寓调,如果在某個判斷上的Ture
,把該判斷對應(yīng)的語句執(zhí)行后锌唾,就忽悠掉剩下的elif
和esle