鱼C论坛

 找回密码
 立即注册
查看: 2722|回复: 0

[技术交流] python入门L19

[复制链接]
发表于 2017-6-30 05:45:34 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
函数与过程
函数function有返回值
过程procedure是简单的、特殊的并且没有返回值的
python严格来说只有函数没有过程
>>> temp=hello()
hello fischc
>>> temp
>>> print(temp)
None
>>> type(temp)
<class 'NoneType'>
函数有返回值则返回一个值,没有返回值则返回一个none对象
返回值:
说一个函数为整型的函数是指该函数返回一个整型的返回值,python是动态地确定类型
python没有变量只有名字,一个变量直接拿来用就可以,不用考虑变量类型,包括它的返回值。
Python 可以返回多个值
>>> def back():
        return[2,'lili',3.14]

>>> back()
[2, 'lili', 3.14]
通过列表来打包,返回多个值
>>> def back():
        return 2,'lili',3.14

>>> back()
(2, 'lili', 3.14)
利用元组将多个数据打包返回
函数变量的作用域问题(变量的可见性):
局部变量local variable和全局变量global variable:
局部变量例如在函数体内定义的变量,
全局变量的作用域是整个代码段,例如在函数体外定义的变量。

Bsp:
def discount(price,rate):
        final_price=price*rate
        return final_price
old_price= float(input('input the original price'))
rate= float(input('input the discount rate'))
new_price= discount(old_price,rate)
print('after discount the price is:',new_price)
#此处打印final_price
print('the final price is:', final_price)
NameError: name 'final_price' is not defined
函数内的变量在执行完函数后就被消除,函数外不能找到函数内的变量
def discount(price,rate):
        final_price=price*rate
        print('here trying to print a global variable',old_price)
        return final_price
old_price= float(input('input the original price'))
rate= float(input('input the discount rate'))
new_price= discount(old_price,rate)
print('after discount the price is:',new_price)

>>>
input the original price100
input the discount rate0.8
here trying to print a global variable 100.0
after discount the price is: 80.0
可以在函数体内访问全局变量
使用全局变量时要注意:如果需要改变全局变量的值,可能发生问题
def discount(price,rate):
        final_price=price*rate
        #print('here trying to print a global variable',old_price)
        old_price=50
        print('after the change the old_price1 is',old_price)

        return final_price
old_price= float(input('input the original price'))
rate= float(input('input the discount rate'))
new_price= discount(old_price,rate)
print('after the change the old_price2 is',old_price)
print('after discount the price is:',new_price)
>>>
input the original price100
input the discount rate0.8
after the change the old_price1 is 50
after the change the old_price2 is 100.0
after discount the price is: 80.0
在函数内试图修改全局变量时,python会在函数内创建一个新的局部变量名称与全局变量相同,所以在函数体外打印old_price会显示100而不是50

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-7-4 14:47

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表