第二章 2.1 变量 1 2 3 4 5 6 n = 1 m = n print (m is n)n = 2 print (m)
True
1
1 2 3 4 a = 10 print (a + 2 )print (a)
12
10
1 2 3 4 5 6 7 8 a = a + 2 print (a)a = 10 temp = a + 2 a = temp print (a)
12
12
2.2 原生数据类型 2.21 数值 1 2 3 print (1 + 2 * 3 )print ((1 + 2 ) * 3 )
7
9
1 2 print (123.0 ,1.23e2 ,12300e-2 )
123.0 123.0 123.0
1 2 print (3.14 +15j ,314e-2 +15j ,3.14 +1.5e1j )
(3.14+15j) (3.14+15j) (3.14+15j)
1 2 3 print (1 +2j * 2 ) print ((1 +2j ) * 2 )
(1+4j)
(2+4j)
1 2 3 4 5 print (True )print (False )print (1 > 2 )print (3.14 < 4 )
True
False
False
True
1 2 3 4 5 print (True + 1 )print (True + True )print (True / 2 )print (False + 1 )
2
2
0.5
1
2.22 空值 1 2 3 4 5 print (None )print (None == 0 )print (None == True )print (None == False )
None
False
False
False
2.23 字符串 1 2 3 4 5 print ('hello' )print ("world" )print ("hello 'world'" )print ('good "morning"' )
hello
world
hello 'world'
good "morning"
1 2 3 4 5 6 7 8 9 10 morning = '''Hi! Good 'morning' ''' evening = """Hello! Good "evening" """ print (morning)print (evening)
Hi!
Good 'morning'
Hello!
Good "evening"
1 2 3 4 5 6 7 print (int ('32' ))print (float ('32' ))a = str (32.0 ) print (a)print (type (a))
32
32.0
32.0
<class 'str'>
1 2 3 print ('hello \n world' )print ('hello \'world\'' )
hello
world
hello 'world'
1 2 3 print (len ('hello' ))print (len ('你好' ))
5
2
1 2 3 4 poem = 'You need Python' print ('nee' in poem)print ('早' in '早上要吃早餐' )
True
True
2.24 列表和元组 1 2 3 4 list_empty = [] list_str = ['hello' , 'good' , 'bye' ] list_hybrid = [1 , 'one' , [2 , 3 ], True ]
1 2 3 print (list ('hello' ))print (list ((1 ,2 ,3 )))
['h', 'e', 'l', 'l', 'o']
[1, 2, 3]
1 2 3 4 names = ['Liming' , 'Lili' , 'Daming' ] print (names[0 ])print (names[1 ])
Liming
Lili
1 2 3 4 names = ['Liming' , 'Lili' , 'Daming' ] print (names[-1 ])print (names[-3 ])
Daming
Liming
1 2 3 4 5 names = ['Liming' , 'Lili' , 'Daming' ] print (names)names[0 ] = 'David' print (names)
['Liming', 'Lili', 'Daming']
['David', 'Lili', 'Daming']
1 2 3 4 5 names = ['Liming' , 'Lili' , 'Daming' ] print (names)names.append('David' ) print (names)
['Liming', 'Lili', 'Daming']
['Liming', 'Lili', 'Daming', 'David']
1 2 3 4 5 6 7 names = ['Liming' , 'Lili' , 'Daming' , 'David' ] print (names)names.pop() print (names)print (names.pop(0 ))print (names)
['Liming', 'Lili', 'Daming', 'David']
['Liming', 'Lili', 'Daming']
Liming
['Lili', 'Daming']
1 2 3 names = ['Liming' , 'Lili' , 'Daming' , 'David' ] print (len (names))
4
1 2 3 4 5 6 7 8 names = ['Liming' , 'Lili' , 'Daming' , 'David' ] visitor = names print (names)print (visitor)names.pop() print (names)print (visitor)
['Liming', 'Lili', 'Daming', 'David']
['Liming', 'Lili', 'Daming', 'David']
['Liming', 'Lili', 'Daming']
['Liming', 'Lili', 'Daming']
1 2 3 4 5 6 7 8 names = ['Liming' , 'Lili' , 'Daming' , 'David' ] visitor = names.copy() print (names)print (visitor)names.pop() print (names)print (visitor)
['Liming', 'Lili', 'Daming', 'David']
['Liming', 'Lili', 'Daming', 'David']
['Liming', 'Lili', 'Daming']
['Liming', 'Lili', 'Daming', 'David']
1 2 3 4 names = ['Liming' , 'Lili' , 'Daming' , 'David' ] print ('Lili' in names)print ('Bob' in names)
True
False
1 2 3 4 tuple_empty = () tuple_name = ('Lili' ,) tuple_score = (10 , 2 ,)
1 2 3 4 5 tuple_wrong = ('wrong' ) print (type (tuple_wrong))tuple_right = ('right' ,) print (type (tuple_right))
<class 'str'>
<class 'tuple'>
1 2 3 print (tuple ('hello' ))print (tuple ([1 ,2 ,3 ]))
('h', 'e', 'l', 'l', 'o')
(1, 2, 3)
1 2 3 names = ('Liming' , 'Lili' , 'Daming' ) print (names[0 ])
Liming
1 2 3 4 names = ('Liming' , 'Lili' , 'Daming' ) print (names[-1 ])print (names[-3 ])
Daming
Liming
1 2 3 4 5 6 tuple_hybrid = (1 , 2 , []) print (tuple_hybrid)print (tuple_hybrid[2 ])tuple_hybrid[2 ].append('hello' ) print (tuple_hybrid)
(1, 2, [])
[]
(1, 2, ['hello'])
1 2 3 4 names = ('Liming' , 'Lili' , 'Daming' , 'David' ) print ('Lili' in names)print ('Bob' in names)
True
False
2.25 集合 1 2 3 4 5 6 7 8 9 set_empty = set () set_number = {1 , 3 , 10 , 4 , 5 , 5 } set_word = {'hello' , 'good' , 'bye' } set_hybrid = {'david' , 1 } print (set_empty)print (set_number)print (set_word)print (set_hybrid)
set()
{1, 3, 4, 5, 10}
{'good', 'bye', 'hello'}
{1, 'david'}
1 2 3 4 print (set ('hello' ))print (set (['good' , 'bye' ]))print (set (('good' , 'bye' )))
{'h', 'l', 'o', 'e'}
{'good', 'bye'}
{'good', 'bye'}
1 2 print ('good' in {'good' , 'hello' })
True
1 2 3 4 5 6 7 8 9 10 11 12 13 fruit_a = {'apple' , 'orange' , 'banana' } fruit_b = {'grape' , 'apple' , 'cherry' } fruit_c = {'grape' , 'berry' , 'cherry' } print (fruit_a & fruit_b)print (fruit_a & fruit_c)fruit_a = {'apple' , 'orange' , 'banana' } fruit_b = {'grape' , 'apple' , 'cherry' } fruit_c = {'grape' , 'berry' , 'cherry' } print (fruit_a | fruit_b)print (fruit_a | fruit_b | fruit_c)
{'apple'}
set()
{'cherry', 'apple', 'orange', 'grape', 'banana'}
{'cherry', 'apple', 'berry', 'orange', 'grape', 'banana'}
2.2.6 字典 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 dict_empty = {} dict_hours = { 'hour' : 1 , 'day' : 24 , 'week' : 168 } dict_hybrid = { 'clock' : 8 , 'say' : 'good morning' , 1 : 'room' } print (dict_empty)print (dict_hours)print (dict_hybrid)
{}
{'hour': 1, 'day': 24, 'week': 168}
{'clock': 8, 'say': 'good morning', 1: 'room'}
1 2 3 4 5 6 7 dict_hours = { 'hour' : 1 , 'day' : 24 , 'week' : 168 } print (dict_hours['day' ])
24
1 2 3 4 5 print ('month' in dict_hours)print (dict_hours.get('week' ))print (dict_hours.get('month' ))print (dict_hours.get('month' , 'no month' ))
False
168
None
no month
1 2 3 4 5 6 7 8 9 dict_ages = { 'Lili' : 20 , 'Daming' : 21 } print (dict_ages)dict_ages['Tom' ] = 25 print (dict_ages)dict_ages['Daming' ] = 23
{'Lili': 20, 'Daming': 21}
{'Lili': 20, 'Daming': 21, 'Tom': 25}
1 2 3 4 5 6 7 8 dict_hours = { 'hour' : 1 , 'day' : 24 , 'week' : 168 } print (dict_hours.keys())print (list (dict_hours.keys()))
dict_keys(['hour', 'day', 'week'])
['hour', 'day', 'week']
1 2 3 4 5 6 7 8 dict_hours = { 'hour' : 1 , 'day' : 24 , 'week' : 168 } print (dict_hours.values())print (list (dict_hours.values()))
dict_values([1, 24, 168])
[1, 24, 168]
1 2 3 4 5 dict_ages = {'Daming' : 21 , 'Lili' :20 } print (dict_ages)dict_ages.update({'Daming' : 23 , 'Tom' : 25 }) print (dict_ages)
{'Daming': 21, 'Lili': 20}
{'Daming': 23, 'Lili': 20, 'Tom': 25}
1 2 3 4 5 dict_ages = {'Daming' : 21 , 'Lili' :20 } print (dict_ages)print (dict_ages.pop('Lili' ))print (dict_ages)
{'Daming': 21, 'Lili': 20}
20
{'Daming': 21}
1 2 3 4 5 6 7 dict_ages = {'Daming' : 21 , 'Lili' :20 } dict_new = dict_ages print (dict_new)dict_ages['Tom' ] = 25 print (dict_new)print (dict_ages)
{'Daming': 21, 'Lili': 20}
{'Daming': 21, 'Lili': 20, 'Tom': 25}
{'Daming': 21, 'Lili': 20, 'Tom': 25}
1 2 3 4 5 6 7 dict_ages = {'Daming' : 21 , 'Lili' :20 } dict_new = dict_ages.copy() print (dict_new)dict_ages['Tom' ] = 25 print (dict_new)print (dict_ages)
{'Daming': 21, 'Lili': 20}
{'Daming': 21, 'Lili': 20}
{'Daming': 21, 'Lili': 20, 'Tom': 25}
2.3 判断 1 2 3 4 5 light_on = True if light_on: print ('开灯' ) print ('灯亮了' )
开灯
灯亮了
1 2 3 4 5 6 7 light_on = True if light_on: print ('开灯' ) print ('灯亮了' ) else : print ('灯没开' )
开灯
灯亮了
2.3.1 比较操作 1 2 3 4 5 a = 10 print (a > 5 and a < 15 )print (a > 5 and not a < 15 )print (a > 5 or not a < 15 )
True
False
True
2.3.2 条件值非布尔值 1 2 3 4 5 6 names = [] if names: print ('有人' ) else : print ('没人' )
没人
2.3.3 多重条件 1 2 3 4 5 6 7 8 9 clock = 15 if clock < 12 : print ('good morning' ) elif clock < 18 : print ('good afternoon' ) elif clock < 21 : print ('good evening' ) else : print ('good night' )
good afternoon
2.4 循环和迭代 2.4.1 循环 1 2 3 4 5 6 n = 0 while n < 3 : print (n) n = n +1 print ('循环结束' )
0
1
2
循环结束
1 2 3 4 5 6 7 8 9 10 11 12 13 names = ['Daming' , 'Lili' , 'Tom' , 'Liming' ] i = 0 while True : if i >= len (names): print ('找不到Tom' ) break elif names[i] == 'Tom' : print ('找到Tom了' ) break print (names[i], '不是Tom' ) i = i + 1 print ('Tom 所对应的索引是' , i)
Daming 不是Tom
Lili 不是Tom
找到Tom了
Tom 所对应的索引是 2
1 2 3 4 5 6 7 8 9 10 11 n = 1 n_sum = 0 while n < 10 : if n % 2 == 0 : n = n + 1 continue print (n, '不是偶数' ) n_sum = n_sum + n n = n + 1 print (n_sum)
1 不是偶数
3 不是偶数
5 不是偶数
7 不是偶数
9 不是偶数
25
2.4.2 迭代 1 2 3 4 5 6 fruits = ['apple' , 'orange' , 'banana' ] for fruit in fruits: print (fruit) if fruit == 'orange' : print ('我最爱orange' )
apple
orange
我最爱orange
banana
1 2 3 4 name = 'Tom' for letter in name: print (letter)
T
o
m
1 2 3 4 dict_ages = {'Daming' : 21 , 'Lili' : 20 } for key in dict_ages.keys(): print (key)
Daming
Lili
1 2 3 4 dict_ages = {'Daming' : 21 , 'Lili' : 20 } for value in dict_ages.values(): print (value)
21
20
1 2 3 4 dict_ages = {'Daming' : 21 , 'Lili' : 20 } for item in dict_ages.items(): print (item)
('Daming', 21)
('Lili', 20)
1 2 3 4 dict_ages = {'Daming' : 21 , 'Lili' : 20 } for name, age in dict_ages.items(): print (name, 'is' , age)
Daming is 21
Lili is 20
1 2 3 4 5 6 fruits = ['apple' , 'orange' , 'banana' ] for fruit in fruits: if fruit == 'orange' : break print (fruit)
orange
1 2 3 4 5 6 fruits = ['apple' , 'orange' , 'banana' ] for fruit in fruits: if fruit == 'orange' : continue print (fruit)
banana
1 2 3 4 5 6 7 8 9 10 for i in range (3 ): print (i) for i in range (2 , 3 ): print (i) for i in range (0 , 3 , 2 ): print (i)
0
1
2
2
0
2
1 2 3 for i in range (3 , -3 , -2 ): print (i)
3
1
-1
1 2 3 4 5 6 7 8 i = 0 while i < 3 : print ('while重复3次' ) i = i + 1 for i in range (3 ): print ('for重复3次' )
while重复3次
while重复3次
while重复3次
for重复3次
for重复3次
for重复3次
2.5 序列切片 1 2 3 4 5 6 7 8 greeting = 'good morning' print (greeting[:])print (greeting[6 :])print (greeting[:4 ])print (greeting[3 :7 ])print (greeting[3 :7 :2 ])print (greeting[::2 ])
good morning
orning
good
d mo
dm
go onn
1 2 3 4 greeting = 'good morning' print (greeting[4 ::-1 ])print (greeting[::-1 ])
doog
gninrom doog
2.6 解析式 2.6.1 列表解析式 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 numbers = [] for i in range (10 ): numbers.append(i) print (numbers)numbers = list (range (10 )) print (numbers)numbers = [i for i in range (10 )] print (numbers)numbers = [i**2 for i in range (10 )] print (numbers)numbers = ['hi' for i in range (10 )] print (numbers)numbers = [i for i in range (10 ) if i % 2 != 0 ] print (numbers)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
['hi', 'hi', 'hi', 'hi', 'hi', 'hi', 'hi', 'hi', 'hi', 'hi']
[1, 3, 5, 7, 9]
1 2 3 4 5 6 7 8 9 10 11 numbers = [(i, j) for i in range (2 ) for j in range (3 )] print (numbers)numbers = [] for i in range (2 ): for j in range (3 ): numbers.append((i, j)) print (numbers)
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)]
2.6.2 字典解析式 1 2 3 4 5 mapping = {i: i**2 for i in range (10 )} print (mapping)mapping = {i: i**2 for i in range (10 ) if i**2 >40 } print (mapping)
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
{7: 49, 8: 64, 9: 81}
2.6.3 集合解析式 1 2 3 numbers = {i for i in range (10 )} print (numbers)
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
2.6.4 生成器解析式 1 2 3 4 5 6 7 numbers = (i for i in range (3 )) for i in numbers: print (i) print ('第一次迭代完成' )for i in numbers: print (i)
0
1
2
第一次迭代完成
2.7 函数 2.7.1 定义函数 1 2 3 4 def nothing (): pass nothing()
1 2 3 4 def say_hi (): print ('Hi' ) say_hi()
Hi
1 2 3 4 5 6 def say_hi (name ): print ('Hi,' , name) say_hi('Daming' )
Hi, Daming
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 def greet (clock ): if clock < 12 : return 'good morning' elif clock < 18 : return 'good afternoon' elif clock < 21 : return 'good evening' else : return 'good night' greeting = greet(13 ) print (greeting)def say_hi (): print ('Hi' ) print (say_hi())
good afternoon
Hi
None
2.7.2 函数的参数 1 2 3 4 5 6 7 def pos_abc (a, b, c ): print ('a is' , a) print ('b is' , b) print ('c is' , c) pos_abc(1 , 3 , 5 )
a is 1
b is 3
c is 5
1 2 3 4 5 6 7 def pos_abc (a, b, c ): print ('a is' , a) print ('b is' , b) print ('c is' , c) pos_abc(b=3 , a=1 , c=5 )
a is 1
b is 3
c is 5
1 2 3 4 5 6 7 def pos_abc (a, b, c ): print ('a is' , a) print ('b is' , b) print ('c is' , c) pos_abc(1 , c=5 , b=3 )
a is 1
b is 3
c is 5
1 2 3 4 5 6 7 def pos_abc (a, b=3 , c=10 ): print ('a is' , a) print ('b is' , b) print ('c is' , c) pos_abc(1 , 3 )
a is 1
b is 3
c is 10
1 2 3 4 5 6 7 8 def pos_abc (a, b, c=10 ): print ('a is' , a) print ('b is' , b) print ('c is' , c) pos_abc(1 , 3 , 5 )
a is 1
b is 3
c is 5
1 2 3 4 5 6 7 8 def pos_abc (a=1 , b=3 , c=5 ): print ('a is' , a) print ('b is' , b) print ('c is' , c) pos_abc()
a is 1
b is 3
c is 5
1 2 3 4 5 6 7 8 def print_args (*args ): print (args) print_args(1 , 2 ,3 ) def print_args (*args ): print (args) print_args()
(1, 2, 3)
()
1 2 3 4 5 def print_kwargs (**kwargs ): print (kwargs) print_kwargs(a=1 , b=2 )
{'a': 1, 'b': 2}
2.7.3 匿名函数 1 2 3 4 5 6 7 8 func = lambda x: x**2 print (func(2 ))greet = lambda : print ('hello' ) pos_ab = lambda a,b: print (a + b) greet() pos_ab(1 , 2 )
4
hello
3
2.7.4 闭包与装饰器 1 2 3 4 5 6 7 def outer (): def inner (): print ("I'm inner func" ) print ("I'm outer func" ) inner() outer()
I'm outer func
I'm inner func
1 2 3 4 5 6 7 8 9 def outer (): def inner (): print ("I'm inner func" ) print ("I'm outer func" ) return inner func = outer() print ('下面执行func' )func()
I'm outer func
下面执行func
I'm inner func
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 def outer (func ): def inner (): func() print ("I'm inner func" ) print ("I'm outer func" ) return inner def say_hi (): print ('Hi!' ) say_hi = outer(say_hi) print ('下面执行say_hi' )say_hi() print ('再次执行say_hi' )say_hi()
I'm outer func
下面执行say_hi
Hi!
I'm inner func
再次执行say_hi
Hi!
I'm inner func
1 2 3 4 5 6 7 8 9 10 11 12 def factory (n ): def multiply (m ): return n * m return multiply x2 = factory(2 ) print (x2(2 ))print (x2(3 ))x10 = factory(10 ) print (x10(2 ))print (x10(3 ))
4
6
20
30
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 def outer (func ): def inner (): func() print ("I'm inner func" ) print ("I'm outer func" ) return inner @outer def say_hi (): print ('Hi!' ) print ('下面执行say_hi' )say_hi() print ('再次执行say_hi' )say_hi()
I'm outer func
下面执行say_hi
Hi!
I'm inner func
再次执行say_hi
Hi!
I'm inner func
2.7.5 高阶函数 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 def plus2 (x ): return x + 2 numbers = [1 , 3 , 5 , 6 ] new_numbers = map (plus2, numbers) print (new_numbers)print (list (new_numbers))def plus2 (x ): return x + 2 numbers = [1 , 3 , 5 , 6 ] new_numbers = [plus2(n) for n in numbers] print (new_numbers)numbers = [1 , 3 , 5 , 6 ] new_numbers = map (lambda x: x + 2 , numbers) print (new_numbers)print (list (new_numbers))
<map object at 0x7fa310300ed0>
[3, 5, 7, 8]
[3, 5, 7, 8]
<map object at 0x7fa310300c90>
[3, 5, 7, 8]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 def lt_5 (x ): return x < 5 numbers = [1 , 3 , 5 , 6 ] new_numbers = filter (lt_5, numbers) print (new_numbers)print (list (new_numbers))def lt_5 (x ): return x < 5 numbers = [1 , 3 , 5 , 6 ] new_numbers = [n for n in numbers if lt_5(n)] print (new_numbers)
<filter object at 0x7fa310300cd0>
[1, 3]
[1, 3]
面向对象基础 2.8.2 类和继承 1 2 3 4 5 6 7 8 9 class Student : def __init__ (self, name, age, deposit ): self.name = name self.age = age self.__deposit = deposit xiaoming = Student('小明' , 12 , 1000 ) print (xiaoming.name)
小明
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 class Student : def __init__ (self, name, age, deposit ): self.name = name self.age = age self.__deposit = deposit def do_homework (self ): answer = self.__calculate(1 , 1 ) print ('做完作业了,答案是' , answer) def wash_dishes (self, n_dishes ): self.__deposit = self.__deposit + n_dishes * 10 print ('洗过碗了,又赚' , n_dishes * 10 , '元,现在有' , self.__deposit) def __calculate (self, a, b ): print ('悄悄算算术,不告诉别人' ) return a + b xiaoming = Student('小明' , 12 , 1000 ) xiaoming.do_homework() xiaoming.wash_dishes(1 ) xiaoming.wash_dishes(5 ) xiaoming.wash_dishes(3 )
悄悄算算术,不告诉别人
做完作业了,答案是 2
洗过碗了,又赚 10 元,现在有 1010
洗过碗了,又赚 50 元,现在有 1060
洗过碗了,又赚 30 元,现在有 1090
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 class Animal : def breathe (self ): print ('动物需要呼吸' ) class Dog (Animal ): def woof (self ): print ('汪汪汪' ) class Cat (Animal ): def meow (self ): print ('喵喵喵' ) speike = Dog() tom = Cat() speike.breathe() tom.breathe() speike.woof() tom.meow()
动物需要呼吸
动物需要呼吸
汪汪汪
喵喵喵
1 2 3 4 5 6 7 class Mouse (Animal ): def breathe (self ): print ('老鼠也需要呼吸' ) jerry = Mouse() jerry.breathe()
老鼠也需要呼吸