1. 程式人生 > >一個 加減法!小遊戲

一個 加減法!小遊戲

from operator import add, sub
from random import randint, choice

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

def doprod():
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 = 0
while True:
try:
if int(input(pr)) == ans:
print('correct')
break
if oops == MAXTRLIES: # 計數器到時,給出值。並讓使用者輸入
print('answer\n%s%f' % (pr, ans))
else:
print('incorrect... tey again') # 輸入的值不符合條件,計數器+1
oops += 1
except (EOFError, KeyboardInterrupt, ValueError, KeyError): # 用來保證不會因為使用者的輸入而導致程式報錯。error
print('invalid input... try again')

def main():
while True: # 迴圈執行 doprod 函式。
doprod()
try:
opt = input('again? [y]').lower() # 當 doprod 函式執行完成。詢問是否繼續
if opt and opt[0] == 'n':
break
except (KeyboardInterrupt, EOFError): # 控制使用者的錯誤輸入。
break


if __name__ == '__main__':
main()