print(1)
1
print("we're going to do something")
we're going to do something
print('we\'re going to do something')
we're going to do something
print('apple'+'car')
applecar
print('apple'+'4')
apple4
print(1+2)
3
print(int('1')+2)
3
print(float('1.2')+2)
3.2
1+1
2
1-1
0
2*2
4
2**2
4
平方运算,不能是2^2
8%3
2
求余运算
9//4
2
取整运算
apple = 1
print(apple)
1
apple = 'iphone 7 plus'
print(apple)
iphone 7 plus
a,b,c = 11,12,13
print(a,b,c)
11 12 13
执行循环,直到符合条件时结束。
while condition:
expressions
condition = 0
while condition<10:
print(condition)
condition = condition+1
#没有condition++这种写法,还可以写成condition += 1, ++condition
0
1
2
3
4
5
6
7
8
9
在使用 while 句法的时候一定要注意在循环内部一定要修改判断条件的值,否则程序的 while 部分 将永远执行下去。
while True:
print(“I’m True”)
如果这样做的话,程序将一直打印出 I’m True, 要停止程序,使用 ctrl + c 终止程序。
for item in sequence:
expressions
item 是在for这里新定义的变量, sequence是之前定义好的数组/列表
example_list = [1,2,3,4,5,6,7,12,543,876,12,3,2,5]
for i in example_list:
print(i)
1
2
3
4
5
6
7
12
543
876
12
3
2
5
python是一个使用缩进表示程序的结构,冒号后会自动缩进一个Tab
example_list = [1,2,3,4,5,6,7,12,543,876,12,3,2,5]
for i in example_list:
print(i)
print('inner of for')
print('outer of for')
1
inner of for
2
inner of for
3
inner of for
4
inner of for
5
inner of for
6
inner of for
7
inner of for
12
inner of for
543
inner of for
876
inner of for
12
inner of for
3
inner of for
2
inner of for
5
inner of for
outer of for
if condition:
expressions
x = 1
y = 2
z = 3
if x < y:
print('x is less than y')
x is less than y
if x < y < z:
print('x is less than y, and y is less than z')
x is less than y, and y is less than z
python特有的写法,意思是x < y and y < z,最好不要这么写。
注意:==是判断,=是赋值
if condition:
true_expressions
else:
false_expressions
x = 1
y = 2
z = 3
if x > y:
print('x is greater than y')
else:
print('x is less or equal to y')
x is less or equal to y
var= var1 if condition else var2
worked = True
result = 'done' if worked else 'not yet'
print(result)
done
if condition1:
true1_expressions
elif condition2:
true2_expressions
elif condtion3:
true3_expressions
elif ...
...
else:
else_expressions
x = 4
y = 2
z = 3
if x > 1:
print ('x > 1')
elif x < 1:
print('x < 1')
else:
print('x = 1')
print('finish')
x > 1
finish
def function_name(parameters):
expressions
def function():
print('This is a function')
a = 1+2
print(a)
function()
This is a function
3
def function_name(parameters):
expressions
def func(a, b):
c = a+b
print('the c is ', c)
func(1, 2)
the c is 3
def function_name(para_1,...,para_n=defau_n,..., para_m=defau_m):
expressions
def sale_car(price, color='red', brand='carmy', is_second_hand=True):
print('price', price,
'color', color,
'brand', brand,
'is_second_hand', is_second_hand,)
sale_car(100)
price 100 color red brand carmy is_second_hand True
if __name__ == '__main__':
#code_here
这里的code可以写入该函数的测试代码,当脚本被执行时,if判断为true,执行测试代码;当外部调用该脚本,if判断为false,不执行测试代码。
可变参数是指可迭代参数,避免了对于list的传参,写的时候放在特定参数和默认参数之后。
def report(name, *grades):
total_grade = 0
for grade in grades:
total_grade += grade
print(name, 'total grade is ', total_grade)
report('Mike', 8, 9, 10)
Mike total grade is 27
关键字参数可以传入0个或者任意个含参数名的参数,这些参数名在函数定义中并没有出现,这些参数在函数内部自动封装成一个字典(dict).写的时候放在所有参数最最后。
def portrait(name, **kw):
print('name is', name)
for k,v in kw.items():
print(k, v)
portrait('Mike', age=24, country='China', education='bachelor')
name is Mike
age 24
country China
education bachelor
def函数中定义的变量就是局部变量,只能在函数中使用
那如何在外部也能调用一个在局部里修改了的全局变量呢. 首先我们在外部定义一个全局变量 a=None, 然后再 fun() 中声明 这个 a 是来自外部的 a. 声明方式就是 global a. 然后对这个外部的 a 修改后, 修改的效果会被施加到外部的 a 上.
APPLE = 100 # 全局变量
a = None
def fun():
global a # 使用之前在全局里定义的 a
a = 20 # 现在的 a 是全局变量了
return a+100
print(APPLE) # 100
print('a past:', a) # None
b=fun()
print('a now:', a) # 20
print(b)
100
a past: None
a now: 20
120
外部模块就是在你 import 什么东西去python 脚本的时候会用到的.
安装语句:pip install 模块名
更新语句:pip install -u 模块名
text='This is my first test.\nThis is the second line.\nThis the third line'
print(text) # 输入换行命令\n,要注意斜杆的方向。注意换行的格式和c++一样
This is my first test.
This is the second line.
This the third line
open 的第一个参数为文件名和路径 ‘my file.txt’, 第二个参数为将要以什么方式打开它, 比如 w 为可写方式. 如果计算机没有找到 ‘my file.txt’ 这个文件, w 方式能够创建一个新的文件, 并命名为 my file.txt
my_file=open('my file.txt','w') #用法: open('文件名','形式'), 其中形式有'w':write;'r':read.
my_file.write(text) #该语句会写入先前定义好的 text
my_file.close() #关闭文件
text='\tThis is my first test.\n\tThis is the second line.\n\tThis is the third line'
print(text) #延伸 使用 \t 对齐
This is my first test.
This is the second line.
This is the third line
append_text='\nThis is appended file.' # 为这行文字提前空行 "\n"
my_file=open('my file.txt','a') # 'a'=append 以增加内容的形式打开
my_file.write(append_text)
my_file.close()
file= open('my file.txt','r')
content=file.read()
print(content)
This is my first test.
This is the second line.
This the third line
This is appended file.
file= open('my file.txt','r')
content=file.readline() # 读取第一行
print(content)
This is my first test.
file= open('my file.txt','r')
content=file.readlines() # python_list 形式
print(content)
['This is my first test.\n', 'This is the second line.\n', 'This the third line\n', 'This is appended file.']
class后面可以定义属性、函数
class Calculator: #首字母要大写,冒号不能缺
name='Good Calculator' #该行为class的属性
price=18
def add(self,x,y):
print(self.name)
result = x + y
print(result)
def minus(self,x,y):
result=x-y
print(result)
def times(self,x,y):
print(x*y)
def divide(self,x,y):
print(x/y)
cal=Calculator()
cal.name
'Good Calculator'
cal.price
18
cal.add(10,20)
Good Calculator
30
cal.minus(10,20)
-10
cal.times(10,20)
200
cal.divide(10,20)
0.5
init功能
__init__可以理解成初始化class的变量,取自英文中initial 最初的意思.可以在运行时,给初始值附值:
class Calculator:
name='good calculator'
price=18
def __init__(self,name,price,height,width,weight): # 注意,这里的下划线是双下划线
self.name=name
self.price=price
self.h=height
self.wi=width
self.we=weight
c=Calculator('bad calculator',18,17,16,15)
c.name
'bad calculator'
c.price
18
c.h
17
c.wi
16
c.we
15
设置属性的默认值, 直接在def里输入即可,如下:
class Calculator:
name='good calculator'
price=18
def __init__(self,name,price,hight=10,width=14,weight=16): #后面三个属性设置默认值,查看运行
self.name=name
self.price=price
self.h=hight
self.wi=width
self.we=weight
variable=input() 表示运行后,可以在屏幕中输入一个数字,该数字会赋值给自变量。
a_input=input('please input a number:')
print('this number is:',a_input)
please input a number:1
this number is: 1
a_input=int(input('please input a number:'))#注意这里要定义一个整数型
if a_input==1:
print('This is a good one')
elif a_input==2:
print('See you next time')
else:
print('Good luck')
please input a number:2
See you next time
score=int(input('Please input your score: \n'))
if score>=90:
print('Congradulation, you get an A')
elif score >=80:
print('You get a B')
elif score >=70:
print('You get a C')
elif score >=60:
print('You get a D')
else:
print('Sorry, You are failed ')
Please input your score:
99
Congradulation, you get an A
叫做 tuple,用小括号、或者无括号来表述,是一连串有顺序的数字。
a_tuple = (12, 3, 5, 15 , 6)
another_tuple = 12, 3, 5, 15 , 6
而list是以中括号来命名的:
a_list = [12, 3, 67, 7, 82]
* 他们的元素可以一个一个地被迭代、输出、运用、定位取值:
for content in a_list:
print(content)
12
3
67
7
82
for content_tuple in a_tuple:
print(content_tuple)
12
3
5
15
6
for index in range(len(a_list)):
print("index = ", index, ", number in list = ", a_list[index])
index = 0 , number in list = 12
index = 1 , number in list = 3
index = 2 , number in list = 67
index = 3 , number in list = 7
index = 4 , number in list = 82
for index in range(len(a_tuple)):
print("index = ", index, ", number in tuple = ", a_tuple[index])
index = 0 , number in tuple = 12
index = 1 , number in tuple = 3
index = 2 , number in tuple = 5
index = 3 , number in tuple = 15
index = 4 , number in tuple = 6
a = [1,2,3,4,1,1,-1]
a.append(0) # 在a的最后面追加一个0
print(a)
[1, 2, 3, 4, 1, 1, -1, 0]
a = [1,2,3,4,1,1,-1]
a.insert(1,0) # 在位置1处添加0
print(a)
[1, 0, 2, 3, 4, 1, 1, -1]
a = [1,2,3,4,1,1,-1]
a.remove(2) # 删除列表中第一个出现的值为2的项
print(a)
[1, 3, 4, 1, 1, -1]
a = [1,2,3,4,1,1,-1]
print(a[0]) # 显示列表a的第0位的值
# 1
print(a[-1]) # 显示列表a的最末位的值
# -1
print(a[0:3]) # 显示列表a的从第0位 到 第2位(第3位之前) 的所有项的值
# [1, 2, 3]
print(a[5:]) # 显示列表a的第5位及以后的所有项的值
# [1, -1]
print(a[-3:]) # 显示列表a的倒数第3位及以后的所有项的值
# [1, 1, -1]
1
-1
[1, 2, 3]
[1, -1]
[1, 1, -1]
打印例表中某个值的索引
a = [1,2,3,4,1,1,-1]
print(a.index(2)) # 显示列表a中第一次出现的值为2的项的索引
1
统计列表中某值出现的次数
a = [4,1,2,3,4,1,1,-1]
print(a.count(-1))
1
a = [4,1,2,3,4,1,1,-1]
a.sort() # 默认从小到大排序
print(a)
# [-1, 1, 1, 1, 2, 3, 4, 4]
a.sort(reverse=True) # 从大到小排序
print(a)
# [4, 4, 3, 2, 1, 1, 1, -1]
[-1, 1, 1, 1, 2, 3, 4, 4]
[4, 4, 3, 2, 1, 1, 1, -1]
a = [1,2,3,4,5] # 一行五列
multi_dim_a = [[1,2,3],
[2,3,4],
[3,4,5]] # 三行三列
print(a[1])
# 2
print(multi_dim_a[0][1])
# 2
2
2
如果说List是有顺序地输出输入的话,那么字典的存档形式则是无需顺序的。
在字典中,有key和 value两种元素,每一个key对应一个value, key是名字, value是内容。
数字和字符串都可以当做key或者value, 在同一个字典中, 并不需要所有的key或value有相同的形式。
这样说, List 可以说是一种key维有序数列的字典。
a_list = [1,2,3,4,5,6,7,8]
d1 = {'apple':1, 'pear':2, 'orange':3}
d2 = {1:'a', 2:'b', 3:'c'}
d3 = {1:'a', 'b':2, 'c':3}
print(d1['apple']) # 1
print(a_list[0]) # 1
del d1['pear'] # 删除pear
print(d1) # {'orange': 3, 'apple': 1}
d1['b'] = 20 # 没有d1中没有b,就直接创建
print(d1) # {'orange': 3, 'b': 20, 'apple': 1} 发现没?无序的!
1
1
{'apple': 1, 'orange': 3}
{'apple': 1, 'orange': 3, 'b': 20}
以上的例子可以对列表中的元素进行增减。在打印出整个列表时,可以发现各个元素并没有按规律打印出来,进一步验证了字典是一个无序的容器。
def func():
return 0
d4 = {'apple':[1,2,3], 'pear':{1:3, 3:'a'}, 'orange':func}
print(d4['pear'][3]) # a
a
方法一:import 模块名:python自带或自己安装的
方法二:import 模块名 as 自定义名
from 模块名 import 模块名.功能名:只导入想要的功能
from 模块名 import * :导入该模块所有功能
a=True
while a:
b= input('type somesthing')
if b=='1':
a= False
else:
pass
print("still in while")
print ('finish run')
type somesthing1
still in while
finish run
while True:
b= input('type somesthing:')
if b=='1':
break
else:
pass
print('still in while')
print ('finish run')
type somesthing:1
finish run
while True:
b=input('input somesthing:')
if b=='1':
continue
else:
pass
print('still in while' )
print ('finish run')
input somesthing:1
input somesthing:2
still in while
input somesthing:3
still in while
try:
file=open('eeee.txt','r') #会报错的代码
except Exception as e: # 将报错存储在 e 中
print(e)
会使用到循环语句。首先报错:没有这样的文件No such file or directory. 然后决定是否输入y, 输入y以后,系统就会新建一个文件(要用写入的类型),再次运行后,文件中就会写入ssss
try:
file=open('eeee.txt','r+')
except Exception as e:
print(e)
response = input('do you want to create a new file:')
if response=='y':
file=open('eeee.txt','w')
else:
pass
else:
file.write('ssss')
file.close()
a=[1,2,3]
b=[4,5,6]
ab=zip(a,b)
print(list(ab)) #需要加list来可视化这个功能
for i,j in zip(a,b):
print(i/2,j*2)
[(1, 4), (2, 5), (3, 6)]
0.5 8
1.0 10
1.5 12
fun = lambda x,y : x+y, 冒号前的x,y为自变量,冒号后x+y为具体运算。
fun= lambda x,y:x+y
x=int(input('x=')) #这里要定义int整数,否则会默认为字符串
y=int(input('y='))
print(fun(x,y))
x=6
y=5
11
def fun(x,y):
return (x+y)
list(map(fun,[1],[2]))
[3]
list(map(fun,[1,2],[3,4]))
[4, 6]
import copy
a=[1,2,3]
b=a
id(a)
2216177872064
id(b)
2216177872064
b[0]=222222
print(a,b) # ab的值会同时改变
[222222, 2, 3] [222222, 2, 3]
import copy
a =[1,2,3]
c=copy.copy(a) #拷贝了a的外围对象本身
print(c)
[1, 2, 3]
id(c)
2216177618560
id(a)
2216177645568
c[0]=222222
print(a,c) #a的值不改变
[1, 2, 3] [222222, 2, 3]
a=[1,2,[3,4]] #第三个值为列表[3,4],即内部元素
d=copy.copy(a) #浅拷贝a中的[3,4]内部元素的引用,非内部元素对象的本身
id(a)==id(d)
False
id(a[2])==id(d[2])
True
a[2][0]=3333 #改变a中内部原属列表中的第一个值
d #这时d中的列表元素也会被改变
[1, 2, [3333, 4]]
e=copy.deepcopy(a) #e为深拷贝了a
a[2][0]=333 #改变a中内部元素列表第一个的值
e[#因为时深拷贝,这时e中内部元素[]列表的值不会因为a中的值改变而改变
[1, 2, [3333, 4]]
多线程 Threading 是一种让程序拥有分身效果. 能同时处理多件事情. 一般的程序只能从上到下一行行执行代码, 不过 多线程 (Threading) 就能打破这种限制. 让你的程序鲜活起来.
“把一个工作分成5人,5个人同时做一份工作”
我们在多线程 (Threading) 里提到过, 它是有劣势的, GIL 让它没能更有效率的处理一些分摊的任务. 而现在的电脑大部分配备了多核处理器, 多进程 Multiprocessing 能让电脑更有效率的分配任务给每一个处理器, 这种做法解决了多线程的弊端. 也能很好的提升效率.
Tkinter 是使用 python 进行窗口视窗设计的模块. 简单的构造, 多平台, 多系统的兼容性, 能让它成为让你快速入门定制窗口文件的好助手. 它在 python 窗口视窗模块中是一款简单型的. 所以用来入门, 熟悉 窗口视窗的使用, 非常有必要.
pickle 是一个 python 中, 压缩/保存/提取 文件的模块. 最一般的使用方式非常简单. 比如下面就是压缩并保存一个字典的方式. 字典和列表都是能被保存的.
import pickle
a_dict = {'da': 111, 2: [23,1,4], '23': {1:2,'d':'sad'}}
# pickle a variable to a file
file = open('pickle_example.pickle', 'wb')
pickle.dump(a_dict, file)
file.close()
Set 最主要的功能就是寻找一个句子或者一个 list 当中不同的元素.
char_list = ['a', 'b', 'c', 'c', 'd', 'd', 'd']
sentence = 'Welcome Back to This Tutorial'
print(set(char_list))
{'b', 'd', 'c', 'a'}
print(set(sentence))
{'e', 'W', 'i', 'B', 'c', 'm', 't', 'o', 's', 'r', ' ', 'u', 'l', 'T', 'k', 'a', 'h'}
print(set(char_list+ list(sentence)))
{'r', 'e', 'i', 'B', 'm', 'b', 'k', 'c', 't', 's', ' ', 'u', 'l', 'T', 'W', 'o', 'd', 'a', 'h'}
unique_char = set(char_list)
print(unique_char.difference({'a', 'e', 'i'}))
{'b', 'd', 'c'}
正则表达式 (Regular Expression) 又称 RegEx, 是用来匹配字符的一种工具. 在一大串字符中寻找你需要的内容. 它常被用在很多方面, 比如网页爬虫, 文稿整理, 数据筛选等等.
# matching string
pattern1 = "cat"
pattern2 = "bird"
string = "dog runs to cat"
print(pattern1 in string) # True
print(pattern2 in string) # False
True
False
import re
# regular expression
pattern1 = "cat"
pattern2 = "bird"
string = "dog runs to cat"
print(re.search(pattern1, string)) # 12-15是cat
print(re.search(pattern2, string)) # None
None
# multiple patterns ("run" or "ran")
ptn = r"r[au]n" # start with "r" means raw string [au]表示两种都可以
print(re.search(ptn, "dog runs to cat"))
print(re.search(r"r[A-Z]n", "dog runs to cat")) # None
print(re.search(r"r[a-z]n", "dog runs to cat")) # <_sre.SRE_Match object; span=(4, 7), match='run'>
print(re.search(r"r[0-9]n", "dog r2ns to cat")) # <_sre.SRE_Match object; span=(4, 7), match='r2n'>
print(re.search(r"r[0-9a-z]n", "dog runs to cat")) # <_sre.SRE_Match object; span=(4, 7), match='run'>
None
除了自己定义规则, 还有很多匹配的规则时提前就给你定义好了的. 下面有一些特殊的匹配类型给大家先总结一下, 然后再上一些例子.
\d : 任何数字
\D : 不是数字
\s : 任何 white space, 如 [\t\n\r\f\v]
\S : 不是 white space
\w : 任何大小写字母, 数字和 _ [a-zA-Z0-9_]
\W : 不是 \w
\b : 空白字符 (只在某个字的开头或结尾)
\B : 空白字符 (不在某个字的开头或结尾)
\\ : 匹配 \
. : 匹配任何字符 (除了 \n)
^ : 匹配开头
$ : 匹配结尾
? : 前面的字符可有可无
# \d : decimal digit
print(re.search(r"r\dn", "run r4n"))
# \D : any non-decimal digit
print(re.search(r"r\Dn", "run r4n"))
# \s : any white space [\t\n\r\f\v]
print(re.search(r"r\sn", "r\nn r4n"))
# \S : opposite to \s, any non-white space
print(re.search(r"r\Sn", "r\nn r4n"))
# \w : [a-zA-Z0-9_]
print(re.search(r"r\wn", "r\nn r4n"))
# \W : opposite to \w
print(re.search(r"r\Wn", "r\nn r4n"))
# \b : empty string (only at the start or end of the word)
print(re.search(r"\bruns\b", "dog runs to cat"))
# \B : empty string (but not at the start or end of a word)
print(re.search(r"\B runs \B", "dog runs to cat"))
# \\ : match \
print(re.search(r"runs\\", "runs\ to me"))
# . : match anything (except \n)
print(re.search(r"r.n", "r[ns to me"))
# ^ : match line beginning
print(re.search(r"^dog", "dog runs to cat"))
# $ : match line ending
print(re.search(r"cat$", "dog runs to cat"))
print(re.search(r"Mon(day)?", "Monday"))
print(re.search(r"Mon(day)?", "Mon"))
如果一个字符串有很多行, 我们想使用 ^ 形式来匹配行开头的字符, 如果用通常的形式是不成功的. 比如下面的 I 出现在第二行开头, 但是使用 r"^I" 却匹配不到第二行, 这时候, 我们要使用 另外一个参数, 让 re.search() 可以对每一行单独处理. 这个参数就是 flags=re.M, 或者这样写也行 flags=re.MULTILINE.
string = """
dog runs to cat.
I run to dog.
"""
print(re.search(r"^I", string)) # None
print(re.search(r"^I", string, flags=re.M)) # <_sre.SRE_Match object; span=(18, 19), match='I'>
None
如果我们想让某个规律被重复使用, 在正则里面也是可以实现的, 而且实现的方式还有很多. 具体可以分为这三种:
*: 重复零次或多次
+: 重复一次或多次
{n, m} : 重复 n 至 m 次
{n} : 重复 n 次
# * : occur 0 or more times
print(re.search(r"ab*", "a")) # <_sre.SRE_Match object; span=(0, 1), match='a'>
print(re.search(r"ab*", "abbbbb")) # <_sre.SRE_Match object; span=(0, 6), match='abbbbb'>
# + : occur 1 or more times
print(re.search(r"ab+", "a")) # None
print(re.search(r"ab+", "abbbbb")) # <_sre.SRE_Match object; span=(0, 6), match='abbbbb'>
# {n, m} : occur n to m times
print(re.search(r"ab{2,10}", "a")) # None
print(re.search(r"ab{2,10}", "abbbbb")) # <_sre.SRE_Match object; span=(0, 6), match='abbbbb'>
None
None
match = re.search(r"(\d+), Date: (.+)", "ID: 021523, Date: Feb/12/2017")
#()表示组,\d表示找数字,+表示重复,然后找Date后面所有内容
print(match.group()) # 021523, Date: Feb/12/2017
print(match.group(1)) # 021523
print(match.group(2)) # Date: Feb/12/2017
021523, Date: Feb/12/2017
021523
Feb/12/2017
match = re.search(r"(?P\d+), Date: (?P.+)" , "ID: 021523, Date: Feb/12/2017")
# ?P<名字> 就给这个组定义了一个名字. 然后就能用这个名字找到这个组的内容.
print(match.group('id')) # 021523
print(match.group('date')) # Date: Feb/12/2017
021523
Feb/12/2017
前面我们说的都是只找到了最开始匹配上的一项而已, 如果需要找到全部的匹配项, 我们可以使用 findall 功能. 然后返回一个列表.
# findall
print(re.findall(r"r[ua]n", "run ran ren")) # ['run', 'ran']
# | : or
print(re.findall(r"(run|ran)", "run ran ren")) # ['run', 'ran'] |是或
['run', 'ran']
['run', 'ran']
print(re.sub(r"r[au]ns", "catches", "dog runs to cat")) # dog catches to cat
dog catches to cat
print(re.split(r"[,;\.]", "a;b,c.d;e")) # ['a', 'b', 'c', 'd', 'e']
['a', 'b', 'c', 'd', 'e']
比如想获取一句话中所有的单词. 比如 “a is b”.split(" "), 这样它就会产生一个列表来保存所有单词.
compiled_re = re.compile(r"r[ua]n")
print(compiled_re.search("dog ran to cat")) # <_sre.SRE_Match object; span=(4, 7), match='ran'>