與小卡特一起學python 第13章 函式-積木

yarking207發表於2016-04-05
#13.1 函式-積木 建立和使用函式
def printMyAddress():
    print("Warren Sande")
    print("123 Main Street")
    print("Ottawa,Ontario,Canada")
    print("K2m 2e9")
    print()
printMyAddress()

#13.2呼叫函式
printMyAddress()
printMyAddress()
printMyAddress()

#13-2 向函式傳遞引數
def printMyAdress(myName):
    print (myName) #形參 人名
    print ("123 Main Street")
    print ("Ottawa,Ontario,Cannada")
    print ("K2M 2E9")
    print()
printMyAdress("Carter Sande") #將Carter Sande傳遞給變數myName
printMyAdress("Warren Sande")
printMyAdress("Kyra Sande")
printMyAdress("Patricia Sande")
#13-3 帶兩個引數的函式
def printMyAddress (someName,houseNum):
    print(someName)
    print(houseNum,end="")#把門牌號和街道顯示同一行
    print("Main Street")
    print("Ottawa,Ontario,Canada")
    print("K2M 2E9")
    print()
printMyAddress("Carter Sande","45")
printMyAddress("Jack Black","64")
printMyAddress("Tom Green","22")
printMyAddress("Todd White","36")

#13.4 返回值的函式 建立和使用返回值的函式
def calculateTax(price,tax_rate):
    total = price +(price * tax_rate)
    return total
my_price = float(input("Enter a price:"))

totalPrice = calculateTax(my_price,0.06)
print("price = ",my_price,"Total price = ",totalPrice)
#13-5 變數作用域 嘗試列印一個區域性變數
def calculateTax(prince,tax_rate):
    total = price + (price * tax_rate)
    return total
my_price = float (input("Enter a price:"))

totalPrice = calculateTax(my_price,0.06)
print("price=",my_price,"Tatal price = ",totalPrice)
print (price) #嘗試列印區域性變數,會出錯,因為沒有定義

#13-6 在函式中使用全域性變數
def calculateTax(price,tax_rate):
    total = price +(price * tax_rate)
    print(my_price) #列印函式中的全域性變數
    return total
my_price = float (input("Enter a price:"))
totalPrice = calculateTax(my_price,0.006)
print("price=",my_price,"Total price = ", totalPrice)
#13-7 嘗試在函式內部修改一個全域性變數
def calculateTax(price,tax_rate):
    total = price +(price * tax_rate)

    my_price = 10000
    print("my_price (inside function) = ",my_price)
    return total
my_price = float (input("Enter a price:"))
totalPrice = calculateTax(my_price,0.06)
print("price = ",my_price,"Total price = ", totalPrice)
print("my_price (outside function) =",my_price)

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/220205/viewspace-2075834/,如需轉載,請註明出處,否則將追究法律責任。

相關文章