標籤:計算 全域變數 包含 使用者 函數 ror 數字 輸出 輸入
隨機播放數字以及一個算術函數, 顯示問題, 以及驗證結果. 在 3 次錯誤的嘗試以後給出結果,等到使用者輸入一個正確的答案後便會繼續運行.
# -*- coding: UTF-8 -*-from operator import add, sub #從 operator 和 random 模組中,匯入我們會用到的函數 from random import randint, choiceops = {'+': 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) #調用一個數學Function Compute出正確的解 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): breakif __name__ == '__main__': main()
python 實現兒童算術遊戲