72-使用函数编写数字游戏2

和之前的使用函数编写数字游戏一样,只是把加减法函数更换为匿名函数。

from random import randint,choice

# def add(x,y):  # 定义加函数
#     return x + y
#
# def sub(x,y):  # 定义减函数
#     return x - y

def exam():
    cmds = {'+': lambda x, y: x + y, '-': lambda x, y: x - y}  # 加减函数的字典
    nums = [randint(1,100) for i in range(2)]  # 随机取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("You are right!")
            break

        else:
            print("You are wrong!")
            tries += 1
    else:
        print("%s %s" %((prompt,result)))

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

 

posted @ 2019-06-03 19:07  hejp  阅读(260)  评论(0编辑  收藏  举报