python 實現兒童算術遊戲

來源:互聯網
上載者:User

標籤:計算   全域變數   包含   使用者   函數   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 實現兒童算術遊戲

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.