Python第四章(北理國家精品課 嵩天等)
阿新 • • 發佈:2019-03-23
pow(x weight 起點 比特 NPU port who bmi lse
一、程序的分支結構
二、身體質量指數BMI
#CalBIv1.py height,weight = eval((input("請輸入身高(米)和體重\(公斤)[逗號隔開]:"))) bmi = weight / pow(height,2) print("BMI數值為:{:.2f}".format(bmi)) who,nat = "","" if bmi<18.5: who,nat = "偏瘦", "偏瘦" elif 18.5<=bmi<25: who,nat = "正常","正常" elif 24<=bmi<=25: who,nat= "正常","偏胖" elif 25<=bmi<28: who,nat = "偏胖","偏胖" elif 28<=bmi<30: who,nat = "偏胖","肥胖" else: who,nat = "肥胖","肥胖" print("BMI指標為:國際‘{0}‘,國家‘{1}‘".format(who,nat))
三、程序的循環結構
遍歷循環
計數循環
for i in renge(N):
<語句塊>
for i in range(M,N,K):
M,起點,N,終點,K,步長for c in s:
s字符串,c,s中的每個字符
for c in "Python123":
print(c,end=",")
P,y,t,h,o,n,1,2,3,
for item in ls:
for item in [123,"PY",456]:
print(item,end=",")
123,PY,456,
for line in fi:
無限循環
while <條件>: <語句塊>
循環控制保留字
break,continue
循環的高級用法
四、random庫
使用隨機數的標準庫基本隨機數函數:seed(),random()
隨機數種子
import random
random
randint(a,b) 生成ab之間的整數
randrange(m,n,k)生成一個mn之間以k為步長的整數
getrandbits(k) 生成一個k比特長的隨機整數
uniform(a,b) ab之間的隨機小數
choice(seq) 從序列seq中隨機選擇一個元素
shuffle(seq) 將序列seq中元素隨機排列,返回打亂後的序列
五、圓周率的計算
#CalPiV2.py from random import random from time import perf_counter DARTS = 1000*1000*10 hits= 0.0 start = perf_counter() for i in range(1,DARTS+1): x,y = random(),random() dist = pow(x**2+y**2,0.5) if dist <= 1.0: hits = hits+1 pi = 4*(hits/DARTS) print("圓周率值是:{}".format(pi)) print("運行時間是:{:.5f}s".format(perf_counter()-start))
Python第四章(北理國家精品課 嵩天等)