zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    OilPaint(转载/实验)
    UE4 3D artist
    render pipeline about (翻译)
    Python 相对导入 碎碎念
    USF, USH Grammar
    JZ19 顺时针打印矩阵
    JZ49 把字符串转换成整数
    JZ45 扑克牌顺子
    JZ53 表示数值的字符串
    JZ48 不用加减乘除做加法
  • 原文地址:https://www.cnblogs.com/hejianping/p/10969468.html
Copyright © 2011-2022 走看看