python之分支結構
if語句的使用
在Python中,要構造分支結構可以使用if、elif和else關鍵字。所謂關鍵字就是有特殊含義的單詞,像if和else就是專門用於構造分支結構的關鍵字,很顯然你不能夠使用它作為變數名(事實上,用作其他的識別符號也是不可以)。下面模擬個認證的例子來說明一下,
username=str(raw_input("請輸入使用者名稱:")) password=str(raw_input("請輸入密碼:")) if username == "admin" and password=="12345" : print ("身份認證成功") else: print ("身份認證失敗")
以上的程式碼還是存在不嚴謹的,我們還需要通過判斷使用者輸入的是否為空值。這裡需要用到if的巢狀。修改後的程式碼如下:
username=str(raw_input("請輸入使用者名稱:")) password=str(raw_input("請輸入密碼:")) if username !='' and password !='': if username == "admin" and password=="12345" : print ("身份認證成功") else: print ("身份認證失敗") else: print("請輸入使用者名稱和密碼")
鞏固練習
練習1:英制單位與公制單位互換
#1英寸=25.4毫米 value=float(raw_input('請輸入長度:')) unit=str(raw_input('請輸入單位:')) if unit == 'in' or unit == '英寸': print('%f英寸=%f釐米' %(value,value*2.54)) elif unit =='cm' or unit =='釐米': print('%f英寸=%f釐米' % (value, value / 2.54)) else: print('請輸入有效的單位')
練習2:與電腦玩剪刀石頭布遊戲
import random payer=int(raw_input('請輸入你的指令(0:石頭,1:剪刀,2:布):')) comptuer=random.randint(0,2) if (payer == 1 and comptuer == 2 ) or (payer == 0 and comptuer == 1 ) or (payer== 2 and comptuer==0): print('電腦出:{},你出{},你贏了'.format(comptuer,payer)) elif (payer== comptuer): print('電腦出:{},你出{},打平'.format(comptuer, payer)) else: print('電腦出:{},你出{},你輸了'.format(comptuer, payer))
針對以上的小遊戲,我們有這樣一個需求,三盤兩勝方可算贏。那麼程式又如何修改呢。參考如下:
import random comptuer_win=0 payer_win=0 while True : payer=int(raw_input('請輸入你的指令(0:石頭,1:剪刀,2:布):')) comptuer=random.randint(0,2) if (payer == 1 and comptuer == 2 ) or (payer == 0 and comptuer == 1 ) or (payer== 2 and comptuer==0): print('電腦出:{},你出{},你贏了'.format(comptuer,payer)) payer_win+=1 print(payer_win) elif (payer== comptuer): print('電腦出:{},你出{},打平'.format(comptuer, payer)) else: print('電腦出:{},你出{},你輸了'.format(comptuer, payer)) comptuer_win += 1 if comptuer_win == 2 : print('電腦最終勝出') break elif payer_win == 2 : print('電腦最終勝出') break
練習3:輸入三條邊長如果能構成三角形就計算周長和麵積
import math a=int(raw_input("請輸入三角形的第一條邊長:")) b=int(raw_input("請輸入三角形的第二條邊長:")) c=int(raw_input("請輸入三角形的第二條邊長:")) if a+b > c and a+c>b and b+c >a : print("三角形的周長:{}".format(a+b+c)) #三角形面積,已知三邊利用海倫公式(p=(a+b+c)/2) #S=sqrt[p(p-a)(p-b)(p-c)] p=(a+b+c)/2 area=math.sqrt(p*(p-a)*(p-b)*(p-c)) print("三角形的面積:{}".format(area)) else: print("輸入的邊長不能構成三角形,請重新輸入")
練習4:實現一個個人所得稅計算器。
salary=float(input('本月收入:')) insurance=float(input('五險一金扣除:')) diff=salary-insurance-5000 if diff <= 0: rate = 0 deduction = 0 elif diff < 3000 : rate=0.3 deduction = 0 elif diff < 12000 : rate =0.1 deduction= 210 elif diff < 25000: rate = 0.2 deduction=1410 elif diff < 35000 : rate = 0.25 deduction = 2660 elif diff < 55000: rate =0.3 deduction = 4410 elif diff < 80000 : rate = 0.35 deduction = 7160 else: rate = 0.45 deduction=15160 tax=abs(diff*rate - deduction) print('個人所得稅: ¥%.2f元' % tax) print('實際到手收入:¥%.2f元' % (diff + 5000 - tax))