一个合格的脚本,至少含有如下部分:

1,文件名注释

2,doc字段

3,主函数

4,异常处理

5,main()

 

这个脚本要实现的功能:

练习1-10内数字的加减法

代码段:

 1 #!/usr/bin/env python3
 2 #-*- coding:utf-8 -*-
 3 #filename = “算数游戏.py”
 4 
 5 '''1到10之间的加减法计算'''
 6 
 7 from operator import add, sub
 8 from random import randint,choice
 9 
10 ops ={
11     '+':add,
12     '-':sub
13 }
14 
15 MAXTRIES = 2
16 
17 def doprob():
18     op = choice('+-')
19     nums = [randint(1,10) for i in range(2)]
20     nums.reverse()
21     ans=ops[op](*nums)
22     print("%d %s %d " %(nums[0],op,nums[1]))
23     Tries = 0
24 
25     while True:
26             try:
27                 your_answer = int((input("Enter your answer\n >#")))
28                 if your_answer == ans:
29                     print("Correct")
30                     break
31                 if Tries == MAXTRIES:
32                     print("answer is %d" %(ans))
33                     break
34                 else:
35                     print("incorrect, Please Try again:")
36                     Tries += 1
37             except (TypeError,EOFError,ValueError,KeyboardInterrupt):
38                 print("Invalid input")
39 
40 
41 def main():
42     while True:
43         doprob()
44         try:
45             opt = input("Again?[Y/N) # ").lower()
46             if opt == 'n':
47                 break
48         except (KeyboardInterrupt,EOFError):
49             break
50 
51 if __name__ == '__main__':
52     main()

 

使用到的模块:

random

operator

 

相关文章:

  • 2022-01-04
  • 2021-11-01
  • 2021-11-07
  • 2021-07-14
  • 2021-11-16
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-10-31
  • 2022-12-23
  • 2021-12-23
  • 2022-12-23
  • 2021-09-22
  • 2021-09-07
  • 2022-12-23
相关资源
相似解决方案