萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 簡易四則運算遊戲實作

本文展示一個互動式命令列數學遊戲:隨機產生加減法題目、限制嘗試次數、錯誤重試、答案揭曉、持續遊玩循環,適合初學者練習 random、operator、迴圈與例外處理。

完整程式碼

#!/usr/bin/env python
from operator import add, sub
from random import randint, choice

ops = {'+': add, '-': sub}
MAXTRIES = 2

def doprob():
    op = choice('+-')
    nums = [randint(1, 10) for _ in range(2)]
    nums.sort(reverse=True)  # 大數在前,避免負數結果
    ans = ops[op](*nums)
    prompt = f'{nums[0]} {op} {nums[1]} = '

    tries = 0
    while True:
        try:
            if int(input(prompt)) == ans:
                print('correct')
                break
            if tries == MAXTRIES:
                print(f'answer: {prompt}{ans}')
                break
            print('incorrect... try again')
            tries += 1
        except (KeyboardInterrupt, EOFError, ValueError):
            print('invalid input... try again')

def main():
    while True:
        doprob()
        try:
            opt = input('Again? [y]').lower()
            if opt and opt[0] == 'n':
                break
        except (KeyboardInterrupt, EOFError):
            break

if __name__ == '__main__':
    main()

執行範例

8 - 1 = 7
correct
Again? [y]y
7 - 1 = 6
correct
Again? [y]y
9 + 4 = 0
incorrect... try again
9 + 4 = 13
correct
Again? [y]n

教學重點

  • operator.add/sub:將運算子作為一級物件存入字典,避免 eval 風險。
  • choice('+-'):從字串序列隨機挑選字元。
  • randint(1,10):包含端點的隨機整數。
  • sort(reverse=True):保證減法不產生負數,符合國小數學範疇。
  • 例外處理涵蓋 Ctrl+C、Ctrl+D、非數字輸入,體驗佳。

擴充想法

  • 加入乘除法、括號、多位數。
  • 計分系統、排行榜 (存檔)。
  • GUI 版本 (tkinter)、Web 版本 (Flask + htmx)。
copyright © 萬盛學電腦網 all rights reserved