码迷,mamicode.com
首页 > 编程语言 > 详细

第七章第4讲:python函数的作用域:局部变量与全局变量

时间:2019-07-21 13:39:11      阅读:105      评论:0      收藏:0      [点我收藏+]

标签:python   函数   ret   put   def   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   函数   ret   put   def   python函数   生效   作用域   全局变量   

原文地址:https://www.cnblogs.com/ling07/p/11220925.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!