開始使用免費開始

回傳函式的數學遊戲

你正在製作一個教育性質的數學遊戲。玩家輸入一個數學術語,你的程式就回傳對應的函式。例如,使用者輸入「add」,你的程式會回傳一個能把兩個數字相加的函式。到目前為止,你只實作了「add」函式。現在你也想加入「subtract」函式。

本練習屬於課程

Python 函式寫作

檢視課程

練習說明

  • 定義 subtract() 函式。它需要兩個引數,並回傳第一個引數減去第二個引數。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

def create_math_function(func_name):
  if func_name == 'add':
    def add(a, b):
      return a + b
    return add
  elif func_name == 'subtract':
    # Define the subtract() function
    ____
      ____
    return subtract
  else:
    print("I don't know that one")
    
add = create_math_function('add')
print('5 + 2 = {}'.format(add(5, 2)))

subtract = create_math_function('subtract')
print('5 - 2 = {}'.format(subtract(5, 2)))
編輯並執行程式碼