python basic

basic

内置函数

type
id
help

input print

1
2
3
4
5
6
7
8
9
>>> name = input("your name is: ")
your name is: zhangsan
>>> name
'zhangsan'
>>> type(name)
<class 'str'>
>>> print(name)
zhangsan
>>>

name.py

1
2
3
4
5
6
7
8
9
10
11
12
#coding:utf-8
'''
your name and age.
'''
name = input("your name: ")
age = input("your age: ")
after = int(age) + 10
print("your name is: ",name)
print("after ten years, you are ",after)

整数 浮点数 四则运算

标准库中的math

1
2
import math
dir(math)
1
['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']
1
2
3
4
5
import math
math.pi
math.pow(2,3)
2 ** 3

异常运算精度问题 大部分使用round可解决

1
2
3
4
5
6
7
8
import decimal
a = decimal.Decimal('0.1')
b = decimal.Decimal('0.2')
a + b
输出
Decimal('0.3')

浮点数溢出问题:

1
2
3
4
5
>>> 2 ** 10000 * 0.1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OverflowError: int too large to convert to float
>>>

python文件 force.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#coding:utf-8
'''
my first programe.
filename: force.py
'''
import math
f1 = 20
f2 = 10
alpha = math.pi / 3
x_force = f1 + f2 * math.sin(alpha)
y_force = f2 * math.cos(alpha)
force = math.sqrt(x_force * x_force + y_force ** 2)
print('The result is : ',round(force,2),'N')

字符和字符串

1
2
3
4
5
>>> ord('a')
97
>>> bin(97)
'0b1100001'
>>>
1
2
3
4
>>> import sys
>>> sys.getdefaultencoding()
'utf-8'
>>>

字符串定义

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
>>> a = "python"
>>> type(a)
<class 'str'>
>>> b = 'python'
>>> type(b)
<class 'str'>
>>> type('250')
<class 'str'>
>>> int('250')
250
>>> str(250)
'250'
>>> 'what's your name'
File "<stdin>", line 1
'what's your name'
^
SyntaxError: invalid syntax
>>> "what's your name"
"what's your name"
>>> 'what"s your name'
'what"s your name'
>>> 'what\'s your name'
"what's your name"
>>>

https://www.runoob.com/python/python-strings.html

序列及其基本操作

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
>>> m = 'python'
>>> n = 'book'
>>> m + n
'pythonbook'
>>> m
'python'
>>>
>>> n
'book'
>>> m * 3
'pythonpythonpython'
>>> len(m)
6
>>>
>>> name = "张三"
>>> len(name)
2
>>> m
'python'
>>> 'p' in m
True
>>> 'm' in m
False
>>>

索引和切片

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
>>> r = "python book"
>>> len(r)
11
>>> r[0]
'p'
>>> r[-1]
'k'
>>> r[1:9]
'ython bo'
>>> r[1:9:1]
'ython bo'
>>> r[:9:2]
'pto o'
>>> r[2:]
'thon book'
>>> r[:]
'python book'
>>> r[::-1]
'koob nohtyp'
>>> r[-10:8:2]
'yhnb'
>>> r[8:-10:-2]
'o ot'

字符串的常用属性和方法

查看对象的属性和方法
1
2
3
4
>>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>>
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
>>> s = 'python lesson'
>>> s
'python lesson'
>>> s.index('n')
5
>>> s.index('n',6)
12
>>> s.index('on')
4
>>> a = "I LOVE PYTHON"
>>> a.split(" ")
['I', 'LOVE', 'PYTHON']
>>> lst = a.split(" ")
>>> lst
['I', 'LOVE', 'PYTHON']
>>> "-".join(lst)
'I-LOVE-PYTHON'
>>> "I like {0} and {1}".format("python","physics")
'I like python and physics'
>>> "I like {0} and {1}".format("PHP","money")
'I like PHP and money'
>>> "I like {0:10} and {1:>15}".format("python","physics")
'I like python and physics'
>>> "She is {0:4d} years old and {1:.1f}m in height".format(28,1,68)
'She is 28 years old and 1.0m in height'
>>>
使用帮助文档

列表

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
>>> lst = [2,3,3.14,"python lesson",[]]
>>> type(list)
<class 'type'>
>>>
>>> dir(list)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>>
# append 尾部追加,无返回值
>>> lst = [1,2,300,4]
>>> lst
[1, 2, 300, 4]
>>> lst.append('python')
>>> lst
[1, 2, 300, 4, 'python']
>>> lst.append('lesson')
>>> list
<class 'list'>
>>> lst
[1, 2, 300, 4, 'python', 'lesson']
>>> r = lst.append('zhangsan')
>>> r
>>> print(r)
None
>>>
# insert 指定索引前增加对象
>>> lst.insert(0,10)
>>> lst
[10, 1, 2, 300, 4, 'python', 'lesson', 'zhangsan']
>>>
# extend 增加可迭代对象
>>> lst2 = ['a','b']
>>> lst2
['a', 'b']
>>> lst.extend(lst2)
>>> lst
[10, 1, 2, 300, 4, 'python', 'lesson', 'zhangsan', 'a', 'b']
>>> lst.extend('book')
>>> lst
[10, 1, 2, 300, 4, 'python', 'lesson', 'zhangsan', 'a', 'b', 'b', 'o', 'o', 'k']
>>>
# pop 指定索引删除对象默认删除尾部,返回对象 remove 删除第一次出现的指定对象 无返回
>>> lst.pop()
'k'
>>> lst.pop(0)
10
>>> lst.remove('b')
>>> lst
[1, 2, 300, 4, 'python', 'lesson', 'zhangsan', 'a', 'b', 'o', 'o']
# clear 清空
>>> lst2
['a', 'b']
>>> lst2.clear()
>>> lst2
[]
>>>
# sort 排序,只能同类型 reverse
>>> lst.sort()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'str' and 'int'
>>>
>>> lst2.sort()
>>> lst2
[1, 2, 2, 4, 6, 9]
>>> lst2.sort(reverse=True)
>>> lst2
[9, 6, 4, 2, 2, 1]
>>> lst2.sort(reverse=False)
>>> lst2
[1, 2, 2, 4, 6, 9]
>>> lst2.reverse()
>>> lst2
[9, 6, 4, 2, 2, 1]
>>> lst2.append(3)
>>> lst2
[9, 6, 4, 2, 2, 1, 3]
>>> sorted(lst2)
[1, 2, 2, 3, 4, 6, 9]
>>> lst2
[9, 6, 4, 2, 2, 1, 3]
>>> reversed(lst2)
<list_reverseiterator object at 0x103c3dd30>
>>>

比较列表与字符串

  • 都是序列
  • 列表是容器类对象,列表可变
  • 字符串不可变

元组

元组只有一个元素必须加逗号

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
>>> t = (1,2,'python',[1,2,3])
>>> t
(1, 2, 'python', [1, 2, 3])
>>> type(t)
<class 'tuple'>
>>> tuple()
()
>>> tuple([1,23,44])
(1, 23, 44)
>>> ('a',)
('a',)
>>> t = ('a')
>>> t
'a'
>>>

元组也是序列

1
2
3
4
5
6
>>> t = (1,2,3)
>>> type(t)
<class 'tuple'>
>>> dir(t)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']
>>>

元组是不可变对象,不可修改

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
>>> t = (1,2,'python',[1,2,3])
>>> t
(1, 2, 'python', [1, 2, 3])
>>> t[1] = 200
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> lst = list(t)
>>> lst
[1, 2, 'python', [1, 2, 3]]
>>> lst[1] = 200
>>> lst
[1, 200, 'python', [1, 2, 3]]
>>> t = tuple(lst)
>>> t
(1, 200, 'python', [1, 2, 3])
1
2
3
4
5
6
7
8
9
10
11
>>> t1 = (1,2,3)
>>> t2 = ("a","b","c")
>>> t1 + t2
(1, 2, 3, 'a', 'b', 'c')
>>> t1 * 3
(1, 2, 3, 1, 2, 3, 1, 2, 3)
>>> len(t1)
3
>>> 1 in t1
True
>>>

比较元组和列表

  • 元组不可变
  • 元组运算速度快
  • 两者都是容器类、序列类对象

字典

定义 key 必须是不可变元素,不可重复

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
>>> d = {}
>>> type(d)
<class 'dict'>
>>> d = {'name':'zhangsan','age':29,'city':'chengdu'}
>>> d
{'name': 'zhangsan', 'age': 29, 'city': 'chengdu'}
>>> dict(a=1,b=2,c=3)
{'a': 1, 'b': 2, 'c': 3}
>>> {[1,2,3]:'hello'}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> {(1,2,3):'hello'}
{(1, 2, 3): 'hello'}
>>>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
>>> dir(d)
['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
>>> d
{'name': 'zhangsan', 'age': 29, 'city': 'chengdu'}
>>> d['age']
29
>>> len(d)
3
>>> d['age']=39
>>> d
{'name': 'zhangsan', 'age': 39, 'city': 'chengdu'}
>>> del d['city']
>>> d
{'name': 'zhangsan', 'age': 39}
>>> 'age' in d
True
>>> 39 in d
False
>>>

字典常用方法

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
>>> d = dict([('a',1),('lang','python')])
>>> d
{'a': 1, 'lang': 'python'}
>>> d['a']
1
>>> d['b']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'b'
>>> d.get('b')
>>> d.get('b','zhangsan')
'zhangsan'
>>> d.setdefault('b')
>>> d
{'a': 1, 'lang': 'python', 'b': None}
>>> d.setdefault('name','zhangsan')
'zhangsan'
>>> d
{'a': 1, 'lang': 'python', 'b': None, 'name': 'zhangsan'}
>>> d['b'] = 'hello'
>>> d
{'a': 1, 'lang': 'python', 'b': 'hello', 'name': 'zhangsan'}
>>> d.update([('price',3.14),('color','white')])
>>> d
{'a': 1, 'lang': 'python', 'b': 'hello', 'name': 'zhangsan', 'price': 3.14, 'color': 'white'}
>>> d1 = {'city':'soochow'}
>>> d.update(d1)
>>> d
{'a': 1, 'lang': 'python', 'b': 'hello', 'name': 'zhangsan', 'price': 3.14, 'color': 'white', 'city': 'soochow'}
>>> del d['a']
>>> d
{'lang': 'python', 'b': 'hello', 'name': 'zhangsan', 'price': 3.14, 'color': 'white', 'city': 'soochow'}
>>> d.pop
d.pop( d.popitem(
>>> d.pop('lang')
'python'
>>> d
{'b': 'hello', 'name': 'zhangsan', 'price': 3.14, 'color': 'white', 'city': 'soochow'}
>>> d.pop('lang')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'lang'
>>> d.pop('lang','pascal')
'pascal'
>>> d.popitem()
('city', 'soochow')
>>>

比较字典和列表:

  • 字典不是序列
  • 两者都是容器对象
  • 两者都是可变对象
  • python3.6开始,字典也有顺序

集合

可变集合

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
27
28
29
30
31
32
33
34
35
>>> s = set([1,2,3,3,2,1,4])
>>> s
{1, 2, 3, 4}
>>> type(s)
<class 'set'>
>>> s2 = {'python',2,3}
>>> s2
{'python', 2, 3}
>>> s3 = {'pyton',[1,2,3]}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> dir(s)
['__and__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__iand__', '__init__', '__init_subclass__', '__ior__', '__isub__', '__iter__', '__ixor__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'add', 'clear', 'copy', 'difference', 'difference_update', 'discard', 'intersection', 'intersection_update', 'isdisjoint', 'issubset', 'issuperset', 'pop', 'remove', 'symmetric_difference', 'symmetric_difference_update', 'union', 'update']
>>> s.add('python')
>>> s
{1, 2, 3, 4, 'python'}
>>> s.pop()
1
>>> s
{2, 3, 4, 'python'}
>>> s.pop()
2
>>> s.remove(4)
>>> s
{3, 'python'}
>>> s.discard(3)
>>> s
{'python'}
>>> s.discard(3)
>>> s.remove(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 3

不可变集合

1
2
3
4
5
6
>>> f_set = frozenset('qiwsir')
>>> f_set
frozenset({'w', 'r', 'i', 's', 'q'})
>>> dir(f_set)
['__and__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'copy', 'difference', 'intersection', 'isdisjoint', 'issubset', 'issuperset', 'symmetric_difference', 'union']
>>>

集合的特点

浅拷贝 深拷贝

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
27
28
29
>>> b1 = ['name',123,['python','php']]
>>> b2 = b1.copy()
>>> b2
['name', 123, ['python', 'php']]
>>> b1 is b2
False
>>> b1[2][0]
'python'
>>> b1[2][0] = 999
>>> b1[2][0]
999
>>> b2[2][0]
999
>>> b1
['name', 123, [999, 'php']]
>>> b2
['name', 123, [999, 'php']]
>>> import copy
>>> b1
['name', 123, [999, 'php']]
>>> b3 = copy.deepcopy(b1)
>>> b3
['name', 123, [999, 'php']]
>>> b1[2][0] = 'java'
>>> b1
['name', 123, ['java', 'php']]
>>> b3
['name', 123, [999, 'php']]
>>>
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
27
28
29
30
31
32
33
34
35
36
37
38
>>> s = set('python')
>>> s
{'o', 'n', 'p', 't', 'y', 'h'}
>>> 'a' in s
False
>>> 'y' in s
True
>>> len(s)
6
>>> a = set([1,2,3,4,5])
>>> b = set([1,2,3])
>>> a.issu
a.issubset( a.issuperset(
>>> a.issu
a.issubset( a.issuperset(
>>> a.issuperset(a)
True
>>> a.issuperset(b)
True
>>> b.issubset(a)
True
>>> a
{1, 2, 3, 4, 5}
>>> b
{1, 2, 3}
>>> a | b
{1, 2, 3, 4, 5}
>>> a.union(b)
{1, 2, 3, 4, 5}
>>> a & b
{1, 2, 3}
>>> a.intersection(b)
{1, 2, 3}
>>> a - b
{4, 5}
>>> a.difference(b)
{4, 5}
>>>

例子

1
2
3
4
5
6
7
8
9
10
11
#coding: utf-8
'''
编写程序,根据输入的半径,计算圆的面积
'''
import math
r = float(input('enter the radius of circle:'))
area = math.pi * r * r
print('the area is :', round(area,2))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#coding: utf-8
'''
编写程序,利用“凯撒密码”方案,实现对用户输入文字的加密操作。
凯撒密码(英语:caesar cipher),是一种最简单且最广为人知的加密技术。它是一种替换加密的技术,明文中的所有字母都在字母
表上向后(或向前)按照一个固定数目进行偏移后被替换成密文。例如:当偏移量是3的时候,所有的字母A将被替换成D,B变成E,以此
类推。
'''
letter = input('please input an english letter: ')
n = 3
pwd = ord(letter) + n
pwd_letter = chr(pwd)
print(letter,"===>",pwd_letter)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#coding:utf-8
'''
编写程序,实现对输入字符串的大小写字母翻转
(即大写变小写、小写变大写)操作。
'''
word = input('please input an english word:')
new_lst = []
for i in word:
if i.islower():
new_lst.append(i.upper())
else:
new_lst.append(i.lower())
new_word = "".join(new_lst)
print(word,"==>",new_word)

布尔类型

True和Flase的类型:bool
True、False之间的四则运算:True:1,False:0

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
>>> type(True)
<class 'bool'>
>>> bool(1)
True
>>> bool(0)
False
>>> bool()
False
>>> bool('')
False
>>> bool(' ')
True
>>> bool([])
False
>>> bool(dict())
False
>>> bool(False)
False
>>>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
>>> False and 3
False
>>> 0 and 3
0
>>> 3 > 2 and 4 > 3
True
>>> 3 > 2 and 4
4
>>> 3 or 0
3
>>> 0 or 3
3
>>> not 3
False
>>>

简单语句

  • import module
  • import module as new_name
  • from module import function
  • from module import function as new_name
  • from module import *

条件语句

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#coding:utf-8
import random
import math
n = random.randint(1,10)
if n > math.pi:
perimeter = n * math.pi
area = math.pi * (n/2) ** 2
else:
perimeter = 2 * n * math.pi
area = math.pi * pow(n,2)
print("random n is: ",n)
print("perimeter is",round(perimeter,2))
print("area is: ",round(area,2))

for循环语句

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#encoding:utf-8
import random
lst = []
for i in range(100):
n = random.randint(1,10)
lst.append(n)
d = {}
for n in lst:
if n in d:
d[n] += 1
else:
d[n] = 1
print(d)

几个常用函数

1
2
3
4
5
6
>>> r = range(4)
>>> r
range(0, 4)
>>> type(r)
<class 'range'>
>>>
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
27
28
29
30
>>> a = 'qiwsir'
>>> b = 'python'
>>> z = zip(c,d)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'c' is not defined
>>> z = zip(a,b)
>>> z
<zip object at 0x10867f8c8>
>>> type(z)
<class 'zip'>
>>> list(z)
[('q', 'p'), ('i', 'y'), ('w', 't'), ('s', 'h'), ('i', 'o'), ('r', 'n')]
>>>
>>> c = [1,2,3,4,5]
>>> d = [5,6,7,8,9,10]
>>> list(zip(c,d))
[(1, 5), (2, 6), (3, 7), (4, 8), (5, 9)]
>>>
>>> c =[1,2,3,4,5]
>>> d =[5,6,7,8,9]
>>> r2 = []
>>> for x,y in zip(c,d):
... r2.append(x+y)
...
>>> r2
[6, 8, 10, 12, 14]
>>>
1
2
3
4
5
6
7
8
9
10
11
12
>>> s = ['one','two','three','four']
>>> list(enumerate(s))
[(0, 'one'), (1, 'two'), (2, 'three'), (3, 'four')]
>>>
>>> lst = [1,5,3,20,6,2,7]
>>> for i,ele in enumerate(lst):
... if ele % 2 == 0:
... lst[i] = 'even'
...
>>> lst
[1, 5, 3, 'even', 'even', 'even', 7]
>>>
1
2
3
4
5
>>> [i**2 for i in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> [i for i in range(100) if i%3==0]
[0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99]
>>>

while循环语句

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#coding: utf-8
'''
'''
a = 0
while a < 3:
s = input('input your lang:')
if s == 'python':
print("your lang is {0}".format(s))
break
else:
a += 1
print("a=",a)
print('the end a:',a)

函数

1
2
def function_name(x,y,x):
do something return object

嵌套函数和装饰器

变量作用域问题 global nonlocal

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
>>>
>>> a = 1
>>> def f2():
... print(a+1)
...
>>> f2()
2
>>> def f3():
... a = a + 1
... print(a)
...
>>> f3()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in f3
UnboundLocalError: local variable 'a' referenced before assignment
>>> def f3():
... global a
... a = a + 1
... print(a)
...
>>> f3()
2
>>> a
2
>>> def foo():
... a = 1
... def bar():
... a = a +1
... print(a)
... bar()
...
>>> foo()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 6, in foo
File "<stdin>", line 4, in bar
UnboundLocalError: local variable 'a' referenced before assignment
>>> def foo():
... a = 1
... def bar():
... nonlocal a
... a = a +1
... print(a)
... bar()
...
>>> foo()
2
>>>

装饰器

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
27
28
#coding: utf-8
# def book(name):
# return "the name of my book is {0}".format(name)
# def p_deco(func):
# def wrapper(name):
# return "<p>{0}<p>".format(func(name))
# return wrapper
# zhangsan = p_deco(book)
# py_book = zhangsan('python大学实用教程')
# print(py_book)
def p_deco(func):
def wrapper(name):
return "<p>{0}<p>".format(func(name))
return wrapper
@p_deco
def book(name):
return "the name of my book is {0}".format(name)
py_book = book('python大学实用教程')
print(py_book)
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
27
28
29
30
31
32
33
34
35
#coding: utf-8
import time
from functools import wraps
def timethis(func):
@wraps(func)
def wrapper(*args,**kwargs):
start = time.time()
func(*args,**kwargs)
end = time.time()
print(func.__name__,end - start)
return wrapper
@timethis
def countdown(n):
while n > 0:
n -= 1
@timethis
def test_list_append():
lst = []
for i in range(1000000):
lst.append(i)
@timethis
def test_list_compare():
[i for i in range(1000000)]
countdown(1000000)
countdown(100000000)
test_list_append()
test_list_compare()

特殊函数

lambda

map

filter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#coding:utf-8
class SuperMan:
'''
A class of superman
'''
def __init__(self,name):
self.name = name
self.gender = 1
self.singel = False
self.illness = False
def nine_negative_kungfu(self):
return "Ya! You have to die."
guojing:SuperMan
guojing = SuperMan('guojing')
print(guojing.name)
print(guojing.gender)
print(guojing.nine_negative_kungfu())

属性

理解类属性和实例属性、

  • 类属性,又称静态属性
  • 只有通过类才能修改
  • 实例也拥有类属性,但不能修改类属性
  • 实例的dict显示当前实例的所有属性

理解self的作用

  • 类中的方法,如无特别规定,都是以self作为第一参数
  • self引用当前实例
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
#coding:utf-8
import datetime
from dateutil import rrule
class BetDate:
def __init__(self,start_date,stop_date):
self.star = datetime.datetime.strptime(start_date,"%Y,%m,%d")
self.stop = datetime.datetime.strptime(stop_date,"%Y,%m,%d")
def days(self):
d = self.stop - self.star
return d.days if d.days >0 else False
def weeks(self):
weeks = rrule.rrule(rrule.WEEKLY,dtstart=self.star,until=self.stop)
return weeks.count()
fir_twe = BetDate("2019,5,1","2019,11,25")
d = fir_twe.days()
w = fir_twe.weeks()
print("between 2019-5-1,2019-11-25:")
print("days are:",d)
print("weeks are:",w)

方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#coding:utf-8
class Date(object):
def __init__(self,year=0,month=0,day=0):
self.year = year
self.month = month
self.day = day
@classmethod
def from_string(cls,date_as_string):
year,month,day = map(int,date_as_string.split('-'))
date1 = cls(year,month,day)
return date1
@staticmethod
def is_date_valid(date_as_string):
year,month,day = map(int,date_as_string.split('-'))
return day <= 31 and month <= 12 and year <= 2038
d = Date.from_string('2019-11-11')
is_date = Date.is_date_valid('2019-11-11')
print(is_date)

继承

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
#coding:utf-8
class Person:
def __init__(self,name,age):
self.name = name
self.age = age
def get_name(self):
return self.name
def get_age(self):
return self.age
class Student(Person):
def __init__(self,school,name,age):
self.school = school
super().__init__(name,age)
def grade(self,n):
print("{0}'s grade is {1}".format(self.name,str(n)))
stu1 = Student('Soochow','galileo',27)
stu1.grade(99)
print(stu1.get_name())
print(stu1.get_age())

标准库和第三方包

引入和使用标准库

安装、引入和使用第三方包