程序的分支结构:
- 单分支结构:
guess = eval(input( ))
if guess==99:
print("猜对")
- 二分支结构:
guess = eval(input( ))
if guess==99:
print("猜对了")
else:
print("猜错了")
#紧凑形式:
guess = eval(input( ))
print("猜{}了".format("对"if guess == 99 else"错"))
- 多分支结构:
guess = eval(input( ))
if guess>99:
print("猜错了")
elif guess<99:
print("猜错了")
else:
print("猜对了")
------
-
条件判断及组合:
guess = eval(input( ))
if guess>99 or guess<99:
print("猜错了")
else:
print("猜对了")
guess = eval(input( ))
if guess != 99:
print("猜错了")
else:
print("猜对了")
程序的异常处理:
身体质量指数BMI:
height,weight = eval(input( "请输入身高(米)和体重(公斤)[用逗号隔开]:"))
BMI = weight/pow(height,2)
print("BMI数值是{:.2f}".format(BMI))
who,nat = " "," "
if BMI < 18.5:
print("偏瘦","偏瘦")
elif 18.5<= BMI < 24:
print( "正常","正常")
elif 24<= BMI < 25:
print( "偏胖","正常")
elif 25<= BMI <28:
print( "偏胖","偏胖")
elif 28<= BMI < 30:
print( "肥胖","偏胖")
else :
print("肥胖","肥胖")
print("BMI指标为国内'{0}',国际'{1}'".format(who,nat))
程序的循环结构:
循环控制保留字break和continue:
- 一个break只能跳出最内层循环,且只能跳出一层循环。
循环的扩展:
循环与else:
for <循环变量> in <遍历结构>:
<语句块1>
else:
<语句块2>
while (条件):
<语句块1>
else:
<语句块2>
- 当循环没有被break退出时,执行else语句块
- else语句块作为“正常”完成循环的奖励
- 这里的else用法和程序异常处理的else用法相似
random库的使用:
圆周率的计算实例:
- 公式法
pi=0
for i in range(100):
pi += 1/pow(16,i)*(\
4/(8*i+1)–2/(8*i+4)–\
1/(8*i+5)–1/(8*i+6))
print("圆周率的近似值是:{:.9f}".format(pi))
- 蒙特卡洛法:
from random import random
from time import perf_counter
darts =1000*1000
hits = 0
start = perf_counter()
for i in range(0,darts):
x,y=random(),random()
dist = pow(x**2+y**2,0.5)
if dist <= 1:
hits += 1
print("圆周率的近似值是:{}".format(pi))
print("运行时间是:{:.5f}s".format(perf_counter()–start))