ex21 return的簡單使用

我們創建了我們自己的加減乘除數學函數: add, subtract, multiply, 以及 divide。重要的是函數的最後一行,例如 add 的最後一行是 return a+ b,
它實現的功能是這樣的:

  1. 我們調用函數時使用了兩個參數: a 和 b 。
  2. 我們打印出這個函數的功能,這裏就是計算加法(adding)
  3. 接下來我們告訴 Python 讓它做某個回傳的動作:我們將 a + b 的值返回(return)。
    或者你可以這麼說: “我將 a 和 b 加起來,再把結果返回。 ”
  4. Python 將兩個數字相加,然後當函數結束的時候,它就可以將 a + b 的結果賦予一個變量。

腳本內容

def add(a,b):       #兩個參數
    print("Adding %d + %d" %(a,b))
    return a + b    #兩個參數運算的返回值

def subtract(a,b):
    print("Subtracting %d - %d" %(a,b))
    return a - b  

def multiply(a,b):
    print("Multipling %d * %d" %(a,b))
    return a * b

def divide(a,b):
    print("Dividing %d / %d" %(a,b))
    return a / b

print("Let's do some math with this funcitons")
age = add(10,12)      #賦予兩個參數,使用add函數進行計算
weight = subtract(70,10)
height = multiply(10,17)
iq = divide(200,2)

print("So it's your information,age:%d,weight:%d,height:%d,iq:%d" %(age,weight,height,iq))

what = add(age,subtract(weight,multiply(height,divide(iq,2))))       #將上面計算出來的變量用於疊加計算
print("The result is",what,"Can you do it by hand?")

運行結果

Let’s do some math with this funcitons
Adding 10 + 12
Subtracting 70 - 10
Multipling 10 * 17
Dividing 200 / 2
So it’s your information,age:22,weight:60,height:170,iq:100
Dividing 100 / 2
Multipling 170 * 50
Subtracting 60 - 8500
Adding 22 + -8440
The result is -8418.0 Can you do it by hand?

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章