1. 程式人生 > >python 實現兒童算術遊戲

python 實現兒童算術遊戲

多少 err 答案 相關 inter for 用戶 選擇 ror

隨機選擇數字以及一個算術函數, 顯示問題, 以及驗證結果. 在 3 次錯誤的嘗試以後給出結果,等到用戶輸入一個正確的答案後便會繼續運行.

# -*- coding: UTF-8 -*-
from operator import add, sub                 #從 operator 和 random 模塊中,導入我們會用到的函數       
from random import randint, choice

ops = {'+': add, '-': sub}                    #定義全局變量 一個包含了運算符和與其相關聯的函數的集合(字典)
maxtaries = 3                                 #定義全局變量 用戶有多少次機會嘗試給出答案的整型變量

def doprob():                                    #定義此程序的核心程序
    op = choice('+-')                            #隨機選擇一個操作
    nums = [randint(1, 10) for i in range(2)]    #隨機生成兩個操作數
    nums.sort(reverse=True)                      #為了避免減法問題中的負數問題,將這兩個操作數按大到下進行排序
    ans = ops[op](*nums)                         #調用一個數學函數計算出正確的解
    pr = '%d %s %d =' % (nums[0], op, nums[1])   #生成 提示用戶計算的等式
    oops = 1                                     #定義 用戶嘗試機會的計數器
    while True:
        try:
            if int(raw_input(pr)) == ans:        #判斷 用戶輸入的答案和 正確答案比較
                print 'correct'                  #輸出提示信息
                break                            #退出循環
            if oops == maxtaries:                #當用戶嘗試次數等於用戶最大嘗試次數時
                print 'answer\n%s%d'%(pr,ans)    #將等式和 正確的答案輸出
                break 
            else:                                #在其他情況下
                print 'incorrect... try again'   #輸出提示信息
                oops += 1                        #用戶嘗試機會的計數器加一
        except(KeyboardInterrupt, EOFError, ValueError):        #捕捉用戶的錯誤輸出
            print 'invalid input... try again'   #輸出提示信息


def main():
    while True:
        doprob()                               #調用核心函數
        try:
            opt = raw_input('Again?[y]').lower()    #讀取用戶輸入的參數 如果是大寫字母時變為小寫
            if opt and opt[0] == 'n':               #當用戶輸入n 或 N 退出用戶循環
                break
        except(KeyboardInterrupt, EOFError):
            break


if __name__ == '__main__':
    main()


python 實現兒童算術遊戲