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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM