一. 布爾型別和比較運算子
- bool布爾型別
- True:真1;Flase:假0
- 變數名稱 = 布爾變數字面量 eg:bool_1 = True
- 比較運算子
- 通過<比較運算子>計算得到布爾型別的結果

二. if陳述句的基本格式
- if 陳述句格式:?
if 條件陳述句:
True,do sth
- 注意事項:
- 條件陳述句結果:布爾型別
- 條件陳述句 + :
- if代碼塊:4個空格縮進
- eg
age = input('請輸入年齡:')
if int(age) > 18:
print('adult:', age)
print('happy')

三. if else陳述句
- if else格式:
if 條件陳述句:
(True)do sth
else:
(False)do sth
2.注意事項:
- else:無條件陳述句,當if的條件不滿足時,else執行
- else代碼塊:4個空格縮進
- eg
age = input('請輸入年齡:')
if int(age) > 18:
print('adult:', age)
else:
print('child:',age)
print('happy')

四. if elif else陳述句
- if elif else陳述句的作用:
可以完成多個條件的判斷 - 注意事項:
- elif:可以寫多個
- 判斷是 互斥且有序,上一個滿足,后面的就不會判斷了
- 可以在條件陳述句中,直接寫input陳述句,節省代碼量
- eg
age = input('請輸入年齡:')
if int(age) < 18:
print('child free:',age)
elif int(age) > 70:
print('olds free:',age)
else:
vip = input('請輸入vip等級(0-1):')
if int(vip) >= 1:
print('adult vip free:', age, int(vip))
else:
print('adult:', age)
print('happy')
或者
if int(input('請輸入年齡:')) < 18:
print('child free')
elif int(input('請輸入年齡:')) > 70:
print('olds free')
elif int(input('請輸入vip等級(0-1):')) >= 1:
print('adult vip free')
else:
print('adult')
print('happy')

五. 條件陳述句的嵌套
- 用于多條件、多層次的邏輯判斷
- 根據需求,自由組合if elif else來構建多層次判斷
- 注意空格縮進,Python通過空格縮進來決定層次關系
六. 實戰案例
-
題目

-
答
import random
num = random.randint(1,10)
i = int(input('猜測1:'))
if i == num:
print('congratulate!')
else:
if i > num:
print('too large')
else:
print('too small')
j = int(input('猜測2:'))
if j == num:
print('congratulate!')
else:
if j > num:
print('too large')
else:
print('too small')
k = int(input('猜測3:'))
if k == num:
print('congratulate!')
else:
print('sorry!!!num =',num)

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/522879.html
標籤:Python
上一篇:淺談PHP設計模式的觀察者模式
