欢迎使用CSDN-markdown编辑器

来源:互联网 发布:怎么把mac照片导入u盘 编辑:程序博客网 时间:2024/06/11 20:13

核心编程-例子 11.1 算术游戏

随机选择数字以及一个算术函数, 显示问题, 以及验证结果. 在 3 次错误的尝试以后给出结果,等到用户输入一个正确的答案后便会继续运行.:

from operator import add,sub
from random import randint,choice
ops={‘+’:add,”-“:sub}
MAXTRIES=2
def doprob():
op=choice(‘+-‘)
nums=[randint(1,10) for i in range(2)]
nums.sort(reverse=True)
ans=opsop
pr=’%d%s%d=’%(nums[0],op,nums[1])
oops=0
while True:
try:
if int(input(pr))==ans:
print (‘correct’)
break
if oops==MAXTRIES:
print(‘answer\n%s%d’%(pr,ans))
else:
print(‘incorrect….try again’)
oops+=1
except(KeyboardInterrupt,\
EOFError,ValueError):
print(‘invalid input…try again’)
def main():
while True:
doprob()
try:
opt=input(‘Again?[y]’).lower()
if opt and opt[0]==’n’:
break
#except(KeyboardInterrupt,EOFError):
except(KeyboardInterrupt,EOFError):
break
if name == ‘main‘:
main()

图:
这里写图片描述