核心编程-例子 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()
图:
本博客介绍了一个简单的算术游戏程序实现。程序通过随机选择两个数字和一个运算符(加法或减法),向用户提问并验证答案。若用户连续三次输入错误答案,则显示正确答案。该程序使用了Python的random和operator模块。
5088

被折叠的 条评论
为什么被折叠?



