1、
def discount(price,rate): ## 定義函數名discount,兩個形式參數price和rate sell_price = price * rate return sell_price ## 函數返回售價 price = float(input("please input the price:")) ## 此處接受輸入原價 rate = float(input("please input the rate:")) ## 此處接受輸入折扣率 final_price = discount(price,rate) ## 調用discount函數,使用位置參數 print("the price after discount is %.2f:" % final_price) ## 輸出最終價格
## 以上函數, price、rate、final_price為全局變量, sell_price為局部變量
please input the price:800 please input the rate:0.6 the price after discount is 480.00:
2、
def discount(price,rate): sell_price = price * rate return sell_price price = float(input("please input the price:")) rate = float(input("please input the rate:")) final_price = discount(price,rate) print("the price after discount is %.2f:" % final_price) print("output sell_price:",sell_price) ## 此處嘗試調用局部變量
please input the price:800 please input the rate:0.6 the price after discount is 480.00: Traceback (most recent call last): File "D:/programs/python/Lib/idlelib/a.py", line 8, in <module> print("output sell_price:",sell_price) NameError: name 'sell_price' is not defined ## 不能調用局部變量
3、
def discount(price,rate): sell_price = price * rate print("please show the price again:", price) print("please show the rate again:",rate) return sell_price price = float(input("please input the price:")) rate = float(input("please input the rate:")) final_price = discount(price,rate) ## 在調用discount函數時,調用了全局變量price和rate print("the price after discount is %.2f:" % final_price)