python入門9 條件語句
阿新 • • 發佈:2018-11-04
條件語句:
if 條件為真:
執行語句塊 (執行完結束不執行elif,else)
elif 條件為真:
執行語句塊 (執行完結束不執行else)
else:
執行語句塊
#coding:utf-8 #/usr/bin/python """ 2018-11-03 dinghanhua 分支結構 """ score = 85 '''if''' if score >= 60: print('已通過考試') #大於等於60分考試通過 '''if else''' if score >= 60: print('合格') else: print('不合格') '''if elif else''' if score >= 90: print('優秀') elif score >= 80: print('良好') elif score >= 60: print('及格') else: print('不合格')
'''判斷使用者輸入是否是偶數''' while True: num = input('請輸入整數:') if num.isdigit() or ( num.startswith('-') andnum[1:].isdigit() ): #正負整數判斷 if int(num)%2==0: print(num) break else: print('不是偶數,重新輸入') else: print('輸入不合法,請重新輸入') '''False 0 None () [] {} 都是False''' if not []: print('非空')
'''根據通話秒數計算話費, 3分鐘之內0.2元 之後每分鐘0.1元 不滿一分鐘按一分鐘計算''' def fee(sec): if sec <=180 and sec > 0: return 0.2 else: min = sec // 60 if sec % 60 == 0 else sec // 60 + 1 #總通話分鐘數,邊界值處理 return 0.2+0.1*(min-3) print('話費:%.2f'%fee(15)) print('話費:%.2f'%fee(60)) print('話費:%.2f'%fee(181)) print('話費:%.2f'%fee(500))
'''根據輸入的月份顯示天數''' month = input('輸入月份') if month in ['1','3','5','7','8','10','12']: print('%s月 31天'%month) elif month in ['4','6','9','11']: print('%s月 30天'%month) elif month == '2': print('%s月閏年29,非閏年28天'%month) else: print('輸入有誤')