简述
掌握程序的控制逻辑(顺序结构、分支结构、循环结构),学会使用异常处理,掌握 random 库,具备应用随机数的能力。
课件
代码汇总
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 "错"))
score = eval(input())
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "E"
print("输入成绩属于级别{}".format(grade))
"""
90
输入成绩属于级别A
80
输入成绩属于级别B
30
输入成绩属于级别E
"""
guess = eval(input())
if guess > 99 or guess < 99:
print("猜错了")
else:
print("猜对了")
num = eval(input("请输入一个整数: "))
print(num**2)
"""
请输入一个整数: abc
Traceback (most recent call last):
File "/Users/huyouda/0/py/1.py", line 1, in <module>
num = eval(input("请输入一个整数: "))
File "<string>", line 1, in <module>
NameError: name 'abc' is not defined
"""
try:
num = eval(input("请输入一个整数:"))
print(num ** 2)
except:
print("输入不是整数")
try:
num = eval(input("请输入一个整数:"))
print(num ** 2)
except NameError:
print("输入不是整数")
height, weight = eval(input("请输入身高(米)和体重(公斤)[逗号隔开]: "))
print("height", height, "weight", weight)
bmi = weight / pow(height, 2)
print("BMI 数值为:{:.2f}".format(bmi))
who = ""
if bmi < 18.5:
who = "偏瘦"
elif 18.5 <= bmi < 25:
who = "正常"
elif 25 <= bmi < 30:
who = "偏胖"
else:
who = "肥胖"
print("BMI 指标为:国际'{0}'".format(who))
"""
请输入身高(米)和体重(公斤)[逗号隔开]: 1.66,66
height 1.66 weight 66
BMI 数值为:23.95
BMI 指标为:国际'正常'
"""
height, weight = eval(input("请输入身高(米)和体重(公斤)[逗号隔开]: "))
bmi = weight / pow(height, 2)
print("BMI 数值为:{:.2f}".format(bmi))
nat = ""
if bmi < 18.5:
nat = "偏瘦"
elif 18.5 <= bmi < 24:
nat = "正常"
elif 24 <= bmi < 28:
nat = "偏胖"
else:
nat = "肥胖"
print("BMI 指标为:国内'{0}'".format(nat))
"""
请输入身高(米)和体重(公斤)[逗号隔开]: 1.66,66
BMI 数值为:23.95
BMI 指标为:国内'正常'
"""
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 = "偏胖", "肥胖"
else:
who, nat = "肥胖", "肥胖"
print("BMI 指标为:国际'{0}', 国内'{1}'".format(who, nat))
"""
请输入身高(米)和体重(公斤)[逗号隔开]: 1.66,66
BMI 数值为:23.95
BMI 指标为:国际'正常', 国内'正常'
"""
for i in range(5):
print(i)
"""
0
1
2
3
4
"""
for i in range(5):
print("Hello:", i)
"""
Hello: 0
Hello: 1
Hello: 2
Hello: 3
Hello: 4
"""
for i in range(1, 6):
print(i)
"""
1
2
3
4
5
"""
for i in range(1, 6, 2):
print("Hello:", i)
"""
Hello: 1
Hello: 3
Hello: 5
"""
for item in [123, "PY", 456]:
print(item, end=",")
# 123,PY,456,
for c in "Python123":
print(c, end=",")
# P,y,t,h,o,n,1,2,3,
for c in "PYTHON":
if c == "T":
continue
print(c, end="") # PYHON
for c in "PYTHON":
if c == "T":
break
print(c, end="") # PY
a = 3
while a > 0:
a = a - 1
print(a)
"""
2
1
0
"""
a = 3
while a > 0:
a = a + 1
print(a)
"""
4
5
……(死循环,按下 Ctrl + C 终止程序)
"""
s = "PYTHON"
while s != "":
for c in s:
print(c, end="")
s = s[:-1]
# PYTHONPYTHOPYTHPYTPYP
s = "PYTHON"
while s != "":
for c in s:
if c == "T":
break
print(c, end="")
s = s[:-1]
# PYPYPYPYPYP
for c in "PYTHON":
if c == "T":
continue
print(c, end="")
else:
print("正常退出")
# PYHON正常退出
for c in "PYTHON":
if c == "T":
break
print(c, end="")
else:
print("正常退出")
# PY
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)) # 圆周率值是: 3.141592653589793
from random import random
from time import perf_counter
DARTS = 1000 * 1000
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))
"""
圆周率值是: 3.142448
运行时间是: 0.49618s
"""
from random import random, seed
DARTS = eval(input())
seed(123)
hits = 0.0
for i in range(DARTS):
x, y = random(), random()
dist = pow(x**2 + y**2, 0.5)
if dist <= 1.0:
hits = hits + 1
pi = 4 * (hits / DARTS)
print("{:.6f}".format(pi))
"""
1024
3.218750
"""
s = 0
count = 1
while count <= 966:
if count % 2 == 0:
s -= count
else:
s += count
count += 1
print(s) # -483
s = ""
for i in range(100, 1000):
t = str(i)
if pow(eval(t[0]), 3) + pow(eval(t[1]), 3) + pow(eval(t[2]), 3) == i:
s += "{},".format(i)
print(s[:-1])
# 153,370,371,407
count = 0
while count < 3:
name = input()
password = input()
if name == "Kate" and password == "666666":
print("登录成功!")
break
else:
count += 1
if count == 3:
print("3次用户名或者密码均有误!退出程序。")
"""
Kate
666666
登录成功!
kate
123
alice
456
john
111111
3次用户名或者密码均有误!退出程序。
"""
count = 0
while count < 3:
name = input()
password = input()
if name == "Kate" and password == "666666":
print("登录成功!")
break
else:
count += 1
print("用户名或密码错误")
if count == 3:
print("3次用户名或者密码均有误!退出程序。")
"""
kate
123
用户名或密码错误
alice
456
用户名或密码错误
john
111111
用户名或密码错误
3次用户名或者密码均有误!退出程序。
Kate
123
用户名或密码错误
Kate
123456
用户名或密码错误
Kate
666666
登录成功!
"""
import random
# 生成一个随机整数
random_number = random.randint(1, 10)
print(random_number) # 4
# 生成一个随机浮点数
random_float = random.random()
print(random_float) # 0.9022500027963487
import random
def estimate_pi(num_points):
points_in_circle = 0
points_total = num_points
for _ in range(num_points):
x = random.uniform(0, 1)
y = random.uniform(0, 1)
distance = x**2 + y**2
if distance <= 1:
points_in_circle += 1
pi_estimate = 4 * (points_in_circle / points_total)
return pi_estimate
num_points = 1000000
pi_estimate = estimate_pi(num_points)
print("Estimated value of pi:", pi_estimate)
"""
Estimated value of pi: 3.140988
Estimated value of pi: 3.142952
Estimated value of pi: 3.14064
"""
s = ""
for i in range(1000, 10000):
t = str(i)
if (
pow(eval(t[0]), 4)
+ pow(eval(t[1]), 4)
+ pow(eval(t[2]), 4)
+ pow(eval(t[3]), 4)
== i
):
print(i)
"""
1634
8208
9474
"""
def is_prime(n):
for i in range(2, n):
if n % i == 0:
return False
return True
sum = 0
for i in range(2, 100):
if is_prime(i):
sum += i
print(sum) # 1060
导学
课前复习
.mp4%22%2C%22size%22%3A46790667%2C%22taskId%22%3A%22uf39f911f-5960-4089-a0c2-156e60ccef3%22%2C%22taskType%22%3A%22upload%22%2C%22url%22%3Anull%2C%22cover%22%3Anull%2C%22videoId%22%3A%22inputs%2Fprod%2Fyuque%2F2023%2F2331396%2Fmp4%2F1688479990622-7377e6a9-5023-457f-92d2-e564508af4a7.mp4%22%2C%22download%22%3Afalse%2C%22__spacing%22%3A%22both%22%2C%22id%22%3A%22hKpCq%22%2C%22margin%22%3A%7B%22top%22%3Atrue%2C%22bottom%22%3Atrue%7D%2C%22card%22%3A%22video%22%7D#hKpCq)
本课概要
.mp4%22%2C%22size%22%3A28312337%2C%22taskId%22%3A%22ud4317b5a-9cab-45e7-8af5-08a4d487377%22%2C%22taskType%22%3A%22upload%22%2C%22url%22%3Anull%2C%22cover%22%3Anull%2C%22videoId%22%3A%22inputs%2Fprod%2Fyuque%2F2023%2F2331396%2Fmp4%2F1688479990615-bef27bfc-0cab-49b9-807f-53f6cd96fd3c.mp4%22%2C%22download%22%3Afalse%2C%22__spacing%22%3A%22both%22%2C%22id%22%3A%22i4Bg4%22%2C%22margin%22%3A%7B%22top%22%3Atrue%2C%22bottom%22%3Atrue%7D%2C%22card%22%3A%22video%22%7D#i4Bg4)
- 介绍程序的控制结构:
- 顺序结构
- 分支结构
- 循环结构
- 介绍 random 库的基本使用
- 通过两个实例练习来巩固所学内容
程序的分支结构
单元开篇
.mp4%22%2C%22size%22%3A13682470%2C%22taskId%22%3A%22u4a63b042-a376-4be7-ae4c-4396b596400%22%2C%22taskType%22%3A%22upload%22%2C%22url%22%3Anull%2C%22cover%22%3Anull%2C%22videoId%22%3A%22inputs%2Fprod%2Fyuque%2F2023%2F2331396%2Fmp4%2F1688479950921-0ac3dbac-84d5-4db0-a9f0-1d3b54f8d4e3.mp4%22%2C%22download%22%3Afalse%2C%22__spacing%22%3A%22both%22%2C%22id%22%3A%22A6Yx5%22%2C%22margin%22%3A%7B%22top%22%3Atrue%2C%22bottom%22%3Atrue%7D%2C%22card%22%3A%22video%22%7D#A6Yx5)
- 单分支结构
- 二分支结构
- 多分支结构
- 条件判断及组合
- 程序的异常处理
学完本节,你将了解分支结构几乎所有的内容。
单分支结构
.mp4%22%2C%22size%22%3A23240266%2C%22taskId%22%3A%22ude95ee85-1d1c-400a-861f-96af4790b8a%22%2C%22taskType%22%3A%22upload%22%2C%22url%22%3Anull%2C%22cover%22%3Anull%2C%22videoId%22%3A%22inputs%2Fprod%2Fyuque%2F2023%2F2331396%2Fmp4%2F1688479950917-c43c6d40-f265-4a1f-8a58-bb110056a078.mp4%22%2C%22download%22%3Afalse%2C%22__spacing%22%3A%22both%22%2C%22id%22%3A%22eCx7i%22%2C%22margin%22%3A%7B%22top%22%3Atrue%2C%22bottom%22%3Atrue%7D%2C%22card%22%3A%22video%22%7D#eCx7i)
guess = eval(input())
if (guess == 99):
print("猜对了")
二分支结构
.mp4%22%2C%22size%22%3A49119434%2C%22taskId%22%3A%22u72aa5fc7-6d24-4500-8036-655e8e64e97%22%2C%22taskType%22%3A%22upload%22%2C%22url%22%3Anull%2C%22cover%22%3Anull%2C%22videoId%22%3A%22inputs%2Fprod%2Fyuque%2F2023%2F2331396%2Fmp4%2F1688479950948-56fcaf24-c9f3-44ba-854b-478e3b2e8549.mp4%22%2C%22download%22%3Afalse%2C%22__spacing%22%3A%22both%22%2C%22id%22%3A%22SftIZ%22%2C%22margin%22%3A%7B%22top%22%3Atrue%2C%22bottom%22%3Atrue%7D%2C%22card%22%3A%22video%22%7D#SftIZ)
guess = eval(input())
if (guess == 99):
print("猜对了")
else:
print("猜错了")
guess = eval(input())
print("猜{}了".format("对" if guess == 99 else "错"))
多分支结构
.mp4%22%2C%22size%22%3A30993689%2C%22taskId%22%3A%22ufb6c4a3d-cbc5-4a5a-9537-bed907cb9e2%22%2C%22taskType%22%3A%22upload%22%2C%22url%22%3Anull%2C%22cover%22%3Anull%2C%22videoId%22%3A%22inputs%2Fprod%2Fyuque%2F2023%2F2331396%2Fmp4%2F1688479950941-0819532d-be36-44ce-ad74-f2e368bc5532.mp4%22%2C%22download%22%3Afalse%2C%22__spacing%22%3A%22both%22%2C%22id%22%3A%22rhEVx%22%2C%22margin%22%3A%7B%22top%22%3Atrue%2C%22bottom%22%3Atrue%7D%2C%22card%22%3A%22video%22%7D#rhEVx)
score = eval(input())
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "E"
print("输入成绩属于级别{}".format(grade))
"""
90
输入成绩属于级别A
80
输入成绩属于级别B
30
输入成绩属于级别E
"""
条件判断及组合
.mp4%22%2C%22size%22%3A32401383%2C%22taskId%22%3A%22u5364bf01-0277-4a08-bf56-d8d74a70ea4%22%2C%22taskType%22%3A%22upload%22%2C%22url%22%3Anull%2C%22cover%22%3Anull%2C%22videoId%22%3A%22inputs%2Fprod%2Fyuque%2F2023%2F2331396%2Fmp4%2F1688479950962-7162cd35-d841-49f9-91a0-349f694aa774.mp4%22%2C%22download%22%3Afalse%2C%22__spacing%22%3A%22both%22%2C%22id%22%3A%22sagAJ%22%2C%22margin%22%3A%7B%22top%22%3Atrue%2C%22bottom%22%3Atrue%7D%2C%22card%22%3A%22video%22%7D#sagAJ)
guess = eval(input())
if guess > 99 or guess < 99:
print("猜错了")
else:
print("猜对了")
程序的异常处理
.mp4%22%2C%22size%22%3A77264456%2C%22taskId%22%3A%22u5c744b4e-5c2a-4700-9dfd-112e421aa60%22%2C%22taskType%22%3A%22upload%22%2C%22url%22%3Anull%2C%22cover%22%3Anull%2C%22videoId%22%3A%22inputs%2Fprod%2Fyuque%2F2023%2F2331396%2Fmp4%2F1688479959896-f43af88d-a3e9-4123-8ddd-07a3232a84da.mp4%22%2C%22download%22%3Afalse%2C%22__spacing%22%3A%22both%22%2C%22id%22%3A%22u2vm1%22%2C%22margin%22%3A%7B%22top%22%3Atrue%2C%22bottom%22%3Atrue%7D%2C%22card%22%3A%22video%22%7D#u2vm1)
num = eval(input("请输入一个整数: "))
print(num**2)
"""
请输入一个整数: abc
Traceback (most recent call last):
File "/Users/huyouda/0/py/1.py", line 1, in <module>
num = eval(input("请输入一个整数: "))
File "<string>", line 1, in <module>
NameError: name 'abc' is not defined
"""
try:
num = eval(input("请输入一个整数:"))
print(num ** 2)
except:
print("输入不是整数")
try:
num = eval(input("请输入一个整数:"))
print(num ** 2)
except NameError:
print("输入不是整数")
单元小结
.mp4%22%2C%22size%22%3A10529282%2C%22taskId%22%3A%22ucebcaba0-cfa6-4f5e-a9e3-30458a38e0b%22%2C%22taskType%22%3A%22upload%22%2C%22url%22%3Anull%2C%22cover%22%3Anull%2C%22videoId%22%3A%22inputs%2Fprod%2Fyuque%2F2023%2F2331396%2Fmp4%2F1688479963754-c39ff0e5-08bb-49be-9980-a9efcb1aba6d.mp4%22%2C%22download%22%3Afalse%2C%22__spacing%22%3A%22both%22%2C%22id%22%3A%22jBlba%22%2C%22margin%22%3A%7B%22top%22%3Atrue%2C%22bottom%22%3Atrue%7D%2C%22card%22%3A%22video%22%7D#jBlba)
实例 5:身体质量指数 BMI
问题分析
.mp4%22%2C%22size%22%3A48002161%2C%22taskId%22%3A%22u411f7be6-bf08-4c5f-87bb-ecdc84c7e92%22%2C%22taskType%22%3A%22upload%22%2C%22url%22%3Anull%2C%22cover%22%3Anull%2C%22videoId%22%3A%22inputs%2Fprod%2Fyuque%2F2023%2F2331396%2Fmp4%2F1688480059627-17913062-bb9c-45ed-baa8-19789dd3bcb2.mp4%22%2C%22download%22%3Afalse%2C%22__spacing%22%3A%22both%22%2C%22id%22%3A%22qVROX%22%2C%22margin%22%3A%7B%22top%22%3Atrue%2C%22bottom%22%3Atrue%7D%2C%22card%22%3A%22video%22%7D#qVROX)
实例讲解
.mp4%22%2C%22size%22%3A73084530%2C%22taskId%22%3A%22ua93b8d01-7a6b-4984-bb54-592bf5e1c98%22%2C%22taskType%22%3A%22upload%22%2C%22url%22%3Anull%2C%22cover%22%3Anull%2C%22videoId%22%3A%22inputs%2Fprod%2Fyuque%2F2023%2F2331396%2Fmp4%2F1688480059631-9db20ccc-05aa-4aeb-ac94-aa533fd40bcd.mp4%22%2C%22download%22%3Afalse%2C%22__spacing%22%3A%22both%22%2C%22id%22%3A%22lQFgA%22%2C%22margin%22%3A%7B%22top%22%3Atrue%2C%22bottom%22%3Atrue%7D%2C%22card%22%3A%22video%22%7D#lQFgA)
height, weight = eval(input("请输入身高(米)和体重(公斤)[逗号隔开]: "))
print("height", height, "weight", weight)
bmi = weight / pow(height, 2)
print("BMI 数值为:{:.2f}".format(bmi))
who = ""
if bmi < 18.5:
who = "偏瘦"
elif 18.5 <= bmi < 25:
who = "正常"
elif 25 <= bmi < 30:
who = "偏胖"
else:
who = "肥胖"
print("BMI 指标为:国际'{0}'".format(who))
"""
请输入身高(米)和体重(公斤)[逗号隔开]: 1.66,66
height 1.66 weight 66
BMI 数值为:23.95
BMI 指标为:国际'正常'
"""
height, weight = eval(input("请输入身高(米)和体重(公斤)[逗号隔开]: "))
bmi = weight / pow(height, 2)
print("BMI 数值为:{:.2f}".format(bmi))
nat = ""
if bmi < 18.5:
nat = "偏瘦"
elif 18.5 <= bmi < 24:
nat = "正常"
elif 24 <= bmi < 28:
nat = "偏胖"
else:
nat = "肥胖"
print("BMI 指标为:国内'{0}'".format(nat))
"""
请输入身高(米)和体重(公斤)[逗号隔开]: 1.66,66
BMI 数值为:23.95
BMI 指标为:国内'正常'
"""
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 = "偏胖", "肥胖"
else:
who, nat = "肥胖", "肥胖"
print("BMI 指标为:国际'{0}', 国内'{1}'".format(who, nat))
"""
请输入身高(米)和体重(公斤)[逗号隔开]: 1.66,66
BMI 数值为:23.95
BMI 指标为:国际'正常', 国内'正常'
"""
举一反三
.mp4%22%2C%22size%22%3A25156785%2C%22taskId%22%3A%22u5512ed39-acde-4f22-9af2-5033736add1%22%2C%22taskType%22%3A%22upload%22%2C%22url%22%3Anull%2C%22cover%22%3Anull%2C%22videoId%22%3A%22inputs%2Fprod%2Fyuque%2F2023%2F2331396%2Fmp4%2F1688480059653-f068b3ad-ab96-4d27-991e-e54c423ae3a9.mp4%22%2C%22download%22%3Afalse%2C%22__spacing%22%3A%22both%22%2C%22id%22%3A%22acGQR%22%2C%22margin%22%3A%7B%22top%22%3Atrue%2C%22bottom%22%3Atrue%7D%2C%22card%22%3A%22video%22%7D#acGQR)
程序的循环结构
单元开篇
.mp4%22%2C%22size%22%3A12424289%2C%22taskId%22%3A%22u6200b03f-2f97-4a7f-bdf6-7061fe55cc8%22%2C%22taskType%22%3A%22upload%22%2C%22url%22%3Anull%2C%22cover%22%3Anull%2C%22videoId%22%3A%22inputs%2Fprod%2Fyuque%2F2023%2F2331396%2Fmp4%2F1688480103562-852eb218-3b2b-4e07-baa0-a29622df3e87.mp4%22%2C%22download%22%3Afalse%2C%22__spacing%22%3A%22both%22%2C%22id%22%3A%22n9MCu%22%2C%22margin%22%3A%7B%22top%22%3Atrue%2C%22bottom%22%3Atrue%7D%2C%22card%22%3A%22video%22%7D#n9MCu)
遍历循环 for
.mp4%22%2C%22size%22%3A153509544%2C%22taskId%22%3A%22u14b6de9c-e1df-46f5-a296-f6b606fb089%22%2C%22taskType%22%3A%22upload%22%2C%22url%22%3Anull%2C%22cover%22%3Anull%2C%22videoId%22%3A%22inputs%2Fprod%2Fyuque%2F2023%2F2331396%2Fmp4%2F1688480103587-4eedc2d2-af12-4b62-9f49-4e74c72a3fda.mp4%22%2C%22download%22%3Afalse%2C%22__spacing%22%3A%22both%22%2C%22id%22%3A%22qyORW%22%2C%22margin%22%3A%7B%22top%22%3Atrue%2C%22bottom%22%3Atrue%7D%2C%22card%22%3A%22video%22%7D#qyORW) 遍历循环是由 for-in 构成的循环结构
遍历循环的应用:
- 计数循环(N次)
- 计数循环(特定次)
- 字符串遍历循环
- 列表遍历循环
- 文件遍历循环
- ……
for i in range(5):
print(i)
"""
0
1
2
3
4
"""
for i in range(5):
print("Hello:", i)
"""
Hello: 0
Hello: 1
Hello: 2
Hello: 3
Hello: 4
"""
for i in range(1, 6):
print(i)
"""
1
2
3
4
5
"""
for i in range(1, 6, 2):
print("Hello:", i)
"""
Hello: 1
Hello: 3
Hello: 5
"""
for c in "Python123":
print(c, end=",")
# P,y,t,h,o,n,1,2,3,
for item in [123, "PY", 456]:
print(item, end=",")
# 123,PY,456,
无限循环 while
.mp4%22%2C%22size%22%3A30300888%2C%22taskId%22%3A%22u1511a13c-83ae-44aa-997f-a4df9a6d76f%22%2C%22taskType%22%3A%22upload%22%2C%22url%22%3Anull%2C%22cover%22%3Anull%2C%22videoId%22%3A%22inputs%2Fprod%2Fyuque%2F2023%2F2331396%2Fmp4%2F1688480103586-d9acee30-d95a-4d6e-ad64-953da7264c20.mp4%22%2C%22download%22%3Afalse%2C%22__spacing%22%3A%22both%22%2C%22id%22%3A%22LXYjO%22%2C%22margin%22%3A%7B%22top%22%3Atrue%2C%22bottom%22%3Atrue%7D%2C%22card%22%3A%22video%22%7D#LXYjO)
a = 3
while a > 0:
a = a - 1
print(a)
"""
2
1
0
"""
a = 3
while a > 0:
a = a + 1
print(a)
"""
4
5
……(死循环,按下 Ctrl + C 终止程序)
"""
循环控制保留字 break、continue
.mp4%22%2C%22size%22%3A107709866%2C%22taskId%22%3A%22uac4d9437-b74e-4f85-988c-672c371beaa%22%2C%22taskType%22%3A%22upload%22%2C%22url%22%3Anull%2C%22cover%22%3Anull%2C%22videoId%22%3A%22inputs%2Fprod%2Fyuque%2F2023%2F2331396%2Fmp4%2F1688480103578-19f2fa1b-4901-4ea7-a9d1-7b974bdda6f0.mp4%22%2C%22download%22%3Afalse%2C%22__spacing%22%3A%22both%22%2C%22id%22%3A%22yj6oz%22%2C%22margin%22%3A%7B%22top%22%3Atrue%2C%22bottom%22%3Atrue%7D%2C%22card%22%3A%22video%22%7D#yj6oz)
for c in "PYTHON":
if c == "T":
continue
print(c, end="") # PYHON
for c in "PYTHON":
if c == "T":
break
print(c, end="") # PY
s = "PYTHON"
while s != "":
for c in s:
print(c, end="") # PYTHONPYTHOPYTHPYTPYP
s = s[:-1]
s = "PYTHON"
while s != "":
for c in s:
if c == "T":
break
print(c, end="") # PYPYPYPYPYP
s = s[:-1]
循环的高级用法
.mp4%22%2C%22size%22%3A53467684%2C%22taskId%22%3A%22uc335a401-983a-4168-8cbd-c300685d418%22%2C%22taskType%22%3A%22upload%22%2C%22url%22%3Anull%2C%22cover%22%3Anull%2C%22videoId%22%3A%22inputs%2Fprod%2Fyuque%2F2023%2F2331396%2Fmp4%2F1688480103585-a6db5284-6572-4d11-8fd9-62085955985a.mp4%22%2C%22download%22%3Afalse%2C%22__spacing%22%3A%22both%22%2C%22id%22%3A%22QOMjm%22%2C%22margin%22%3A%7B%22top%22%3Atrue%2C%22bottom%22%3Atrue%7D%2C%22card%22%3A%22video%22%7D#QOMjm)
- 当循环没有被 break 语句退出时,执行 else 语句块
- else 语句块作为”正常”完成循环的奖励
- 这里 else 的用法与异常处理中 else 用法相似
for c in "PYTHON":
if c == "T":
continue
print(c, end="")
else:
print("正常退出")
# PYHON正常退出
for c in "PYTHON":
if c == "T":
break
print(c, end="")
else:
print("正常退出")
# PY
单元小结
.mp4%22%2C%22size%22%3A20475654%2C%22taskId%22%3A%22ufafa8857-b426-4082-bde5-b866a151e3a%22%2C%22taskType%22%3A%22upload%22%2C%22url%22%3Anull%2C%22cover%22%3Anull%2C%22videoId%22%3A%22inputs%2Fprod%2Fyuque%2F2023%2F2331396%2Fmp4%2F1688480112453-8f051d3e-d7c1-4ea8-b2d9-1b22094cb133.mp4%22%2C%22download%22%3Afalse%2C%22__spacing%22%3A%22both%22%2C%22id%22%3A%22ULUGi%22%2C%22margin%22%3A%7B%22top%22%3Atrue%2C%22bottom%22%3Atrue%7D%2C%22card%22%3A%22video%22%7D#ULUGi)
模块 3:random 库的使用
random 库基本介绍
.mp4%22%2C%22size%22%3A35594764%2C%22taskId%22%3A%22u389a3a7b-59ba-4ded-8a94-5c69382ef8a%22%2C%22taskType%22%3A%22upload%22%2C%22url%22%3Anull%2C%22cover%22%3Anull%2C%22videoId%22%3A%22inputs%2Fprod%2Fyuque%2F2023%2F2331396%2Fmp4%2F1688480128698-1d5196e7-8bcc-4c5d-9f02-ba76ec318e3f.mp4%22%2C%22download%22%3Afalse%2C%22__spacing%22%3A%22both%22%2C%22id%22%3A%22tTRaV%22%2C%22margin%22%3A%7B%22top%22%3Atrue%2C%22bottom%22%3Atrue%7D%2C%22card%22%3A%22video%22%7D#tTRaV) random 库是使用随机数的 Python 标准库
- 伪随机数: 采用梅森旋转算法生成的(伪)随机序列中元素
- random 库主要用于生成随机数
- 使用 random 库:
import random
random 库包括两类函数,常用共 8 个
- 基本随机数函数:
seed()
random()
- 扩展随机数函数:
randint()
getrandbits()
uniform()
randrange()
choice()
shuffle()
基本随机数函数
.mp4%22%2C%22size%22%3A71496961%2C%22taskId%22%3A%22u3e13d23b-65b4-491e-a589-048f6a86c9a%22%2C%22taskType%22%3A%22upload%22%2C%22url%22%3Anull%2C%22cover%22%3Anull%2C%22videoId%22%3A%22inputs%2Fprod%2Fyuque%2F2023%2F2331396%2Fmp4%2F1688480128718-652d3e87-e011-4655-8a55-85928d3e7cd6.mp4%22%2C%22download%22%3Afalse%2C%22__spacing%22%3A%22both%22%2C%22id%22%3A%22A1tPY%22%2C%22margin%22%3A%7B%22top%22%3Atrue%2C%22bottom%22%3Atrue%7D%2C%22card%22%3A%22video%22%7D#A1tPY)
随机数种子确定了随机序列的产生
通常无需手动去调用 random.seed
函数去设置随机数种子,设置种子的这个步骤在我们每次调用 random.random
时,会自动使用当前系统时间作为随机数种子帮我们调用一次 random.seed
函数。
扩展随机数函数
.mp4%22%2C%22size%22%3A85336340%2C%22taskId%22%3A%22u62a97357-e850-4e15-afec-a93952386a3%22%2C%22taskType%22%3A%22upload%22%2C%22url%22%3Anull%2C%22cover%22%3Anull%2C%22videoId%22%3A%22inputs%2Fprod%2Fyuque%2F2023%2F2331396%2Fmp4%2F1688480128724-faa7e78c-1ced-4642-b3bc-26b4ced71290.mp4%22%2C%22download%22%3Afalse%2C%22__spacing%22%3A%22both%22%2C%22id%22%3A%22NE4xa%22%2C%22margin%22%3A%7B%22top%22%3Atrue%2C%22bottom%22%3Atrue%7D%2C%22card%22%3A%22video%22%7D#NE4xa)
对于 random 库,我们需要具备以下能力:
- 能够利用随机数种子产生”确定”伪随机数
- 能够产生随机整数
- 能够对序列类型进行随机操作
实例 6:圆周率的计算
问题分析
.mp4%22%2C%22size%22%3A46191756%2C%22taskId%22%3A%22u73e76bdc-af91-4810-934e-1a2fe8fed9b%22%2C%22taskType%22%3A%22upload%22%2C%22url%22%3Anull%2C%22cover%22%3Anull%2C%22videoId%22%3A%22inputs%2Fprod%2Fyuque%2F2023%2F2331396%2Fmp4%2F1688480176698-271afdaf-9e92-4409-8a5e-e6b5f1e226da.mp4%22%2C%22download%22%3Afalse%2C%22__spacing%22%3A%22both%22%2C%22id%22%3A%22pNMIk%22%2C%22margin%22%3A%7B%22top%22%3Atrue%2C%22bottom%22%3Atrue%7D%2C%22card%22%3A%22video%22%7D#pNMIk)
讲解
.mp4%22%2C%22size%22%3A118878825%2C%22taskId%22%3A%22uacfc243f-774b-4e02-89f1-e6582c7cd93%22%2C%22taskType%22%3A%22upload%22%2C%22url%22%3Anull%2C%22cover%22%3Anull%2C%22videoId%22%3A%22inputs%2Fprod%2Fyuque%2F2023%2F2331396%2Fmp4%2F1688480176701-d6cfbd86-431e-4886-a2e6-8d373109be7c.mp4%22%2C%22download%22%3Afalse%2C%22__spacing%22%3A%22both%22%2C%22id%22%3A%22a4SGp%22%2C%22margin%22%3A%7B%22top%22%3Atrue%2C%22bottom%22%3Atrue%7D%2C%22card%22%3A%22video%22%7D#a4SGp)
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)) # 圆周率值是: 3.141592653589793
from random import random
from time import perf_counter
DARTS = 1000 * 1000
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))
"""
圆周率值是: 3.142448
运行时间是: 0.49618s
"""
举一反三
.mp4%22%2C%22size%22%3A83083196%2C%22taskId%22%3A%22u0bdd0ebd-a30f-4a13-96d4-25f57f0f6d1%22%2C%22taskType%22%3A%22upload%22%2C%22url%22%3Anull%2C%22cover%22%3Anull%2C%22videoId%22%3A%22inputs%2Fprod%2Fyuque%2F2023%2F2331396%2Fmp4%2F1688480176724-8a371e8f-0000-4dc8-880c-8cf60ecb87a7.mp4%22%2C%22download%22%3Afalse%2C%22__spacing%22%3A%22both%22%2C%22id%22%3A%22b2fmz%22%2C%22margin%22%3A%7B%22top%22%3Atrue%2C%22bottom%22%3Atrue%7D%2C%22card%22%3A%22video%22%7D#b2fmz)
程序运行时间分析
- 使用time库的计时方法获得程序运行时间
- 改变撒点数量,理解程序运行时间的分布
- 初步掌握简单的程序性能分析方法
有科学家做过统计,一个程序运行的大部分(≈ 80%)时间,耗费在(≈ 10%)的代码(循环代码)上。
我们在看待一个程序性能时,需要重点关注程序的循环部分。
比如:如果我们编写的程序执行耗时比较长,此时可优先关注循环部分,使用 time 库来测量一下从进入循环到离开循环所消耗的时间。
练习
单选题
k = 10000
counter = 0
while k > 1:
counter += 1
print(counter, '\t', k)
k = k / 2
"""
1 10000
2 5000.0
3 2500.0
4 1250.0
5 625.0
6 312.5
7 156.25
8 78.125
9 39.0625
10 19.53125
11 9.765625
12 4.8828125
13 2.44140625
14 1.220703125
"""
for s in "PYTHON":
if s == "T":
continue
print(s, end="")
# PYHON
四位玫瑰数
s = ""
for i in range(1000, 10000):
t = str(i)
if (
pow(eval(t[0]), 4)
+ pow(eval(t[1]), 4)
+ pow(eval(t[2]), 4)
+ pow(eval(t[3]), 4)
== i
):
print(i)
"""
1634
8208
9474
"""
100 以内素数之和
def is_prime(n):
for i in range(2, n):
if n % i == 0:
return False
return True
sum = 0
for i in range(2, 100):
if is_prime(i):
sum += i
print(sum) # 1060
实例 5:身体质量指数 BMI
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 = "偏胖", "肥胖"
else:
who, nat = "肥胖", "肥胖"
print("BMI指标为:国际'{0}',国内'{1}'".format(who, nat))
"""
1.68,41
BMI数值为:14.53
BMI指标为:国际'偏瘦',国内'偏瘦'
1.72,80
BMI数值为:27.04
BMI指标为:国际'偏胖',国内'偏胖'
1.66,66
BMI数值为:23.95
BMI指标为:国际'正常',国内'正常'
"""
这是本课程的实例5:
(1) 多分支条件之间的覆盖是重要问题;
(2) BMI分类:
实例 6:圆周率的计算
from random import random, seed
DARTS = eval(input())
seed(123)
hits = 0.0
for i in range(DARTS):
x, y = random(), random()
dist = pow(x**2 + y**2, 0.5)
if dist <= 1.0:
hits = hits + 1
pi = 4 * (hits / DARTS)
print("{:.6f}".format(pi))
"""
1024
3.218750
"""
这是本课程的实例6,请注意:from...import
引入具体的函数,使用 seed()
需要提前引入
整数的加减和
s = 0
count = 1
while count <= 966:
if count % 2 == 0:
s -= count
else:
s += count
count += 1
print(s) # -483
这个题应该没什么可解释的。
三位水仙花数
s = ""
for i in range(100, 1000):
t = str(i)
if pow(eval(t[0]), 3) + pow(eval(t[1]), 3) + pow(eval(t[2]), 3) == i:
s += "{},".format(i)
print(s[:-1])
# 153,370,371,407
这里采用了 s[:-1]
方式不输出最后一个逗号。也可以把所有结果放到一个列表中,采用字符串的 .join()
方法输出结果。
用户登录的三次机会
count = 0
while count < 3:
name = input()
password = input()
if name == "Kate" and password == "666666":
print("登录成功!")
break
else:
count += 1
if count == 3:
print("3次用户名或者密码均有误!退出程序。")
"""
Kate
666666
登录成功!
kate
123
alice
456
john
111111
3次用户名或者密码均有误!退出程序。
"""
这里是参考答案,运用 while 进行非确定次数循环。
按照题目要求的示例来实现程序,在交互上会感觉很别扭,因为输入失败后并没有给予错误提示。
count = 0
while count < 3:
name = input()
password = input()
if name == "Kate" and password == "666666":
print("登录成功!")
break
else:
count += 1
print("用户名或密码错误")
if count == 3:
print("3次用户名或者密码均有误!退出程序。")
"""
kate
123
用户名或密码错误
alice
456
用户名或密码错误
john
111111
用户名或密码错误
3次用户名或者密码均有误!退出程序。
Kate
123
用户名或密码错误
Kate
123456
用户名或密码错误
Kate
666666
登录成功!
"""
补充
资深程序员如何看待编程工具?
梅森旋转算法
梅森旋转算法(Mersenne Twister Algorithm)是一种广泛应用的随机数生成算法。它由松本真(Makoto Matsumoto)和西村拓士(Takuji Nishimura)于1997年开发,被认为是目前最常用的伪随机数生成算法之一。
梅森旋转算法的特点包括:
- 高周期性:该算法使用一个很大的状态空间(219937-1),能够产生非常长的周期,约为219937-1个随机数序列。这意味着在很长一段时间内生成的随机数序列不会重复。
- 高质量的随机数:梅森旋转算法生成的随机数具有较好的统计特性,可以满足大多数应用的随机性需求。
- 快速性能:梅森旋转算法的计算速度相对较快,适用于大量的随机数生成需求。
在Python中,标准库的random
模块使用的随机数生成器就是基于梅森旋转算法的。你可以使用random
模块来生成随机数,例如:
import random
# 生成一个随机整数
random_number = random.randint(1, 10)
print(random_number)
# 生成一个随机浮点数
random_float = random.random()
print(random_float)
除了random
模块,还有一些第三方库也提供了更高级和更灵活的梅森旋转算法实现,例如numpy
库中的numpy.random
模块,可以生成更多类型的随机数。
总而言之,梅森旋转算法是一种可靠、高质量且高性能的随机数生成算法,适用于许多应用领域,包括模拟、密码学、游戏开发等。
学不会编程怎么办?
虽然是打鸡血,不过说得确实有道理……
蒙特卡罗方法
蒙特卡罗方法(Monte Carlo Method)是一种基于随机抽样和统计推断的计算方法。它以概率统计理论为基础,通过生成大量的随机样本来近似计算问题的解。
蒙特卡罗方法常用于解决无法通过解析方法求解的复杂问题,特别是涉及概率、统计和数值计算的领域。它的基本思想是通过随机抽样和大数定律,通过大量的重复试验得到问题的近似解。
蒙特卡罗方法的应用领域非常广泛,包括但不限于以下几个方面:
- 数值计算:蒙特卡罗方法可以用来计算复杂的数学积分、求解微分方程、模拟随机过程等。通过生成大量的随机样本,并根据这些样本的统计特性进行数值计算。
- 金融领域:蒙特卡罗方法在金融工程中被广泛应用,用于模拟股票价格、利率变动、期权定价等问题。通过随机模拟大量的市场情景,评估金融产品的风险和收益。
- 物理模拟:蒙特卡罗方法在物理学研究中也有重要应用,如粒子物理学中的事件生成、核反应的模拟等。通过生成随机粒子的运动轨迹,模拟物理系统的行为。
- 统计推断:蒙特卡罗方法可以用于参数估计、假设检验、置信区间等统计推断问题。通过生成大量的随机样本,进行统计推断,得到对问题的近似解。
蒙特卡罗方法的基本步骤包括:
- 定义问题:明确要解决的问题和需要计算的量。
- 设定模型:选择合适的数学模型或概率模型来描述问题。
- 随机抽样:通过随机数生成器生成大量的随机样本。
- 计算量的统计特性:根据抽样的结果,计算所关注的量的统计特性,如平均值、方差等。
- 结果评估:通过对统计特性进行分析和解释,得到问题的近似解或概率分布。
总而言之,蒙特卡罗方法是一种基于随机抽样和统计推断的计算方法,适用于解决各种复杂问题。它的优势在于可以处理高维、非线性和难以求解的问题,并且具有较好的数值稳定性和可扩展性。
以下是蒙特卡罗方法用于估算圆周率 π 的原理:
- 在一个边长为 L 的正方形内部,画一个半径为 R 的圆,使其完全内切于正方形。这意味着正方形的边界与圆的周界相切。
- 根据几何关系,该圆的面积为 A = πR^2,正方形的面积为 A_square = L^2。
- 假设我们随机均匀地在该正方形内生成足够多的点。
- 统计落在圆内的点的数量,假设为 N_circle。
- 统计总共生成的点的数量,假设为 N_total。
- 根据几何关系,圆的面积与正方形的面积之比为 A/A_square = πR^2 / L^2。同样,落在圆内的点的数量与总点数之比也近似等于这个比值,即 N_circle / N_total ≈ A / A_square。
- 根据步骤 6 中的比值,我们可以得到一个近似的 π 的估计值:π ≈ 4 * (N_circle / N_total)。
蒙特卡罗方法利用大量的随机点的统计性质来估算圆的面积与正方形的面积之比,从而估算出圆周率 π 的值。通过增加生成的随机点数量,可以提高估算的准确性。
需要注意的是,蒙特卡罗方法是一种概率性方法,估算的结果会受到随机抽样的影响。为了得到更准确的估计,通常需要生成足够多的随机点。
下面是一个使用蒙特卡罗方法估算圆周率的简单示例代码:
import random
def estimate_pi(num_points):
points_in_circle = 0
points_total = num_points
for _ in range(num_points):
x = random.uniform(0, 1)
y = random.uniform(0, 1)
distance = x**2 + y**2
if distance <= 1:
points_in_circle += 1
pi_estimate = 4 * (points_in_circle / points_total)
return pi_estimate
num_points = 1000000
pi_estimate = estimate_pi(num_points)
print("Estimated value of pi:", pi_estimate)
这个代码通过生成一百万个随机点,并统计落在单位正方形内的落在单位圆内的点的数量,从而估算圆周率的值。