第4讲:python函数的作用域:局部变量与全局变量
Posted ling07
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了第4讲:python函数的作用域:局部变量与全局变量相关的知识,希望对你有一定的参考价值。
1.局部变量:只在函数体内,函数运行之前或运行结束之后,该变量无效
def calculateTax(price,tax_rate): print(price) taxTotal = price * tax_rate return taxTotal my_price = int(input("Enter a price:")) totalPrice = calculateTax(my_price,8) print("Price = ",my_price,",","TotalPrice = ",totalPrice) # print(price)
2.全局变量:在主程序(函数外或函数内)到都是生效的
def calculateTax(price,tax_rate): print("全局变量Myptice:", my_price) taxTotal = price * tax_rate return taxTotal my_price = int(input("Enter a price:")) totalPrice = calculateTax(my_price,8) print("Price = ",my_price,",","TotalPrice = ",totalPrice) print("Myprice = ",my_price)
3.全局变量在函数体内的修改
def calculateTax(price,tax_rate): # print(price) my_price=100 print("全局变量Myptice:", my_price) taxTotal = price * tax_rate return taxTotal my_price = int(input("Enter a price:")) totalPrice = calculateTax(my_price,8) print("Price = ",my_price,",","TotalPrice = ",totalPrice) print("Myprice = ",my_price) 结果: Enter a price:3 全局变量Myptice: 100 Price = 3 , TotalPrice = 24 Myprice = 3
以上是关于第4讲:python函数的作用域:局部变量与全局变量的主要内容,如果未能解决你的问题,请参考以下文章
PYTHON学习0024:函数---局部变量和全局变量----2019-6-19