python中函式的區域性變數

2022-06-15 14:24:09 字數 2064 閱讀 8648

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.6the price after discount

is480.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.6the price after discount

is480.00

:traceback (most recent call last):

file

"d:/programs/python/lib/idlelib/a.py

", line 8, in

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)

python函式區域性變數

python簡單變數 不考慮類變數 分為兩類 函式內定義的區域性變數,和函式外定義的全域性變數 基本訪問規則 1.在函式內部,可以直接 讀取訪問全域性變數 注意唯讀 usr bin env python i 10 def f j i 1 讀取全域性變數i f print i d i 2.在函式內部,...

python函式和區域性變數

不帶引數的方法,攜帶返回值 defmethod return 不攜帶引數的方法 不帶引數的方法,攜帶返回值 defmethod1 print 不攜帶引數的方法 二者區別 函式呼叫 print method 只執行方法,不列印的話無法顯示資訊 method1 在方法中直接進行了列印,可以直接顯示,但是...

python 函式引數與區域性變數

形參變數只有在被呼叫時才分配記憶體單元,在呼叫結束時,即刻釋放所分配的記憶體單元。因此,形參只在函式內部有效。函式呼叫結束返回主呼叫函式後則不能再使用該形參變數 實參可以是常量 變數 表示式 函式等,無論實參是何種型別的量,在進行函式呼叫時,它們都必須有確定的值,以便把這些值傳送給形參。因此應預先用...