python-随机加减游戏.(71)

#转自https://www.jianshu.com/c/00c61372c46a网址
#随机生成100以内的两个数字,实现随机的加减法。如果是减法,结果不能是负数。算错三次,给出正确答案
from random import randint,choice

def add(x,y):
    return x + y

def sub(x,y):
    return x - y

def exam():
    cmds = {'+':add,'-':sub}
    nums = [randint(1,100) for i in range(2)]   #循环两次,每次从1-100选两个数
    nums.sort(reverse=True) #sort(),排序,reverse=True,反转,最后列表是降序排列
    op = choice('+-')
    result = cmds[op](*nums)    #(*nums),将列表转换成元组,[op],['+']或['-'],cmds[op],字典cmds内[op]对应的值,即add或sub
    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('Very good!')
            break
        else:
            print('Wrong answer')
            tries +=1
    else:   #while的else,全算错才给答案,答对了就不给出答案
        print('%s%s' % (prompt,result))

if __name__ == '__main__':
    while True:
        exam()
        try:    #异常处理
            yn = input("Continue(y/n)?").strip()[0] #去除所有空格,取第一个字符
        except ImportError:
            continue
        except (KeyboardInterrupt,EOFError):
            print()
            yn = 'n'

        if yn in 'Nn':
            break

 

#或

#转自https://www.jianshu.com/c/00c61372c46a网址

from random import randint,choice

def exam():
    cmds = {'+':lambda x,y:x + y,'-':lambda x,y:x - y}  #lambda,匿名函数
    nums = [randint(1,100) for i in range(2)]
    nums.sort(reverse=True)
    op = choice('+-')
    result = cmds[op](*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('Very good!')
            break
        else:
            print('Wrong answer.')
            tries +=1
    else:
        print('%s%s' % (prompt,result))

if __name__ == '__main__':
    while True:
        exam()
        try:
            yn = input("Continue(y/n)?").strip()[0]
        except ImportError:
            continue
        except (KeyboardInterrupt,EOFError):
            print()
            yn = 'n'

        if yn in 'nN':
            break

 

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值