python中函数的局部变量
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)