当前位置:   article > 正文

Python 语言程序设计基础(第二版)嵩天 高等教育出版社——第四章答案_python语言程序设计基础第二版答案

python语言程序设计基础第二版答案

所有答案皆为本人自行编写,不涉及版权问题!!

4.1

  1. from random import randint
  2. x = randint(0,9)
  3. print("猜数游戏,请输入0到9之间的整数".center(20,'*'))
  4. n = eval(input("请输入:"))
  5. i= 1
  6. while n != x:
  7. if n > x:
  8. print("太大了!")
  9. elif n < x:
  10. print("太小了!")
  11. n = eval(input("请输入:"))
  12. i += 1
  13. print("预测{}次,你猜中了!".format(i))

4.2

  1. print("统计各个类型的字符数量".center(20,'*'))
  2. Str = input("请输入一串字符:")
  3. char, number, space, other = 0,0,0,0
  4. for i in Str:
  5. if 'a' <= i <= 'z' or 'A' <= i <= 'Z':
  6. char += 1
  7. elif '0' <= i <= '9':
  8. number += 1
  9. elif i == ' ':
  10. space += 1
  11. else:
  12. other += 1
  13. print("有{}个英文字母,{}个数字,{}个空格,{}个其他字符。".format(char, number, space, other))

4.3

  1. num1, num2 = eval(input("请输入两个整数,用逗号隔开:"))
  2. max = 1
  3. min = 1
  4. i = 1
  5. # 储存输入的值,以便后续使用
  6. a, b = num1, num2
  7. while i <= num1 if num1<=num2 else num2:
  8. if num1%i == 0 and num2%i == 0:
  9. max *= i
  10. num1, num2 = num1/i, num2/i
  11. # 把i充值为1
  12. i = 1
  13. i += 1
  14. min = a*b/max
  15. print("最大公约数为{},最小公倍数为{}".format(max,min))

4.4

  1. from random import randint
  2. x = randint(0,100)
  3. print("猜数游戏,请输入0到100之间的整数".center(20,'*'))
  4. n = eval(input("请输入:"))
  5. i= 1
  6. while n != x:
  7. if n > x:
  8. print("太大了!")
  9. elif n < x:
  10. print("太小了!")
  11. n = eval(input("请输入:"))
  12. i += 1
  13. print("预测{}次,你猜中了!".format(i))

4.6

  1. from random import *
  2. times = 1000000
  3. NoChangeRight = 0
  4. ChangeRight = 0
  5. for i in range(times):
  6. # 设置1号和2号门后面是山羊
  7. hit = randint(1,3)
  8. if hit in [1,2]:
  9. NoChangeRight += 1
  10. # 改变时,需选择一个与之前不同的门
  11. ReHit = randint(1,3)
  12. while ReHit == hit:
  13. ReHit = randint(1,3)
  14. if ReHit in [1,2]:
  15. ChangeRight += 1
  16. NoChange = NoChangeRight/times
  17. Change = ChangeRight/times
  18. print("不改变的获胜几率为{},反之为{}".format(NoChange, Change))

4.7

  1. from random import randint
  2. x = randint(0,9)
  3. print("猜数游戏,请输入0到9之间的整数".center(20,'*'))
  4. # 获取正确的数字
  5. while True:
  6. try:
  7. n = eval(input("请输入:"))
  8. except:
  9. print("错误,必须输入一个整数!")
  10. else:
  11. break
  12. i= 1
  13. while n != x:
  14. if n > x:
  15. print("太大了!")
  16. elif n < x:
  17. print("太小了!")
  18. # 获取正确的数字
  19. while True:
  20. try:
  21. n = eval(input("请输入:"))
  22. except:
  23. print("错误,必须输入一个整数!")
  24. else:
  25. break
  26. i += 1
  27. print("预测{}次,你猜中了!".format(i))
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/402535
推荐阅读
相关标签
  

闽ICP备14008679号