1. 程式人生 > >python-隨機加減遊戲.(71)

python-隨機加減遊戲.(71)

#轉自https://www.jianshu.com/c/00c61372c46a網址
#隨機生成100以內的兩個數字,實現隨機的加減法。如果是減法,結果不能是負數。算錯三次,給出正確答案
from random import randint,choice

def add(x,y):
    return x + y

def sub(x,y):
    return x - y

def exam():
    cmds = {'+':add,'-':sub}
    nums = [randint(1,100) for i in range(2)]   #迴圈兩次,每次從1-100選兩個數
    nums.sort(reverse=True) #sort(),排序,reverse=True,反轉,最後列表是降序排列
    op = choice('+-')
    result = cmds[op](*nums)    #(*nums),將列表轉換成元組,[op],['+']或['-'],cmds[op],字典cmds內[op]對應的值,即add或sub
    prompt = "%s %s %s = " % (nums[0],op,nums[1])
    tries = 0

    while tries < 3:
        try:    #異常處理
            answer = int(input(prompt))
        except: #簡單粗暴的捕獲所有異常
            continue

        if answer == result:
            print('Very good!')
            break
        else:
            print('Wrong answer')
            tries +=1
    else:   #while的else,全算錯才給答案,答對了就不給出答案
        print('%s%s' % (prompt,result))

if __name__ == '__main__':
    while True:
        exam()
        try:    #異常處理
            yn = input("Continue(y/n)?").strip()[0] #去除所有空格,取第一個字元
        except ImportError:
            continue
        except (KeyboardInterrupt,EOFError):
            print()
            yn = 'n'

        if yn in 'Nn':
            break

#或

#轉自https://www.jianshu.com/c/00c61372c46a網址

from random import randint,choice

def exam():
    cmds = {'+':lambda x,y:x + y,'-':lambda x,y:x - y}  #lambda,匿名函式
    nums = [randint(1,100) for i in range(2)]
    nums.sort(reverse=True)
    op = choice('+-')
    result = cmds[op](*nums)
    prompt = "%s %s %s = " % (nums[0],op,nums[1])
    tries = 0

    while tries < 3:
        try:
            answer = int(input(prompt))
        except:
            continue

        if answer == result:
            print('Very good!')
            break
        else:
            print('Wrong answer.')
            tries +=1
    else:
        print('%s%s' % (prompt,result))

if __name__ == '__main__':
    while True:
        exam()
        try:
            yn = input("Continue(y/n)?").strip()[0]
        except ImportError:
            continue
        except (KeyboardInterrupt,EOFError):
            print()
            yn = 'n'

        if yn in 'nN':
            break