Python编写两个数的加减法游戏

目标:

  1.实现两个数的加减法

  2.回答者3次输错计算结果后,输出正确结果,并询问回答者是否继续

 

1.使用常规函数实现两个数的加减法游戏

代码如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

'''使用常规函数编写出题游戏'''

import random

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

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

def chuti():
    cmds = {'+': add, '-': sub}
    ops = '+-'
    op = random.choice(ops)
    nums = [random.randint(1,50) for i in xrange(2)]
    nums.sort(reverse=True)
    prompt = '%s %s %s = ' %(nums[0], op, nums[1])
    anwser = cmds[op](*nums)

    counter = 0 
    while counter < 3:
        try:
            result = int(raw_input(prompt))
        except:
            continue
        if anwser == result:
            print "回答正确"
            print "-" * 20 
            break
        else:
            counter += 1
            print "回答错误"
            print "-" * 20
    else:
        print "正确答案是: %s %s" % (prompt, anwser)


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

•运行代码,测试效果

[root@localhost python]# python new_mathgame.py
27 + 25 = 5
回答错误
--------------------
27 + 25 = 2
回答错误
--------------------
27 + 25 = 3
回答错误
--------------------
正确答案是: 27 + 25 =  52
Continue(y/n?)y
15 - 1 = 12
回答错误
--------------------
15 - 1 = 13
回答错误
--------------------
15 - 1 = 14
回答正确
--------------------
Continue(y/n?)n
结束

 

2.使用lambda匿名函数实现两位数的加减法游戏

代码如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

'''使用匿名函数lambda编写出题游戏'''

import random

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

# def sub(x,y):
#    return x - y
def chuti():
    cmds = {'+': lambda x, y: x + y, '-': lambda x, y: x - y}
    ops = '+-'
    op = random.choice(ops)
    nums = [random.randint(1,50) for i in xrange(2)]
    nums.sort(reverse=True)
    prompt = '%s %s %s = ' %(nums[0], op, nums[1])
    anwser = cmds[op](*nums)

    counter = 0 
    while counter < 3:
        try:
            result = int(raw_input(prompt))
        except:
            continue
        if anwser == result:
            print "回答正确"
            print "-" * 20 
            break
        else:
            counter += 1
            print "回答错误"
            print "-" * 20
    else:
        print "正确答案是: %s %s" % (prompt, anwser)


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

 

posted @ 2017-01-09 10:39  xkops  阅读(5715)  评论(0编辑  收藏  举报