Python筆記:條件語句

1、python流程控制,python代碼的執行順序分爲:順序、分支、循環 2、順序執行很簡單,就是從第一行一條一條執行,直到最後一行執行結束

分支,也叫條件語句,在不同的條件下,執行不同的代碼塊
常用的分支語句:if,if else ,if elif,if elif else
第一種:if
if 條件表達式:
條件表達式爲真時,執行此代碼塊

age = 15
if age<=28 and age>=14:
    print '團員'
else:
    print '年齡不合法'

第二種:if else if 條件表達式: 條件表達式爲真時,執行此代碼塊 else: 條件表達式爲假時,執行此代碼塊

age = 9
if age<=28 and age>=14:
    print '團員'
else:
    print '年齡不合法'
#密碼password爲123456,用戶輸入密碼如果與此密碼一致,則提示密碼輸入正確,否則提示密碼輸入錯誤
password = '123456'
pass_input = raw_input('請輸入密碼:')
if pass_input==password :
    print '密碼輸入正確'
else:
    print '密碼輸入錯誤'

elif即else-if語句
python中沒有switch語句,所以多個條件時,可以用elif來實現
第三種:if elif
if 條件表達式A:
條件表達式A爲真時,執行此代碼塊
elif 條件表達式B:
條件表達式B爲真時,執行此代碼塊

#舉例:成績小於60的輸出不及格,大於等於60小於80的輸出及格,
# 大於等於80小於90的輸出良好,大於等於90小於等於100的,輸出優秀
# 其他輸入,輸出 輸入成績不合法提示
score = -1
if score>=0 and score<60:
    print '成績不及格'
elif  score>=60 and score < 80:
    print '及格'
elif  score>=80 and score < 90:
    print '良好'
elif  score>=90 and score <= 100:
    print '優秀'

第四種:if elif else
if 條件表達式A:
條件表達式爲真時,執行此代碼塊
elif 條件表達式B:
條件表達式B爲真時,執行此代碼塊
else:
以上表達式都爲假時,執行此代碼塊

# 舉例:成績小於60的輸出不及格,大於等於60小於80的輸出及格,
# 大於等於80小於90的輸出良好,大於等於90小於等於100的,輸出優秀
# 其他輸入,輸出 輸入成績不合法提示
score = 95
if score>=0 and score<60:
    print '成績不及格'
elif  score>=60 and score < 80:
    print '及格'
elif  score>=80 and score < 90:
    print '良好'
elif  score>=90 and score <= 100:
    print '優秀'
else:
    print '輸入成績不合法'

# if-else語句的嵌套
if score>=0 and score<=100:
    if score < 60:
        print '成績不及格'
    elif score >= 60 and score < 80:
        print '及格'
    elif score >= 80 and score < 90:
        print '良好'
    elif score >= 90:
        print '優秀'
else:
    print '輸入成績不合法'

三元表達式,X if C else Y,C是條件表達式,X是條件表達式爲真的結果,Y是條件表達式爲假時的結果

x = 4
y = 3

if x<=y:
    smaller = x
else:
    smaller = y

# 有了三元表達式,可以寫成
smaller = x if x<=y else y
print smaller
# 練習題
# 1、用戶輸入一個數字,判斷這個數字是否能夠被3整除,
# 如果能夠被整除,則輸出,xx是3的倍數,否則輸出xx不是3的倍數
# 2、根據傳入的月份來輸出,這個月有幾天(默認2月有28天,不考慮閏年)

month = 5

if month in (1,3,5,7,8,10,12):
    print '%d 月有 31天'%(month)
elif month in [4,6,9,11]:
    print '%d 月有 30天' % (month)
elif month==2:
    print '%d 月有 28天' % (month)
else:
    print '輸入不合法'


#根據傳入的月份來輸出,這個月有幾天(默認2月有28天,不考慮閏年)
month = 5
if month == 2:
    print '%s 月有28天' % month
elif month in [1, 3, 5, 7, 8, 10, 12]:  # 成員運算符 in
    print '%d 月有31天' % month
elif month in [4, 6, 9, 11]:
    print '%d 月有30天' % month
else:
    print '輸入月份不合法'
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章