1 案例1:简单的加减法数学游戏
1.1 问题
编写math_game.py脚本,实现以下目标:
随机生成两个100以内的数字
随机选择加法或是减法
总是使用大的数字减去小的数字
如果用户答错三次,程序给出正确答案
- 1
- 2
- 3
- 4
1.2 方案
创建4个函数,分别实现返回两数之和、返回两数之差、判断表达式正确性、是否继续计算四种方法:
1.首先调用main()函数(是否继续计算功能),main函数利用循环无限次调用exam()函数进行计算,计算结束,用户选择是否继续(此过程利用try语句捕获索引错误、ctrl+c(中断)错误、ctrl+d错误),如果选择n即结束循环,不再调用exam()函数,否则循环继续
2.调用exam()函数:
a)输出运算公式:利用列表切片将随机生成的两个数打印(这两个数利用random模块及列表生成式随机生成,并利用sort()方法进行降序排序,确保相减时一直是大的数字减小的数字),利用random模块随机生成“+”“-”号,输出在两数之间
b)用户输入值,利用for循环进行三次判断,如果运算公式结果与用户输入值相同,循环结束,系统输出“你赢了”,exam()函数执行结束,否则系统输出“你答错了”,循环继续,3次都回答错误,利用循环的else分支输出运算公式及结果
c)上诉运算公式结果:利用random模块随机生成“+”“-”值对关系调用(其中“+”“-”号作为字典键,返回和函数add()及返回差函数sub()作为值,调用时将随机生成的两个数字作为参数传递给add()函数及sub()函数)
1.3 步骤
实现此案例需要按照如下步骤进行。
步骤一:编写脚本
[root@localhost day06]# vim math_game.py
#!/usr/bin/env python3
import random
def add(x, y):
return x + y
def sub(x, y):
return x - y
def exam():
cmds = {'+': add, '-': sub} # 将函数存入字典
nums = [random.randint(1, 100) for i in range(2)] # 生成两个数
nums.sort(reverse=True) # 降序排列
op = random.choice('+-')
result = cmds[op](*nums) # 调用存入字典的函数,把nums列表拆开,作为参数传入
prompt = "%s %s %s = " % (nums[0], op, nums[1])
for i in range(3):
try:
answer = int(input(prompt))
except:
continue
if answer == result:
print('你真棒,答对了!')
break # 答对了就不要再回答了,结束循环
else:
print('答错了')
else:
print("%s%s" % (prompt, result)) # 只有循环不被break才执行
def main():
while True:
exam()
try:
go_on = input('Continue(y/n)? ').strip()[0]
except IndexError:
continue
except (KeyboardInterrupt, EOFError):
go_on = 'n'
if go_on in 'nN':
print('\nBye-bye.')
break
if __name__ == '__main__':
main()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
实现此案例还可利用while循环:
[root@localhost day06]# vim mygui.py
#!/usr/bin/env python3
import random
def add(x, y):
return x + y
def sub(x, y):
return x - y
def exam():
cmds = {'+': add, '-': sub} # 将函数存入字典
nums = [random.randint(1, 100) for i in range(2)] # 生成两个数
nums.sort(reverse=True) # 降序排列
op = random.choice('+-')
result = cmds[op](*nums) # 调用存入字典的函数,把nums列表拆开,作为参数传入
prompt = "%s %s %s = " % (nums[0], op, nums[1])
tries = 0
while tries < 3:
try:
answer = int(input(prompt))
except:
continue
if answer == result:
print('你真棒,答对了!')
break # 答对了就不要再回答了,结束循环
else:
print('答错了')
tries += 1
else:
print("%s%s" % (prompt, result)) # 只有循环不被break才执行
def main():
while True:
exam()
try:
go_on = input('Continue(y/n)? ').strip()[0]
except IndexError:
continue
except (KeyboardInterrupt, EOFError):
go_on = 'n'
if go_on in 'nN':
print('\nBye-bye.')
break
if __name__ == '__main__':
main()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
步骤二:测试脚本执行
[root@localhost day06]# python3 math_game.py
54 + 19 =
54 + 19 =
54 + 19 = 73
你真棒,答对了!
Continue(y/n)? y
60 + 39 = 99
你真棒,答对了!
Continue(y/n)? y
18 + 15 = 33
你真棒,答对了!
Continue(y/n)? y
35 + 20 = 55
你真棒,答对了!
Continue(y/n)? y
37 + 35 = 72
你真棒,答对了!
Continue(y/n)? y
77 - 57 = 20
你真棒,答对了!
Continue(y/n)? y
35 + 23 = 5
答错了
35 + 23 = 6
答错了
35 + 23 = 7
答错了
35 + 23 = 58
Continue(y/n)? y
75 + 47 = 122
你真棒,答对了!
Continue(y/n)? ^C
Bye-bye.
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
</div>
<link href="https://csdnimg.cn/release/phoenix/mdeditor/markdown_views-60ecaf1f42.css" rel="stylesheet">
<div class="more-toolbox">
<div class="left-toolbox">
<ul class="toolbox-list">
<li class="tool-item tool-active is-like "><a href="javascript:;"><svg class="icon" aria-hidden="true">
<use xlink:href="#csdnc-thumbsup"></use>
</svg><span class="name">点赞</span>
<span class="count"></span>
</a></li>
<li class="tool-item tool-active is-collection "><a href="javascript:;" data-report-click="{"mod":"popu_824"}"><svg class="icon" aria-hidden="true">
<use xlink:href="#icon-csdnc-Collection-G"></use>
</svg><span class="name">收藏</span></a></li>
<li class="tool-item tool-active is-share"><a href="javascript:;" data-report-click="{"mod":"1582594662_002"}"><svg class="icon" aria-hidden="true">
<use xlink:href="#icon-csdnc-fenxiang"></use>
</svg>分享</a></li>
<!--打赏开始-->
<!--打赏结束-->
<li class="tool-item tool-more">
<a>
<svg t="1575545411852" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5717" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><defs><style type="text/css"></style></defs><path d="M179.176 499.222m-113.245 0a113.245 113.245 0 1 0 226.49 0 113.245 113.245 0 1 0-226.49 0Z" p-id="5718"></path><path d="M509.684 499.222m-113.245 0a113.245 113.245 0 1 0 226.49 0 113.245 113.245 0 1 0-226.49 0Z" p-id="5719"></path><path d="M846.175 499.222m-113.245 0a113.245 113.245 0 1 0 226.49 0 113.245 113.245 0 1 0-226.49 0Z" p-id="5720"></path></svg>
</a>
<ul class="more-box">
<li class="item"><a class="article-report">文章举报</a></li>
</ul>
</li>
</ul>
</div>
</div>
<div class="person-messagebox">
<div class="left-message"><a href="https://blog.csdn.net/xie_qi_chao">
<img src="https://profile.csdnimg.cn/B/F/6/3_xie_qi_chao" class="avatar_pic" username="xie_qi_chao">
<img src="https://g.csdnimg.cn/static/user-reg-year/1x/2.png" class="user-years">
</a></div>
<div class="middle-message">
<div class="title"><span class="tit"><a href="https://blog.csdn.net/xie_qi_chao" data-report-click="{"mod":"popu_379"}" target="_blank">解启超</a></span>
</div>
<div class="text"><span>发布了404 篇原创文章</span> · <span>获赞 56</span> · <span>访问量 4万+</span></div>
</div>
<div class="right-message">
<a href="https://im.csdn.net/im/main.html?userName=xie_qi_chao" target="_blank" class="btn btn-sm btn-red-hollow bt-button personal-letter">私信
</a>
<a class="btn btn-sm attented bt-button personal-watch" data-report-click="{"mod":"popu_379"}">已关注</a>
</div>
</div>
</div>
</article>