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

版权声明: https://blog.csdn.net/qq_37791134/article/details/83177372

复习:

第一周:

第二周:

第三周:

 

 

 

 

今日学习内容:

 

要掌握:

  • 程序的分支结构

 

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

 

 

 

分支结构的总结:

实例5:身体质量指数BMI

合起来怎么写呢?

#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()
    password =input()
    if name == 'Kate' and password =='666666':
        print("ok")
        break
    else:
        count += 1
        if count == 3:
            print("3次用户名或者密码均有误!退出程序")

展开阅读全文

没有更多推荐了,返回首页