本文展示一個互動式命令列數學遊戲:隨機產生加減法題目、限制嘗試次數、錯誤重試、答案揭曉、持續遊玩循環,適合初學者練習 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、非數字輸入,體驗佳。tkinter)、Web 版本 (Flask + htmx)。