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

2021-08-10 18:07:46 字數 1635 閱讀 1769

我們已經學過用=給變數賦值,這次習題我們將學習用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)

return a - b

def multiply(a,b):

#乘法函式

print"multiply %d * %d"%(a, b)

return a*b

def divide(a, b):

#除法函式

print"divide %d / %d"%(a,b)

return a/b

print"let's do some math with just functions!"

age = add(30, 5) #返回20-5給age

height = subtract(78, 4) #返回78-4給height

weight = multiply(90, 2) #返回90*2給weight

iq = divide(100, 2) #返回100/2給divide

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

#a puzzle for the extra credit,type it in anyway.

print"here is a puzzle."what = add(age,subtract(height,multiply(weight,divide(iq,2))))

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

執行結果:

simengred$ python ex21.py

let's do some math with just functions!

adding 30 + 5

subtract 78 - 4

multiply 90 * 2

divide 100 / 2

age: 35,height:74,weight:180,iq:50

here is a puzzle.

divide 50 / 2

multiply 180 * 25

subtract 74 - 4500

adding 35 + -4426

that becomes: -4391 can you do it by hand?

除了return的運用外,在多個函式疊加使用時,運算的順序為:從內到外

例如:

what = add(age,subtract(height,multiply(weight,divide(iq,2))))
這個函式中,運算順序是divide-multiply-subtract-add

《笨辦法學python》習題38 40

mystuff 然後作者又給出了乙個錯誤的情況 class thing object def test hi print hia thing a.test hello 錯誤原因是test 只可以接受乙個引數,卻給了兩個。也就是 a.test hello 實際上是test a,hello 從這裡開始到...

《笨辦法學Python》 習題3

加分習題 系統 mac os 10.14 python 2.7.10 版本 笨辦法學python 第四版 print i will now count my chickens print hens 25 30 6.0 print roosters 100 25 3 4 print now i wil...

《笨辦法學Python》 習題6

加分習題 系統 mac os 10.14 python 2.7.10 版本 笨辦法學python 第四版 x there are d types of people.10 binary binary do not don t y those who know s and those who s.bi...