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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM