第七章第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