6 For 循环
example_list = [1,20,3,64,5,34,63]
#for i in example_list:
# print(i) # 4 space
# print('inner of for loop')
# 注释
# for windows control +[
# for mac commend +[
print('out of for loop')
for i in range(1,7,1):
print(i)
print(example_list[i])
#range(1,3) #1,2,3
#output 1,2. 注意此处的range
10、定义函数
def add(a,b):
#四个空格才是函数以内的东西
print('this is a add function')
c=a+b
print(c)
#直接在脚本里面调用函数
add(1,2)
11 函数默认参数
def sale_car(price, color='red', brand='carmy', is_second_hand=True):
print('price:',price,
'color:',color,
'is_second_hand:',is_second_hand,
)
sale_car(1000,'red','carmy',True)
sale_car(1000)
sale_car(1000,'blue')
13、全局变量和局部变量
a = None
APPLE = 100 #函数外面定义。 global变量通常全部字母大写
def fun():
global a #需要两次声明,此处表示使用全局变量
a = 10; #局部变量
print(a)
return a+100
# fun()
# print(fun()) #输出函数返回的那个值
print(APPLE)
print('a past=',a) #错误
print(fun())
print('a now=',a)
14、模块安装 pip pip3 pip3.7
pip install numpy
pip uninstall numpy
指定安装版本
pip uninstall numpy-1.10.2
升级(-U update)
pip install -U numpy
15-16、文件的读写
text ='This is my first line.\n This is next line.\n This is the last line.'
print(text)
my_file = open('my file.txt','w')
my_file.write(text)
my_file.close()
文件追加 my_file = open('my file.txt','a')
17、读取文件
file = open('my file.txt','r')
#是把文件存到file里面,不是把文件的内容存到file里面。相当于一个指针。
file = open('my file.txt','r') # 获取文件对象
content = file.read()
print(content)
#同样可以读取excel表格,根据读取的方式不同,同样可以存到python的list里面
python_list = [1,2,3,’zhagnsna’,’lisi’]
可以用 file.readline() 把读取内容一行一行放到list里面。
file.readlines()
#file = open('my file.txt','r')
#content = file.read()
#print(content)
#一行一行 file.readline()
file = open('my file.txt','r')
content = file.readline()
second_read_line = file.readline()
print(content,second_read_line)
# file.readlines()
file = open('my file.txt','r')
content = file.readlines()
print(content)
Output:['This is my first line.\n', ' This is next line.\n', ' This is the last line.\n', ' \n', ' This is appended line.']
18、class
class Calculator:
name = 'Good calculator'
price = 18
def add(self,x,y): #要加一个self
result =x+y
print(result)
print(self.name)
def minus(self,x,y):
result=x-y
print(result)
def times(self,x,y):
print(x*y)
获得指针 calcul = Calculator()
19、init
类初始化
class Calculator:
name = 'Good calculator'
price = 18
def __init__(self,name2,price2=38,height2=18,width2=20,weight2=22):
self.name = name2
self.price = price2
self.h = height2
self.w = width2
self.we = weight2
20、input
a_input = input('please input:') # return a string '1'
#print('output input:',a_input)
if a_input==1:
print('input is 1')
if a_input=='1':
print('input is "1" ')
else:
print('good')
str() int() 可以强制类型转换
21 元组和列表
tuple list 一连串连续的数字 -----都有序
# tuple list
a_tuple =(1,34,45,12,4)
another_tuple =1,34,45,12,4
a_list = [1,23,44,56,7]
for content in a_list:
print(content)
#range(5) 输出:0,1,2,3,4
for index in range(len(a_list)):
print(index,' ',a_list[index])
最重要的一点是tuple是不可变类型,大小固定,而 list 是可变类型、数据可以动态变化,这种差异使得两者提供的方法、应用场景、性能上都有很大的区别。
22 list append
#append
a = [1,45,6,73,4]
a.append(1)
a.insert(1,90)
print(a)
a.remove(1) #remove 掉一个value 不是index。 移除第一个出现1的值
print(a)
print(a[0])
print(a[-0])
print(a[-1])
print(a[0:3])
print(a[3:-1])
print(a.index(6)) #打印某个值的索引
print(a.count(6)) #出现某个数的次数
print(a)
# 列表排序,覆盖原有的list
#print(a.sort())
a.sort(reverse=True) #上面的语句不行
print(a)
24 多维列表
numpy pandas 模块(库) 提供强大的矩阵,多维列表运算
import numpy
运用到机器学习和神经网络当中
#a = [[1],2,3,4,5]
#print(a[1])
multi_dim_a = [[1,2,3],
[2,3,4],
[3,4,5]]
print(multi_dim_a)
print(multi_dim_a[0])
print(multi_dim_a[0][1])
24、dictionary 字典
列表 按序输出内容
字典 没有顺序
#dictionary 无序
a_list = [1,2,34,5,4,3]
d = {'apple':1,'pear':2,'orange':3}
d2 = {2:'a','c':'d'}
print(d) # 输出
print(d['apple'])
print(d2[2])
del d['pear'] #delete
print(d)
d['b']=20 # add
print(d)
d3 = {'apple':1,'pear':{1:2,3:'a'},'orange':3} #字典的值也可以是字典
print(d3)
print(d3['pear'])
print(d3['pear'][1])
#字典中的值也可以是一个 函数
25 Import
import time
print (time.localtime())
import time as t
print (t.localtime())
#from time import time,localtime #import 子模块
#print(localtime())
from time import * #函数调用时可以省略 time的类名 子模块
print(localtime())
26 导入自己的脚本
确定两个文件在同一个目录下
import def_Function as addf
#def_Function.add(2,3)
addf.add(2,3)
27 continue break
a = True
while a:
b = input('please input:')
if(b=='1'):
a=False
else:
pass #什么都不做
print('Finish')
break
while True:
b = input('please input:')
if(b=='1'):
break
else:
pass #什么都不做
print('still in while')
print('Finish')
28 try 异常处理
#file = open('eee','r') #用只读方式打开文件,必须文件存在
try:
file = open('eee.txt','r')
#file.close()
except Exception as e:
print('no this file')
print(e)
response = input('do you want to creat a new file (y or n):')
if response == 'y':
file = open('eee.txt','w')
file.write('sss')
else:
pass
else:
s = file.read()
print(s)
file.close()
29、map zip lambda
zip可以用作迭代器
a=[1,2,3]
>>> b=[4,5,6]
>>> zip(a,b)
<zip object at 0x0000006578D6E348>
>>> list(zip(a,b))
[(1, 4), (2, 5), (3, 6)]
>>> for i,j in zip(a,b)
SyntaxError: invalid syntax
>>> for i,j in zip(a,b):
print(i,j)
1 4
2 5
3 6
Lambda 和def函数一样,用作一个简单的def
>>> def add(x,y):
return (x+y)
>>> add(1,2)
3
>>> add2 =lambda x,y:x+y
>>> add2(1,2)
3
>>>
像方程一样
>>> map(add,[1],[2])
<map object at 0x0000006578FC5518>
>>> list(map(add,[1],[2]))
[3]
>>> list(map(add,[1,3],[2,5]))
[3, 8]
感觉简化多输入
30 copy
# 需要导入该模块
# id表示索引(内存地址)
在Python中对象的赋值其实就是对象的引用。当创建一个对象,把它赋值给另一个变量的时候,python并没有拷贝这个对象,只是拷贝了这个对象的引用而已。
浅拷贝:拷贝了最外围的对象本身,内部的元素都只是拷贝了一个引用而已。也就是,把对象复制一遍,但是该对象中引用的其他对象我不复制
深拷贝:外围和内部元素都进行了拷贝对象本身,而不是引用。也就是,把对象复制一遍,并且该对象中引用的其他对象我也复制。
>>> import copy
>>> a=[1,2,3]
>>> b=a //相当于两个指针指向同一个对象
>>> id(a)
635659438728
>>> id(b)
635659438728
>>> a[0]=11
>>> b
[11, 2, 3]
>>> c = copy.copy(a) //shallow copy
>>> id(c)
635659439752
>>> c[1]=22222
>>> a
[11, 2, 3]
>>> a=[1,2,[3,4]]
>>> d=copy.copy(a)
>>> id(a)==id(d)
False
>>> id(a[2])==id(d[2])
True
>>> a[0]=1212
>>> d
[1, 2, [3, 4]]
>>> a[2][0]=333
>>> d
[1, 2, [333, 4]]
>>> e =copy.deepcopy(a) //深复制
>>> id(e[2])==id(a[2])
False
>>>
31、thread 多线程
后面有多线程专讲
32、multiprocessing
运用多核心,一般的python只会运用的一个核或者一个线程来处理
多核心可以避免多线程的劣势
33 tkinter 窗口
Python特定的GUI界面
34、pickle 存放数据
保存python运算完的结果 在当地目录,隔一天继续加工
import pickle
a_dict ={'da':111,2:[23,1,3],'23':{1:2,'d':'sad'}}
'''
file = open('pickle_example.pickle','wb') #写入二进制的方式打开,人类看不懂
pickle.dump(a_dict,file) #dump
file.close()
'''
'''
file = open('pickle_example.pickle','rb')
a_dict1=pickle.load(file)
file.close()
print(a_dict1)
'''
with open('pickle_example.pickle','rb') as file: ##不用担心没有关闭文件
a_dict1=pickle.load(file)
print(a_dict1)
35、set 相当于集合 ,所有元素不同,也乱序
Windows下的IDLE的注释快捷键是Alt+3,取消注释是Alt+4
# unexpected eof while parsing 一般是少打了一个括号
char_list = ['a','b','c','c','d','d','d']
print(set(char_list))
print(type(set(char_list)))
print(type({1:2}))
str = 'welcome to New York' #大小写也会区分,空格
print(set(str))
unique = set(char_list)
unique.add('23')
#unique.add(['a','x']) #不可以这样
#print(unique.clear()) #清除
#print(unique.remove('a'))
unique.remove('a') #删除的东西不存在会报错
print(unique)
print(unique.discard('y')) #如删除的东西不存在,也不会报错
set1 = {'a','b','c','d'}
set2 = {'a','e','i'}
print(set1.difference(set2)) #set1有,set2没有
print(set1.intersection(set2)) #交集
36 正则表达式
最主要的处理是文字处理,最最最是网页爬虫
<title>我 是标题</title>