Python第十九课:函数:我的地盘听我的

  • A+
所属分类:Python学习

函数与过程

函数(function):有返回值,过程(procedure)是简单,特殊并且没有返回值的

python只有函数,没有过程

  1. >>> def hello():
  2.     print('www.lijinlong.cc')
  3. >>> a = hello()
  4. www.lijinlong.cc
  5. >>> a
  6. >>> print(a)
  7. None #python不是什么都没有返回,而是返回了None的对象
  8. >>> type(a)
  9. <class 'NoneType'>

返回值

通过列表返回多个值

  1. >>> def back():
  2.     return [1,'www.lijinlong.cc',342422,610]
  3. >>> back()
  4. [1, 'www.lijinlong.cc', 342422, 610]

通过元祖返回多个值

  1. >>> def back():
  2.     return 1,'www.lijinlong.cc',342422,610
  3. >>> back()
  4. (1, 'www.lijinlong.cc', 342422, 610)

函数变量的作用域

全局变量 global variable

局部变量 local variable

  1. def diccounts(price,rate):
  2.     final_price = price * rate   # final_price属于局部变量
  3.     return final_price
  4. #以下为全局变量
  5. old_price = float(input('请输入原价:'))
  6. rate = float(input('请输入折扣:'))
  7. new_price = diccounts(old_price,rate)
  8. print('打印折扣后的价格',new_price)

调用局部变量 final_price

  1. print('打印折扣后的价格',final_price) #报错 name 'final_price' is not defined

调用全局变量

  1. def diccounts(price,rate):
  2.     final_price = price * rate
  3.     print('打印原始价格:',old_price) #内容被正常读取
  4.     return final_price
  5. old_price = float(input('请输入原价:'))
  6. rate = float(input('请输入折扣:'))
  7. new_price = diccounts(old_price,rate)
  8. print('打印折扣后的价格',new_price)

局部变量的名称与全局变量的名称相同

  1. def diccounts(price,rate):
  2.     final_price = price * rate
  3.     print('打印原始价格:',old_price) #局部变量引用了之前的分配(local variable 'old_price' referenced before assignment)
  4.     old_price = 50
  5.     print('打印局部变量中原始价格:',old_price)   #局部变量old_price被重新赋值
  6.     return final_price
  7. old_price = float(input('请输入原价:'))
  8. rate = float(input('请输入折扣:'))
  9. new_price = diccounts(old_price,rate)
  10. print('打印折扣后的价格',new_price)
  11. print('打印全局变量中原始价格:',old_price)   #这是全部变量,并不会获取到局部变量中的值

单词扩展:

  • global : 总体的
  • local: 局部的
  • variable : 变量

扩展阅读:


版权注释:

Python课程来源于鱼C论坛:http://bbs.fishc.com/forum-243-1.html 版块,课程内容为免费内容,如果你喜欢该课程,建议购买VIP账号支持小甲鱼,官方网店:https://fishc.taobao.com/)。

本内容为在李金龙在学习课程中做的日记记录,方便自己以后查找相关信息,另一方面也希望自己写下的东西可以帮助到别人。

课程内容:http://blog.fishc.com/3110.html

李金龙

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: