from operator import add,sub
from random import randint,choice
#從operator、random模塊導入函數
ops={'+':add,'-':sub}
#定義字典
MAXTRIES=2
def doprob():
op=choice('+-')
#隨機選擇操作符
nums=[randint(1,10) for i in range(2)]
#隨機生成一個1-10的數字,2次。
nums.sort(reverse=True)
#將nums數組降序
ans=ops[op](*nums)
#取字典中add,sub值,而nums中的元素一次作爲參數傳給add或sub,例nums<span style="font-family: Arial, Helvetica, sans-serif;">[3,4]</span><span style="font-family: Arial, Helvetica, sans-serif;">相當於add(3,4)或sub(3,4)</span>
pr='%d %s %d='%(nums[0],op,nums[1])
oops=0
while True:
try:
if int(raw_input(pr))==ans:
print 'correct'
break
if oops==MAXTRIES:
print 'anwser\n%s%d'%(pr,ans)
else:
print 'incorrect...try again'
oops+=1
except ValueError as e:
print 'invalid input...try again '
#3次錯誤顯示正確答案
def main():
while True:
doprob()
try:
opt=raw_input('Again?[y]').lower()
if opt and opt[0]=='n':
break
except EOFError as e:
break
if __name__=='__main__':
main()
難點在於這個ans=ops[op](*nums)
的理解。~~~~by勿語星空丶