- A+
所属分类:Python学习
函数与过程
函数(function):有返回值,过程(procedure)是简单,特殊并且没有返回值的
python只有函数,没有过程
- >>> def hello():
- print('www.lijinlong.cc')
- >>> a = hello()
- www.lijinlong.cc
- >>> a
- >>> print(a)
- None #python不是什么都没有返回,而是返回了None的对象
- >>> type(a)
- <class 'NoneType'>
返回值
通过列表返回多个值
- >>> def back():
- return [1,'www.lijinlong.cc',342422,610]
- >>> back()
- [1, 'www.lijinlong.cc', 342422, 610]
通过元祖返回多个值
- >>> def back():
- return 1,'www.lijinlong.cc',342422,610
- >>> back()
- (1, 'www.lijinlong.cc', 342422, 610)
函数变量的作用域
全局变量 global variable
局部变量 local variable
- def diccounts(price,rate):
- final_price = price * rate # final_price属于局部变量
- return final_price
- #以下为全局变量
- old_price = float(input('请输入原价:'))
- rate = float(input('请输入折扣:'))
- new_price = diccounts(old_price,rate)
- print('打印折扣后的价格',new_price)
调用局部变量 final_price
- print('打印折扣后的价格',final_price) #报错 name 'final_price' is not defined
调用全局变量
- def diccounts(price,rate):
- final_price = price * rate
- print('打印原始价格:',old_price) #内容被正常读取
- return final_price
- old_price = float(input('请输入原价:'))
- rate = float(input('请输入折扣:'))
- new_price = diccounts(old_price,rate)
- print('打印折扣后的价格',new_price)
局部变量的名称与全局变量的名称相同
- def diccounts(price,rate):
- final_price = price * rate
- print('打印原始价格:',old_price) #局部变量引用了之前的分配(local variable 'old_price' referenced before assignment)
- old_price = 50
- print('打印局部变量中原始价格:',old_price) #局部变量old_price被重新赋值
- return final_price
- old_price = float(input('请输入原价:'))
- rate = float(input('请输入折扣:'))
- new_price = diccounts(old_price,rate)
- print('打印折扣后的价格',new_price)
- 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