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

來源:互聯網
上載者:User

標籤: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學習之五【程式控制結構-選擇結構&&迴圈結構】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.