標籤:python 學習筆記
直接講多分支結構(Chained)吧,比較簡單,就概括一下:
比如
舉例1: 將考試分數轉換為等級
分數 >= 90
A
分數 >= 80
B
分數 >= 70
C
分數 >= 60
D
分數 < 60
E
Python語句實現:
score =98if score>=90: print 'A'elif score>=80: print 'B'elif score>=70: print 'C'elif score>=60: print 'D'else: print 'E'</span>
輸出 A
舉例2:求一元二次方程的解
python 代碼實現:
import matha=float(raw_input('input a: '))b=float(raw_input('input b: '))c=float(raw_input('input c: '))if a==0: print 'not quadratic'else: delta=b**2-4*a*c if delta <0: print 'no real root!' elif delta ==0: print 'only one root is',-b/(2*a) else: root =math.sqrt(delta) s1=(-b+root)/(2*a) s2=(-b-root)/(2*a) print 'two distinct solutions are: ',s1,s2運行結果如下:
舉例3:計算1+2+3+…+10的值
注意:range 函數產生 0, 1, …, 10 序列
代碼實現:
s = 0i=1for i in range(11): s += i print 'sum is ',s
輸出 55
舉例4:計算常數 e
思路:(1)調用函數,(2)自己寫函數
代碼實現
import mathe = 1for i in range(1,100): e += 1.0/math.factorial(i) print 'e is ',e
輸出:e is 2.71828182846
e = 1fib=1for i in range(1, 100): fib *= i e +=1.0/fibprint 'e is ', e
輸出:e is 2.71828182846
可以看出兩種方法結果是一樣的,不過注意第二種,for迴圈下面第二行或更多行,要和第一行保持左邊對齊,否則運行則單獨為一條語句
注意:
range(2, 10) = [2, 3, 4, 5, 6, 7, 8, 9]
range(2, 10, 3) = [2, 5, 8]
range(10, 2, -1) =[10, 9, 8, 7, 6, 5, 4, 3]
Python學習之五【程式控制結構-選擇結構&&迴圈結構】