python学习笔记(二)

代码写多行的时候,需要换一下行在继续写,此时用反斜杠敲一个反斜杠:'\'

a='春花秋月何时了,往事知多少?\
小楼昨夜又东风\
古国不堪回首月明中'
print(a)
'''
春花秋月何时了,往事知多少?小楼昨夜又东风古国不堪回首月明中
'''
View Code

引用全局变量和局部变量的耗时比较:

import math
import time
def test01():
    t1 = time.time()
    for i in range(10000000):
        math.sqrt(30)
    t2=time.time()
    print('the exausting time is :',t2-t1)

def test02():
    b=math.sqrt
    t1 = time.time()
    for i in range(10000000):
        b(30)
    t2 = time.time()
    print('the exausting time is :', t2 - t1)

test01()
test02()
'''
the runnin result is :
the exausting time is : 2.2281274795532227
the exausting time is : 1.7481002807617188
'''
View Code

每一个函数当然都可以自由的引用全局变量,但是当某一个函数的内部定义的局部变量a和全局变量a的名字相同时,在该函数内部,该变量a按照局部变量对待,除非做出是它是全局变量的声明。global a

不建议定义全局变量,除非是需要定义一个常数。

a=111
def test():
    a=123
    print(a)
test()
'''
是按照局部变量打印的:
123
'''
View Code
a=111
def test():
    print(a)
    a=123
    print(a)
test()
'''
是按照局部变量对待,因为引用前未赋值,所以报错:
UnboundLocalError: local variable 'a' referenced before assignment
'''
View Code
a=111
def test():
    global a
    print('在对全局变量做出更改之前a的值:',a)
    a=123
    print('在对全局变量做出更改之后a的值:', a)
test()
print('在对全局变量做出更改之后a的值:',a)
'''
在对全局变量做出更改之前a的值: 111
在对全局变量做出更改之后a的值: 123
在对全局变量做出更改之后a的值: 123
'''
View Code

可变对象有哪些?

答:列表,字典,集合,自定义的对象

不可变对象有哪些?

答:元组,数字,字符串,function

传递不可变对象与可变对象的引用的差别:

#传递不可变对象的的引用,创建了新对象,从对象的地址发生了改变就可以看出来
a=100
def f1(m):
    print(a)
    print(id(a))
    m=m+3
    print(id(m))
    print(m)
f1(a)
'''
100
1827827008
1827827104
103
'''
View Code
#传递可变对象的的引用,没有创建新对象
a=[100,200,300]
def f1(m):
    print(a)
    print(id(a))
    m.append(5)
    print(id(m))
    print(m)
f1(a)
print(a)
'''
[100, 200, 300]
40894216
40894216
[100, 200, 300, 5]
[100, 200, 300, 5]
'''
View Code

 

posted on 2018-08-01 18:10  一杯明月  阅读(255)  评论(0)    收藏  举报