天天看點

Python學習之五【程式控制結構-選擇結構&&循環結構】

直接講多分支結構(Chained)吧,比較簡單,就概括一下:

比如

舉例1: 将考試分數轉換為等級

分數 >= 90

A

分數 >= 80

B

分數 >= 70

C

分數 >= 60

D

分數 < 60

E

Python語句實作:

score =98
if 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 math
a=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      

運作結果如下:

Python學習之五【程式控制結構-選擇結構&amp;&amp;循環結構】

舉例3:計算1+2+3+…+10的值

注意:range 函數生成 0, 1, …, 10 序列

代碼實作:

s = 0
i=1
for i in range(11):
    s += i      
print 'sum is ',s      

輸出 55

舉例4:計算常數 e

思路:(1)調用函數,(2)自己寫函數

代碼實作

import math
e = 1
for i in range(1,100):
   e += 1.0/math.factorial(i) 
print 'e is ',e      

輸出:e is  2.71828182846

e = 1
fib=1
for i in range(1, 100):
    fib *= i
    e +=1.0/fib
print '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]