笨辦法21函式的返回值

2021-08-08 03:12:35 字數 1545 閱讀 3589

**如下:把第3行的加號換成了減號

def

add(a, b):

print

"adding %d + %d" % (a, b)

return a - b

defsubstract

(a, b):

print

"subtracting %d - %d" % (a, b)

return a - b

defmultiply

(a, b):

print

"multiplying %d * %d" % (a, b)

return a * b

defdivide

(a, b):

print

"dividing %d / %d" % (a, b)

return a / b

age = add(30, 5)

height = substract(78, 4)

weight = multiply(90, 2)

iq = divide(100, 2)

print

"age: %d, height: %d, weight: %d, iq:%d" % (age, height, weight, iq)

what = add(age, substract(height, multiply(weight, divide(iq, 2))))

print

"that becomes:", what, "can you do it by hand?"

執行結果可見,return的值和定義變數裡print那一行的內容無關

總覺得冗餘的內容太多反而不利於理解,以下簡化**:

def

add(a, b):

return a - b

defsubstract

(a, b):

return a - b

defmultiply

(a, b):

return a * b

defdivide

(a, b):

return a / b

age = add(30, 5)

height = substract(78, 4)

weight = multiply(90, 2)

iq = divide(100, 2)

print

"age: %d, height: %d, weight: %d, iq:%d" % (age, height, weight, iq)

what = add(age, substract(height, multiply(weight, divide(iq, 2))))

print

"that becomes:", what, "can you do it by hand?"

輸出結果:

笨辦法學python習題21 函式可以返回某些東西

我們已經學過用 給變數賦值,這次習題我們將學習用return來將函式的值賦給變數 如下 coding utf 8 def add a,b 加法函式 print adding d d a,b return a b def subtract a,b 減法函式 print subtract d d a,b...

主函式的返回值返回給誰 主函式返回值

responsebody報406 原因是 要返回的物件沒有setget方法sdfsdf 自定義視 析器和缺省視 析器需同時使用才好用 如果以redireci或forward字首,那麼 走缺省視 析器 return redirect index.jsp return forward index 需寫全...

函式返回值

這裡接著探求被調函式的返回值是如何傳遞到主調函式中的,下面為c程式。add函式通過直接返回a b的,而add1函式先定義乙個區域性變數c,儲存a b的值,然後再返回c的值。其中a b可以當成乙個臨時變數,其結果是暫時存放在暫存器中的 eax 參照反匯程式設計序,可以看出函式的值並不是通過壓棧 基址定...