python核心编程(第二版)-算术游戏

本文介绍了一个Python脚本,通过随机生成数学运算题目并让用户进行解答,旨在提高用户的数学运算能力和快速反应能力。脚本利用了Python的operator和random模块来实现随机选择运算符和生成数字,并通过循环和条件判断让用户参与互动。程序设有答题次数限制,若用户在限定次数内答对,则显示'correct';若超时则显示正确答案。此外,还提供了再次尝试的功能,让用户可以重复练习。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

from operator import add,sub
from random import randint,choice
#从operator、random模块导入函数
ops={'+':add,'-':sub}
#定义字典
MAXTRIES=2

def doprob():
    op=choice('+-')
#随机选择操作符
    nums=[randint(1,10) for i in range(2)]
#随机生成一个1-10的数字,2次。
    nums.sort(reverse=True)
#将nums数组降序
    ans=ops[op](*nums)
#取字典中add,sub值,而nums中的元素一次作为参数传给add或sub,例nums<span style="font-family: Arial, Helvetica, sans-serif;">[3,4]</span><span style="font-family: Arial, Helvetica, sans-serif;">相当于add(3,4)或sub(3,4)</span>
    pr='%d %s %d='%(nums[0],op,nums[1])
    oops=0
    while True:
        try:
            if int(raw_input(pr))==ans:
                print 'correct'
                break
            if oops==MAXTRIES:
                print 'anwser\n%s%d'%(pr,ans)
            else:
                print 'incorrect...try again'
                oops+=1
        except ValueError as e:
            print 'invalid input...try again '
#3次错误显示正确答案

def main():
    while True:
        doprob()
        try:
            opt=raw_input('Again?[y]').lower()
            if opt and opt[0]=='n':
                break
        except EOFError as e:
            break

if __name__=='__main__':
    main()
难点在于这个
ans=ops[op](*nums)
的理解。


~~~~by勿语星空丶

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值