编程语言
首页 > 编程语言> > Python第四章(北理国家精品课 嵩天等)

Python第四章(北理国家精品课 嵩天等)

作者:互联网

一、程序的分支结构

二、身体质量指数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))

 

标签:北理,seq,Python,random,精品课,item,循环,print,import
来源: https://www.cnblogs.com/kmxojer/p/10553557.html