Chapter VII Lecture 4: Scope python function: local variables and global variables

1. Local variables: only after prior in vivo function, or the function is finished running, the variable is invalid

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. global variables: the main routine (function inside or outside of the function) are in force to

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. modify global variables in the function body

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) 

Results: 
the Enter. Price A: . 3 
global variables Myptice: 100 
Price =. 3, the TotalPrice = 24 
Myprice =. 3

 

Guess you like

Origin www.cnblogs.com/ling07/p/11220925.html