Python语言程序设计（MOOC崇天）第四章程序的控制结构学习笔记（身体质量指数BMI+圆周率的计算）

• 程序的分支结构

#多分支结构
score = eval(input())
if 60 <= score <= 70:
elif  70 <= score <= 80:
elif  80<= score <= 90:
elif  score >90:
print("输入成绩属于级别:{}".format(grade))

#calBMIv3
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 < 24:
who, nat = "正常", "正常"
elif 24 <= bmi < 25:
who, nat = "正常", "偏胖"
elif 25 <= bmi < 28:
who, nat = "偏胖", "偏胖"
elif 28 <= bmi < 30:
who, nat = "偏胖", "肥胖"

print("身体质量指数BMI：国际'{}',国内'{}'".format(who, nat))

• 循环结构单元

•  无限循环：

• 循环控制保留字

break只跳出一层循环，多层时外层依旧有效。

• 循环的扩展

• random库概述

• 圆周率的计算

#counter π
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))

pi = 0
N = 100
for k in range(N):
pi += 1/pow(16, k)*( \
4/(8*k+1) - 2/(8*k+4) - \
1/(8*k+5) -1/(8*k+6))
print("圆周率值是:{}".format(pi))


按照公式算还是精确点的，但是门特卡罗就比较....

•  举一反三

output = []
for i in range(100,1000):
s = 0
for digit in str(i):
s += pow(int(digit), 3)
if s == i:
output.append(str(i))
# for i in range(len(output)):
#     if i == len(output)-1:
#         print(output[i])
#     else:
#         print(output[i], end=',')
str = ",".join(output)
print(str)

count = 0
while count< 3:
name =  input()
print("3次用户名或者密码均有误！退出程序")