简述

4. 程序的控制结构 - 图1

掌握程序的控制逻辑(顺序结构、分支结构、循环结构),学会使用异常处理,掌握 random 库,具备应用随机数的能力。

课件

4.pdf

代码汇总

  1. guess = eval(input())
  2. if (guess == 99):
  3. print("猜对了")
  1. guess = eval(input())
  2. if (guess == 99):
  3. print("猜对了")
  4. else:
  5. print("猜错了")
  1. guess = eval(input())
  2. print("猜{}了".format("对" if guess == 99 else "错"))
  1. score = eval(input())
  2. if score >= 90:
  3. grade = "A"
  4. elif score >= 80:
  5. grade = "B"
  6. elif score >= 70:
  7. grade = "C"
  8. elif score >= 60:
  9. grade = "D"
  10. else:
  11. grade = "E"
  12. print("输入成绩属于级别{}".format(grade))
  13. """
  14. 90
  15. 输入成绩属于级别A
  16. 80
  17. 输入成绩属于级别B
  18. 30
  19. 输入成绩属于级别E
  20. """
  1. guess = eval(input())
  2. if guess > 99 or guess < 99:
  3. print("猜错了")
  4. else:
  5. print("猜对了")
  1. num = eval(input("请输入一个整数: "))
  2. print(num**2)
  3. """
  4. 请输入一个整数: abc
  5. Traceback (most recent call last):
  6. File "/Users/huyouda/0/py/1.py", line 1, in <module>
  7. num = eval(input("请输入一个整数: "))
  8. File "<string>", line 1, in <module>
  9. NameError: name 'abc' is not defined
  10. """
  1. try:
  2. num = eval(input("请输入一个整数:"))
  3. print(num ** 2)
  4. except:
  5. print("输入不是整数")
  1. try:
  2. num = eval(input("请输入一个整数:"))
  3. print(num ** 2)
  4. except NameError:
  5. print("输入不是整数")
  1. height, weight = eval(input("请输入身高(米)和体重(公斤)[逗号隔开]: "))
  2. print("height", height, "weight", weight)
  3. bmi = weight / pow(height, 2)
  4. print("BMI 数值为:{:.2f}".format(bmi))
  5. who = ""
  6. if bmi < 18.5:
  7. who = "偏瘦"
  8. elif 18.5 <= bmi < 25:
  9. who = "正常"
  10. elif 25 <= bmi < 30:
  11. who = "偏胖"
  12. else:
  13. who = "肥胖"
  14. print("BMI 指标为:国际'{0}'".format(who))
  15. """
  16. 请输入身高(米)和体重(公斤)[逗号隔开]: 1.66,66
  17. height 1.66 weight 66
  18. BMI 数值为:23.95
  19. BMI 指标为:国际'正常'
  20. """
  1. height, weight = eval(input("请输入身高(米)和体重(公斤)[逗号隔开]: "))
  2. bmi = weight / pow(height, 2)
  3. print("BMI 数值为:{:.2f}".format(bmi))
  4. nat = ""
  5. if bmi < 18.5:
  6. nat = "偏瘦"
  7. elif 18.5 <= bmi < 24:
  8. nat = "正常"
  9. elif 24 <= bmi < 28:
  10. nat = "偏胖"
  11. else:
  12. nat = "肥胖"
  13. print("BMI 指标为:国内'{0}'".format(nat))
  14. """
  15. 请输入身高(米)和体重(公斤)[逗号隔开]: 1.66,66
  16. BMI 数值为:23.95
  17. BMI 指标为:国内'正常'
  18. """
  1. height, weight = eval(input("请输入身高(米)和体重(公斤)[逗号隔开]: "))
  2. bmi = weight / pow(height, 2)
  3. print("BMI 数值为:{:.2f}".format(bmi))
  4. who, nat = "", ""
  5. if bmi < 18.5:
  6. who, nat = "偏瘦", "偏瘦"
  7. elif 18.5 <= bmi < 24:
  8. who, nat = "正常", "正常"
  9. elif 24 <= bmi < 25:
  10. who, nat = "正常", "偏胖"
  11. elif 25 <= bmi < 28:
  12. who, nat = "偏胖", "偏胖"
  13. elif 28 <= bmi < 30:
  14. who, nat = "偏胖", "肥胖"
  15. else:
  16. who, nat = "肥胖", "肥胖"
  17. print("BMI 指标为:国际'{0}', 国内'{1}'".format(who, nat))
  18. """
  19. 请输入身高(米)和体重(公斤)[逗号隔开]: 1.66,66
  20. BMI 数值为:23.95
  21. BMI 指标为:国际'正常', 国内'正常'
  22. """
  1. for i in range(5):
  2. print(i)
  3. """
  4. 0
  5. 1
  6. 2
  7. 3
  8. 4
  9. """
  1. for i in range(5):
  2. print("Hello:", i)
  3. """
  4. Hello: 0
  5. Hello: 1
  6. Hello: 2
  7. Hello: 3
  8. Hello: 4
  9. """
  1. for i in range(1, 6):
  2. print(i)
  3. """
  4. 1
  5. 2
  6. 3
  7. 4
  8. 5
  9. """
  1. for i in range(1, 6, 2):
  2. print("Hello:", i)
  3. """
  4. Hello: 1
  5. Hello: 3
  6. Hello: 5
  7. """
  1. for item in [123, "PY", 456]:
  2. print(item, end=",")
  3. # 123,PY,456,
  1. for c in "Python123":
  2. print(c, end=",")
  3. # P,y,t,h,o,n,1,2,3,
  1. for c in "PYTHON":
  2. if c == "T":
  3. continue
  4. print(c, end="") # PYHON
  1. for c in "PYTHON":
  2. if c == "T":
  3. break
  4. print(c, end="") # PY
  1. a = 3
  2. while a > 0:
  3. a = a - 1
  4. print(a)
  5. """
  6. 2
  7. 1
  8. 0
  9. """
  1. a = 3
  2. while a > 0:
  3. a = a + 1
  4. print(a)
  5. """
  6. 4
  7. 5
  8. ……(死循环,按下 Ctrl + C 终止程序)
  9. """
  1. s = "PYTHON"
  2. while s != "":
  3. for c in s:
  4. print(c, end="")
  5. s = s[:-1]
  6. # PYTHONPYTHOPYTHPYTPYP
  1. s = "PYTHON"
  2. while s != "":
  3. for c in s:
  4. if c == "T":
  5. break
  6. print(c, end="")
  7. s = s[:-1]
  8. # PYPYPYPYPYP
  1. for c in "PYTHON":
  2. if c == "T":
  3. continue
  4. print(c, end="")
  5. else:
  6. print("正常退出")
  7. # PYHON正常退出
  1. for c in "PYTHON":
  2. if c == "T":
  3. break
  4. print(c, end="")
  5. else:
  6. print("正常退出")
  7. # PY
  1. pi = 0
  2. N = 100
  3. for k in range(N):
  4. pi += (
  5. 1
  6. / pow(16, k)
  7. * (4 / (8 * k + 1) - 2 / (8 * k + 4) - 1 / (8 * k + 5) - 1 / (8 * k + 6))
  8. )
  9. print("圆周率值是: {}".format(pi)) # 圆周率值是: 3.141592653589793
  1. from random import random
  2. from time import perf_counter
  3. DARTS = 1000 * 1000
  4. hits = 0.0
  5. start = perf_counter()
  6. for i in range(1, DARTS + 1):
  7. x, y = random(), random()
  8. dist = pow(x**2 + y**2, 0.5)
  9. if dist <= 1.0:
  10. hits = hits + 1
  11. pi = 4 * (hits / DARTS)
  12. print("圆周率值是: {}".format(pi))
  13. print("运行时间是: {:.5f}s".format(perf_counter() - start))
  14. """
  15. 圆周率值是: 3.142448
  16. 运行时间是: 0.49618s
  17. """
  1. from random import random, seed
  2. DARTS = eval(input())
  3. seed(123)
  4. hits = 0.0
  5. for i in range(DARTS):
  6. x, y = random(), random()
  7. dist = pow(x**2 + y**2, 0.5)
  8. if dist <= 1.0:
  9. hits = hits + 1
  10. pi = 4 * (hits / DARTS)
  11. print("{:.6f}".format(pi))
  12. """
  13. 1024
  14. 3.218750
  15. """
  1. s = 0
  2. count = 1
  3. while count <= 966:
  4. if count % 2 == 0:
  5. s -= count
  6. else:
  7. s += count
  8. count += 1
  9. print(s) # -483
  1. s = ""
  2. for i in range(100, 1000):
  3. t = str(i)
  4. if pow(eval(t[0]), 3) + pow(eval(t[1]), 3) + pow(eval(t[2]), 3) == i:
  5. s += "{},".format(i)
  6. print(s[:-1])
  7. # 153,370,371,407
  1. count = 0
  2. while count < 3:
  3. name = input()
  4. password = input()
  5. if name == "Kate" and password == "666666":
  6. print("登录成功!")
  7. break
  8. else:
  9. count += 1
  10. if count == 3:
  11. print("3次用户名或者密码均有误!退出程序。")
  12. """
  13. Kate
  14. 666666
  15. 登录成功!
  16. kate
  17. 123
  18. alice
  19. 456
  20. john
  21. 111111
  22. 3次用户名或者密码均有误!退出程序。
  23. """
  1. count = 0
  2. while count < 3:
  3. name = input()
  4. password = input()
  5. if name == "Kate" and password == "666666":
  6. print("登录成功!")
  7. break
  8. else:
  9. count += 1
  10. print("用户名或密码错误")
  11. if count == 3:
  12. print("3次用户名或者密码均有误!退出程序。")
  13. """
  14. kate
  15. 123
  16. 用户名或密码错误
  17. alice
  18. 456
  19. 用户名或密码错误
  20. john
  21. 111111
  22. 用户名或密码错误
  23. 3次用户名或者密码均有误!退出程序。
  24. Kate
  25. 123
  26. 用户名或密码错误
  27. Kate
  28. 123456
  29. 用户名或密码错误
  30. Kate
  31. 666666
  32. 登录成功!
  33. """
  1. import random
  2. # 生成一个随机整数
  3. random_number = random.randint(1, 10)
  4. print(random_number) # 4
  5. # 生成一个随机浮点数
  6. random_float = random.random()
  7. print(random_float) # 0.9022500027963487
  1. import random
  2. def estimate_pi(num_points):
  3. points_in_circle = 0
  4. points_total = num_points
  5. for _ in range(num_points):
  6. x = random.uniform(0, 1)
  7. y = random.uniform(0, 1)
  8. distance = x**2 + y**2
  9. if distance <= 1:
  10. points_in_circle += 1
  11. pi_estimate = 4 * (points_in_circle / points_total)
  12. return pi_estimate
  13. num_points = 1000000
  14. pi_estimate = estimate_pi(num_points)
  15. print("Estimated value of pi:", pi_estimate)
  16. """
  17. Estimated value of pi: 3.140988
  18. Estimated value of pi: 3.142952
  19. Estimated value of pi: 3.14064
  20. """
  1. s = ""
  2. for i in range(1000, 10000):
  3. t = str(i)
  4. if (
  5. pow(eval(t[0]), 4)
  6. + pow(eval(t[1]), 4)
  7. + pow(eval(t[2]), 4)
  8. + pow(eval(t[3]), 4)
  9. == i
  10. ):
  11. print(i)
  12. """
  13. 1634
  14. 8208
  15. 9474
  16. """
  1. def is_prime(n):
  2. for i in range(2, n):
  3. if n % i == 0:
  4. return False
  5. return True
  6. sum = 0
  7. for i in range(2, 100):
  8. if is_prime(i):
  9. sum += i
  10. print(sum) # 1060

导学

课前复习

[5.1.1]--前课复习(1).mp4 (44.62MB).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)

本课概要

[5.1.2]--本课概要(1).mp4 (27MB).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)

  1. 介绍程序的控制结构:
    • 顺序结构
    • 分支结构
    • 循环结构
  2. 介绍 random 库的基本使用
  3. 通过两个实例练习来巩固所学内容

程序的分支结构

单元开篇

[5.2.1]--单元开篇(1).mp4 (13.05MB).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)

  • 单分支结构
  • 二分支结构
  • 多分支结构
  • 条件判断及组合
  • 程序的异常处理

学完本节,你将了解分支结构几乎所有的内容。

单分支结构

[5.2.2]--单分支结构(1).mp4 (22.16MB).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) image.png
image.png

  1. guess = eval(input())
  2. if (guess == 99):
  3. print("猜对了")

二分支结构

[5.2.3]--二分支结构(1).mp4 (46.84MB).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) image.png
image.png

  1. guess = eval(input())
  2. if (guess == 99):
  3. print("猜对了")
  4. else:
  5. print("猜错了")

image.png

  1. guess = eval(input())
  2. print("猜{}了".format("对" if guess == 99 else "错"))

多分支结构

[5.2.4]--多分支结构(1).mp4 (29.56MB).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) image.png
image.png

  1. score = eval(input())
  2. if score >= 90:
  3. grade = "A"
  4. elif score >= 80:
  5. grade = "B"
  6. elif score >= 70:
  7. grade = "C"
  8. elif score >= 60:
  9. grade = "D"
  10. else:
  11. grade = "E"
  12. print("输入成绩属于级别{}".format(grade))
  13. """
  14. 90
  15. 输入成绩属于级别A
  16. 80
  17. 输入成绩属于级别B
  18. 30
  19. 输入成绩属于级别E
  20. """

条件判断及组合

[5.2.5]--条件判断及组合(1).mp4 (30.9MB).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) image.png
image.png
image.png

  1. guess = eval(input())
  2. if guess > 99 or guess < 99:
  3. print("猜错了")
  4. else:
  5. print("猜对了")

程序的异常处理

[5.2.6]--程序的异常处理(1).mp4 (73.69MB).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) image.png

  1. num = eval(input("请输入一个整数: "))
  2. print(num**2)
  3. """
  4. 请输入一个整数: abc
  5. Traceback (most recent call last):
  6. File "/Users/huyouda/0/py/1.py", line 1, in <module>
  7. num = eval(input("请输入一个整数: "))
  8. File "<string>", line 1, in <module>
  9. NameError: name 'abc' is not defined
  10. """

image.png
image.png
image.png

  1. try:
  2. num = eval(input("请输入一个整数:"))
  3. print(num ** 2)
  4. except:
  5. print("输入不是整数")

image.png

  1. try:
  2. num = eval(input("请输入一个整数:"))
  3. print(num ** 2)
  4. except NameError:
  5. print("输入不是整数")

image.png

单元小结

[5.2.7]--单元小结(1).mp4 (10.04MB).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)

image.png

实例 5:身体质量指数 BMI

问题分析

[5.3.1]--身体质量指数BMI问题分析(1).mp4 (45.78MB).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) image.png
image.png
image.png
image.png

实例讲解

[5.3.2]--身体质量指数BMI实例讲解(1).mp4 (69.7MB).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) image.png

  1. height, weight = eval(input("请输入身高(米)和体重(公斤)[逗号隔开]: "))
  2. print("height", height, "weight", weight)
  3. bmi = weight / pow(height, 2)
  4. print("BMI 数值为:{:.2f}".format(bmi))
  5. who = ""
  6. if bmi < 18.5:
  7. who = "偏瘦"
  8. elif 18.5 <= bmi < 25:
  9. who = "正常"
  10. elif 25 <= bmi < 30:
  11. who = "偏胖"
  12. else:
  13. who = "肥胖"
  14. print("BMI 指标为:国际'{0}'".format(who))
  15. """
  16. 请输入身高(米)和体重(公斤)[逗号隔开]: 1.66,66
  17. height 1.66 weight 66
  18. BMI 数值为:23.95
  19. BMI 指标为:国际'正常'
  20. """
  1. height, weight = eval(input("请输入身高(米)和体重(公斤)[逗号隔开]: "))
  2. bmi = weight / pow(height, 2)
  3. print("BMI 数值为:{:.2f}".format(bmi))
  4. nat = ""
  5. if bmi < 18.5:
  6. nat = "偏瘦"
  7. elif 18.5 <= bmi < 24:
  8. nat = "正常"
  9. elif 24 <= bmi < 28:
  10. nat = "偏胖"
  11. else:
  12. nat = "肥胖"
  13. print("BMI 指标为:国内'{0}'".format(nat))
  14. """
  15. 请输入身高(米)和体重(公斤)[逗号隔开]: 1.66,66
  16. BMI 数值为:23.95
  17. BMI 指标为:国内'正常'
  18. """
  1. height, weight = eval(input("请输入身高(米)和体重(公斤)[逗号隔开]: "))
  2. bmi = weight / pow(height, 2)
  3. print("BMI 数值为:{:.2f}".format(bmi))
  4. who, nat = "", ""
  5. if bmi < 18.5:
  6. who, nat = "偏瘦", "偏瘦"
  7. elif 18.5 <= bmi < 24:
  8. who, nat = "正常", "正常"
  9. elif 24 <= bmi < 25:
  10. who, nat = "正常", "偏胖"
  11. elif 25 <= bmi < 28:
  12. who, nat = "偏胖", "偏胖"
  13. elif 28 <= bmi < 30:
  14. who, nat = "偏胖", "肥胖"
  15. else:
  16. who, nat = "肥胖", "肥胖"
  17. print("BMI 指标为:国际'{0}', 国内'{1}'".format(who, nat))
  18. """
  19. 请输入身高(米)和体重(公斤)[逗号隔开]: 1.66,66
  20. BMI 数值为:23.95
  21. BMI 指标为:国际'正常', 国内'正常'
  22. """

举一反三

[5.3.3]--身体质量指数BMI举一反三(1).mp4 (23.99MB).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) image.png

程序的循环结构

单元开篇

[5.4.1]--单元开篇(1).mp4 (11.85MB).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

[5.4.2]--遍历循环(1).mp4 (146.4MB).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 构成的循环结构

image.png
image.png

遍历循环的应用:

  • 计数循环(N次)
  • 计数循环(特定次)
  • 字符串遍历循环
  • 列表遍历循环
  • 文件遍历循环
  • ……

image.png

  1. for i in range(5):
  2. print(i)
  3. """
  4. 0
  5. 1
  6. 2
  7. 3
  8. 4
  9. """
  1. for i in range(5):
  2. print("Hello:", i)
  3. """
  4. Hello: 0
  5. Hello: 1
  6. Hello: 2
  7. Hello: 3
  8. Hello: 4
  9. """

image.png

  1. for i in range(1, 6):
  2. print(i)
  3. """
  4. 1
  5. 2
  6. 3
  7. 4
  8. 5
  9. """
  1. for i in range(1, 6, 2):
  2. print("Hello:", i)
  3. """
  4. Hello: 1
  5. Hello: 3
  6. Hello: 5
  7. """

image.png

  1. for c in "Python123":
  2. print(c, end=",")
  3. # P,y,t,h,o,n,1,2,3,

image.png

  1. for item in [123, "PY", 456]:
  2. print(item, end=",")
  3. # 123,PY,456,

image.png
image.png

image.png

无限循环 while

[5.4.3]--无限循环(1).mp4 (28.9MB).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) image.png

  1. a = 3
  2. while a > 0:
  3. a = a - 1
  4. print(a)
  5. """
  6. 2
  7. 1
  8. 0
  9. """
  1. a = 3
  2. while a > 0:
  3. a = a + 1
  4. print(a)
  5. """
  6. 4
  7. 5
  8. ……(死循环,按下 Ctrl + C 终止程序)
  9. """

循环控制保留字 break、continue

[5.4.4]--循环控制保留字(1).mp4 (102.72MB).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) image.png

image.png

  1. for c in "PYTHON":
  2. if c == "T":
  3. continue
  4. print(c, end="") # PYHON
  1. for c in "PYTHON":
  2. if c == "T":
  3. break
  4. print(c, end="") # PY

image.png

  1. s = "PYTHON"
  2. while s != "":
  3. for c in s:
  4. print(c, end="") # PYTHONPYTHOPYTHPYTPYP
  5. s = s[:-1]
  1. s = "PYTHON"
  2. while s != "":
  3. for c in s:
  4. if c == "T":
  5. break
  6. print(c, end="") # PYPYPYPYPYP
  7. s = s[:-1]

循环的高级用法

[5.4.5]--循环的高级用法(1).mp4 (50.99MB).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) image.png

  • 当循环没有被 break 语句退出时,执行 else 语句块
  • else 语句块作为”正常”完成循环的奖励
  • 这里 else 的用法与异常处理中 else 用法相似

image.png

  1. for c in "PYTHON":
  2. if c == "T":
  3. continue
  4. print(c, end="")
  5. else:
  6. print("正常退出")
  7. # PYHON正常退出
  1. for c in "PYTHON":
  2. if c == "T":
  3. break
  4. print(c, end="")
  5. else:
  6. print("正常退出")
  7. # PY

单元小结

[5.4.6]--单元小结(1).mp4 (19.53MB).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) image.png

模块 3:random 库的使用

random 库基本介绍

[5.5.1]--random库基本介绍(1).mp4 (33.95MB).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()

基本随机数函数

[5.5.2]--基本随机数函数(1).mp4 (68.18MB).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) 随机数种子确定了随机序列的产生
image.png

image.png

相同的种子会得到相同的随机数

通常无需手动去调用 random.seed 函数去设置随机数种子,设置种子的这个步骤在我们每次调用 random.random 时,会自动使用当前系统时间作为随机数种子帮我们调用一次 random.seed 函数。

扩展随机数函数

[5.5.3]--扩展随机数函数(1).mp4 (81.38MB).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) image.png
image.png
image.png
image.png

对于 random 库,我们需要具备以下能力:

  • 能够利用随机数种子产生”确定”伪随机数
  • 能够产生随机整数
  • 能够对序列类型进行随机操作

实例 6:圆周率的计算

问题分析

[5.6.1]--圆周率的计算问题分析(1).mp4 (44.05MB).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) 圆周率的近似计算公式

image.png

讲解

[5.6.2]--圆周率的计算实例讲解(1).mp4 (113.37MB).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)

  1. pi = 0
  2. N = 100
  3. for k in range(N):
  4. pi += (
  5. 1
  6. / pow(16, k)
  7. * (4 / (8 * k + 1) - 2 / (8 * k + 4) - 1 / (8 * k + 5) - 1 / (8 * k + 6))
  8. )
  9. print("圆周率值是: {}".format(pi)) # 圆周率值是: 3.141592653589793
  1. from random import random
  2. from time import perf_counter
  3. DARTS = 1000 * 1000
  4. hits = 0.0
  5. start = perf_counter()
  6. for i in range(1, DARTS + 1):
  7. x, y = random(), random()
  8. dist = pow(x**2 + y**2, 0.5)
  9. if dist <= 1.0:
  10. hits = hits + 1
  11. pi = 4 * (hits / DARTS)
  12. print("圆周率值是: {}".format(pi))
  13. print("运行时间是: {:.5f}s".format(perf_counter() - start))
  14. """
  15. 圆周率值是: 3.142448
  16. 运行时间是: 0.49618s
  17. """

举一反三

[5.6.3]--圆周率的计算举一反三(1).mp4 (79.23MB).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) image.png
image.png

程序运行时间分析

  • 使用time库的计时方法获得程序运行时间
  • 改变撒点数量,理解程序运行时间的分布
  • 初步掌握简单的程序性能分析方法

有科学家做过统计,一个程序运行的大部分(≈ 80%)时间,耗费在(≈ 10%)的代码(循环代码)上。
我们在看待一个程序性能时,需要重点关注程序的循环部分。
比如:如果我们编写的程序执行耗时比较长,此时可优先关注循环部分,使用 time 库来测量一下从进入循环到离开循环所消耗的时间。

练习

单选题

image.png

image.png

image.png

  1. k = 10000
  2. counter = 0
  3. while k > 1:
  4. counter += 1
  5. print(counter, '\t', k)
  6. k = k / 2
  7. """
  8. 1 10000
  9. 2 5000.0
  10. 3 2500.0
  11. 4 1250.0
  12. 5 625.0
  13. 6 312.5
  14. 7 156.25
  15. 8 78.125
  16. 9 39.0625
  17. 10 19.53125
  18. 11 9.765625
  19. 12 4.8828125
  20. 13 2.44140625
  21. 14 1.220703125
  22. """

image.png

image.png

image.png

image.png

image.png

  1. for s in "PYTHON":
  2. if s == "T":
  3. continue
  4. print(s, end="")
  5. # PYHON

image.png

image.png

四位玫瑰数

image.png

  1. s = ""
  2. for i in range(1000, 10000):
  3. t = str(i)
  4. if (
  5. pow(eval(t[0]), 4)
  6. + pow(eval(t[1]), 4)
  7. + pow(eval(t[2]), 4)
  8. + pow(eval(t[3]), 4)
  9. == i
  10. ):
  11. print(i)
  12. """
  13. 1634
  14. 8208
  15. 9474
  16. """

100 以内素数之和

image.png

  1. def is_prime(n):
  2. for i in range(2, n):
  3. if n % i == 0:
  4. return False
  5. return True
  6. sum = 0
  7. for i in range(2, 100):
  8. if is_prime(i):
  9. sum += i
  10. print(sum) # 1060

实例 5:身体质量指数 BMI

image.png

  1. height, weight = eval(input())
  2. bmi = weight / pow(height, 2)
  3. print("BMI数值为:{:.2f}".format(bmi))
  4. who, nat = "", ""
  5. if bmi < 18.5:
  6. who, nat = "偏瘦", "偏瘦"
  7. elif 18.5 <= bmi < 24:
  8. who, nat = "正常", "正常"
  9. elif 24 <= bmi < 25:
  10. who, nat = "正常", "偏胖"
  11. elif 25 <= bmi < 28:
  12. who, nat = "偏胖", "偏胖"
  13. elif 28 <= bmi < 30:
  14. who, nat = "偏胖", "肥胖"
  15. else:
  16. who, nat = "肥胖", "肥胖"
  17. print("BMI指标为:国际'{0}',国内'{1}'".format(who, nat))
  18. """
  19. 1.68,41
  20. BMI数值为:14.53
  21. BMI指标为:国际'偏瘦',国内'偏瘦'
  22. 1.72,80
  23. BMI数值为:27.04
  24. BMI指标为:国际'偏胖',国内'偏胖'
  25. 1.66,66
  26. BMI数值为:23.95
  27. BMI指标为:国际'正常',国内'正常'
  28. """

这是本课程的实例5
(1) 多分支条件之间的覆盖是重要问题;
(2) BMI分类:
image.png

实例 6:圆周率的计算

image.png

  1. from random import random, seed
  2. DARTS = eval(input())
  3. seed(123)
  4. hits = 0.0
  5. for i in range(DARTS):
  6. x, y = random(), random()
  7. dist = pow(x**2 + y**2, 0.5)
  8. if dist <= 1.0:
  9. hits = hits + 1
  10. pi = 4 * (hits / DARTS)
  11. print("{:.6f}".format(pi))
  12. """
  13. 1024
  14. 3.218750
  15. """

这是本课程的实例6,请注意:from...import 引入具体的函数,使用 seed() 需要提前引入

整数的加减和

image.png

  1. s = 0
  2. count = 1
  3. while count <= 966:
  4. if count % 2 == 0:
  5. s -= count
  6. else:
  7. s += count
  8. count += 1
  9. print(s) # -483

这个题应该没什么可解释的。

三位水仙花数

image.png

  1. s = ""
  2. for i in range(100, 1000):
  3. t = str(i)
  4. if pow(eval(t[0]), 3) + pow(eval(t[1]), 3) + pow(eval(t[2]), 3) == i:
  5. s += "{},".format(i)
  6. print(s[:-1])
  7. # 153,370,371,407

这里采用了 s[:-1] 方式不输出最后一个逗号。也可以把所有结果放到一个列表中,采用字符串的 .join() 方法输出结果。

用户登录的三次机会

image.png

  1. count = 0
  2. while count < 3:
  3. name = input()
  4. password = input()
  5. if name == "Kate" and password == "666666":
  6. print("登录成功!")
  7. break
  8. else:
  9. count += 1
  10. if count == 3:
  11. print("3次用户名或者密码均有误!退出程序。")
  12. """
  13. Kate
  14. 666666
  15. 登录成功!
  16. kate
  17. 123
  18. alice
  19. 456
  20. john
  21. 111111
  22. 3次用户名或者密码均有误!退出程序。
  23. """

这里是参考答案,运用 while 进行非确定次数循环。

按照题目要求的示例来实现程序,在交互上会感觉很别扭,因为输入失败后并没有给予错误提示。

  1. count = 0
  2. while count < 3:
  3. name = input()
  4. password = input()
  5. if name == "Kate" and password == "666666":
  6. print("登录成功!")
  7. break
  8. else:
  9. count += 1
  10. print("用户名或密码错误")
  11. if count == 3:
  12. print("3次用户名或者密码均有误!退出程序。")
  13. """
  14. kate
  15. 123
  16. 用户名或密码错误
  17. alice
  18. 456
  19. 用户名或密码错误
  20. john
  21. 111111
  22. 用户名或密码错误
  23. 3次用户名或者密码均有误!退出程序。
  24. Kate
  25. 123
  26. 用户名或密码错误
  27. Kate
  28. 123456
  29. 用户名或密码错误
  30. Kate
  31. 666666
  32. 登录成功!
  33. """

补充

资深程序员如何看待编程工具?

image.png

梅森旋转算法

梅森旋转算法(Mersenne Twister Algorithm)是一种广泛应用的随机数生成算法。它由松本真(Makoto Matsumoto)和西村拓士(Takuji Nishimura)于1997年开发,被认为是目前最常用的伪随机数生成算法之一。

梅森旋转算法的特点包括:

  1. 高周期性:该算法使用一个很大的状态空间(219937-1),能够产生非常长的周期,约为219937-1个随机数序列。这意味着在很长一段时间内生成的随机数序列不会重复。
  2. 高质量的随机数:梅森旋转算法生成的随机数具有较好的统计特性,可以满足大多数应用的随机性需求。
  3. 快速性能:梅森旋转算法的计算速度相对较快,适用于大量的随机数生成需求。

在Python中,标准库的random模块使用的随机数生成器就是基于梅森旋转算法的。你可以使用random模块来生成随机数,例如:

  1. import random
  2. # 生成一个随机整数
  3. random_number = random.randint(1, 10)
  4. print(random_number)
  5. # 生成一个随机浮点数
  6. random_float = random.random()
  7. print(random_float)

除了random模块,还有一些第三方库也提供了更高级和更灵活的梅森旋转算法实现,例如numpy库中的numpy.random模块,可以生成更多类型的随机数。

总而言之,梅森旋转算法是一种可靠、高质量且高性能的随机数生成算法,适用于许多应用领域,包括模拟、密码学、游戏开发等

学不会编程怎么办?

image.png

虽然是打鸡血,不过说得确实有道理……

蒙特卡罗方法

蒙特卡罗方法(Monte Carlo Method)是一种基于随机抽样和统计推断的计算方法。它以概率统计理论为基础,通过生成大量的随机样本来近似计算问题的解

蒙特卡罗方法常用于解决无法通过解析方法求解的复杂问题,特别是涉及概率、统计和数值计算的领域。它的基本思想是通过随机抽样和大数定律,通过大量的重复试验得到问题的近似解。

蒙特卡罗方法的应用领域非常广泛,包括但不限于以下几个方面:

  1. 数值计算:蒙特卡罗方法可以用来计算复杂的数学积分、求解微分方程、模拟随机过程等。通过生成大量的随机样本,并根据这些样本的统计特性进行数值计算。
  2. 金融领域:蒙特卡罗方法在金融工程中被广泛应用,用于模拟股票价格、利率变动、期权定价等问题。通过随机模拟大量的市场情景,评估金融产品的风险和收益。
  3. 物理模拟:蒙特卡罗方法在物理学研究中也有重要应用,如粒子物理学中的事件生成、核反应的模拟等。通过生成随机粒子的运动轨迹,模拟物理系统的行为。
  4. 统计推断:蒙特卡罗方法可以用于参数估计、假设检验、置信区间等统计推断问题。通过生成大量的随机样本,进行统计推断,得到对问题的近似解。

蒙特卡罗方法的基本步骤包括:

  1. 定义问题:明确要解决的问题和需要计算的量。
  2. 设定模型:选择合适的数学模型或概率模型来描述问题。
  3. 随机抽样:通过随机数生成器生成大量的随机样本。
  4. 计算量的统计特性:根据抽样的结果,计算所关注的量的统计特性,如平均值、方差等。
  5. 结果评估:通过对统计特性进行分析和解释,得到问题的近似解或概率分布。

总而言之,蒙特卡罗方法是一种基于随机抽样和统计推断的计算方法,适用于解决各种复杂问题。它的优势在于可以处理高维、非线性和难以求解的问题,并且具有较好的数值稳定性和可扩展性

以下是蒙特卡罗方法用于估算圆周率 π 的原理:

  1. 在一个边长为 L 的正方形内部,画一个半径为 R 的圆,使其完全内切于正方形。这意味着正方形的边界与圆的周界相切。
  2. 根据几何关系,该圆的面积为 A = πR^2,正方形的面积为 A_square = L^2。
  3. 假设我们随机均匀地在该正方形内生成足够多的点。
  4. 统计落在圆内的点的数量,假设为 N_circle。
  5. 统计总共生成的点的数量,假设为 N_total。
  6. 根据几何关系,圆的面积与正方形的面积之比为 A/A_square = πR^2 / L^2。同样,落在圆内的点的数量与总点数之比也近似等于这个比值,即 N_circle / N_total ≈ A / A_square。
  7. 根据步骤 6 中的比值,我们可以得到一个近似的 π 的估计值:π ≈ 4 * (N_circle / N_total)。

蒙特卡罗方法利用大量的随机点的统计性质来估算圆的面积与正方形的面积之比,从而估算出圆周率 π 的值。通过增加生成的随机点数量,可以提高估算的准确性。

需要注意的是,蒙特卡罗方法是一种概率性方法,估算的结果会受到随机抽样的影响。为了得到更准确的估计,通常需要生成足够多的随机点。

下面是一个使用蒙特卡罗方法估算圆周率的简单示例代码:

  1. import random
  2. def estimate_pi(num_points):
  3. points_in_circle = 0
  4. points_total = num_points
  5. for _ in range(num_points):
  6. x = random.uniform(0, 1)
  7. y = random.uniform(0, 1)
  8. distance = x**2 + y**2
  9. if distance <= 1:
  10. points_in_circle += 1
  11. pi_estimate = 4 * (points_in_circle / points_total)
  12. return pi_estimate
  13. num_points = 1000000
  14. pi_estimate = estimate_pi(num_points)
  15. print("Estimated value of pi:", pi_estimate)

这个代码通过生成一百万个随机点,并统计落在单位正方形内的落在单位圆内的点的数量,从而估算圆周率的值。