Python 快速入门笔记
- Xu An 2018-3-7
- 1Python print
- # 在 Python3.X 中使用 print()进行输出, 而 2.x 中使用 () 会报错
- print("hello world")
- print('I\'m apple') # 如果全部使用单引号, 则需要在前面加上转义字符 \+ 引号
- print('apple'+'pear')
- print('apple'+str(4)) # 将数字转换为字符串并打印
- print(int("1")+2)# 将字符串转换为整数类型
2pyhton 数值运算
- print(2**2) # 幂运算为 **
- print(10%3) # 取余数为 %
- print(9//4) # 取整数为 //
3 自变量定义
- a,b,c=1,2,3 # 一次定义多个变量
- print(a,b,c)
4while 循环
- condition=1
- while condition<10:
- print(condition)
- condition+=1
5for 循环(相当于迭代器)
- x=1
- y=2
- z=3
- if x<y<z:
- print("x is less than y")
6if-else 语句
- if x<y:
- print("x<y")
- else:
- print("x>y")
- 7if-elif-else
- if x<y:
- print("x<y")
- elif x==y:
- print("")
- else:
- print("x>y")
8 函数定义
- def add(a,b): # 在 python 中定义函数需要使用 def()
- c=a+b
- print("This is the result of the addtion:",c)
- add(1,3)
9 默认函数参数
- def car(price,color='red',second_hand=True):
- # 在函数参数后面加 = 默认值可以完成默认值的赋值
- #bool 类型中的参数需要大写 TrueFlase
- # 需要把默认参数放到变量的后面
- print('price',price,
- 'color',color,
- 'second_hand',second_hand,
- )
- car(1000)
10 变量类型
'''
(1)全局变量
在模块内所有函数外 class 外的变量, 可以被全局共享, 也可以被外部文件共享
全局变量使用时, 需要使用 global 显式声明
如果不将全局变量更新, 一般不需要加 global 声明
如果有重新赋值, 又没有在函数内部使用 global 声明时, 相当于在内部创建了一个同名的局部变量
同名局部变量优先级高于未显式声明的全局变量
- '''
- APPLE=10 # 全局变量需要在函数外部定义
- def test10_01():
- global APPLE # 在函数内部定义全局变量
- APPLE=20 # 在函数内声明的局部变量的优先级高于全局变量
- print(APPLE)
- test10_01()
- '''
(2)局部变量
在函数内 class 方法内(未加 self 修饰)
生命周期在函数执行时, 当函数执行完毕后局部变量消亡
- '''
- def test10_02():
- city='shijiazhuang'
- print(city)
- '''
(3)静态变量(类变量)
通过类名直接访问, 也可以通过实例名直接访问, 变量在类中实例间全局共享
- '''
- # class foo:
- # all=0
- # def add(self):
- # foo.q+=1
- # ins_1=foo() # 实例化对象 1
- # ins_2=foo() # 实例化对象 2
- # print(ins_1.all) #0
- # print(ins_2.all) #0
- # print(foo.all) #0
- # ins_1.add() # 静态全局变量加 1
- '''
(4)实例变量
对于模块来说, 拥有自己的全局变量, 可以供自己内部的类, 函数使用
对于类或者方法来说, 有自己的局部变量, 供自己内部使用
对于类, 有了静态变量, 可以供内部和有继承关系的父子使用
实例间各自的局部变量需要靠动态绑定多态实现
- '''
- class foo_1:
- all=0
- def __init__(self,name):
- self.name=name
- def add(self):
- foo.q+=1
- '''
(5)总结
私有变量: 自己独享的变量, 如函数和方法的局部变量, 实例变量
公有变量: 需要在一定范围内共享, 达到同步的目的, 如模块内的代码共享的全局变量, 类与子类之间共享的静态变量
'''
11 文件写入
- text="This is my first text.\nThis is next line\n" # 使用 \ n 表示换行, 主要换行指令与 C++ 一致
- print(text)
- my_file=open('1.txt','w')
- #open 可以打开一个文件, open(文件路径, 形式), 形式 w 为可写形式, r 为只读形式
- my_file.write(text) # 在文件中写入相应的语句
- my_file.close() # 切记在文件写入后要使用 close 方法关闭文件
- print('Flie writing completed.')
12 文字内容追加
- my_file=open('1.txt','a') # 方式 a 是 append 的缩写, 表示文件的追加模式
- append_text="this is appened text"
- my_file.write(append_text)
- my_file.close()
- # 13 读文件
- my_file=open('1.txt','r') #r 为读模式
- content=my_file.read() # 读取文件内容需要使用 read()方法
- second_read=my_file.readline()
- third_read=my_file.readline() #readline 为逐行输出文字
- all_read=my_file.readlines() # 逐行读取后会将读取的元素按行放置在一个列表中
- print(content,'second_read',second_read,'third_read',third_read,'all_read',all_read)
14 类(class)
- class Calculator: # 类一般为大写
- def __init__(self,name,price): # 构造函数, 在进行对象实例化时必须赋值, 前面需要加上 self
- self.name=name
- self.price=price
- name="Calculator"
- price=10
- def add(self,x,y):
- print(self.name) # 如果要在类内调用本身的方法, 需要加上 self. 属性名或 self. 方法名
- result=x+y
- print(result)
- def minus(self,x,y):
- result=x-y
- print(result)
- def times(self,x,y):
- result=x*y
- print(result)
- def devide(self,x,y):
- result=x/y
- print(result)
- newcalulator=Calculator('name',10)
- print(newcalulator.name)
- 15input
- a_input=input('Please give me a number:') #input 的功能为输入, 其后面的括号为提示信息, input 的返回值为输入的内容(是 str 类型), 并赋值给对应的参数
- int_input=int(a_input) # 对字符串需要转换为 int 类型后进行判断
- if int_input==1:
- print('your input is 1')
- elif int_input==2:
- print('your input is 2')
- else:
- print('your input number is other')
16 元组 使用小括号或者不使用括号
- a_tuple=(1,2,3,43) # 元组可以用小括号的形式, 也可以不加小括号
- another_tuple=1,12,43,23
- for x in a_tuple:
- print(x)
17 列表 使用中括号
- a_list=[12,34,23,43]
- for x in a_list: # 将 list 的值使用 for 循环放到 x 中, 之后打印出来
- print(x)
- for index in range(len(a_list)): #range()会生成一个迭代器, index 为索引
- print("index=",index,'number in list=',a_list[index])
- a=[1,2,3,4,5]
- a.append(0) # 在列表后面追加一个元素
- print(a)
- a.insert(1,0) #insert(添加位置, 数值)
- a.remove(2) #remove(第一次出现的数值)
- print(a[3:5])
- a.index(1)# 列表中第一次出现该数值的索引
- a.sort(reverse=True) # 默认为从小到大进行排序, 加入 reverse 则进行从大到小进行排序
- print(a)
18 多维列表
- a=[1,2,3,4,5]
- multi_dim_a=[[1,2,3],[123,312,4],[12,43,1]]
- print(multi_dim_a[1][1]) # 使用 [][] 进行索引
19 字典 使用大括号
- d={'apple':1,'pear':2,'orange':3} # 冒号前面的为 key, 后面的为内容, 字典的 key 唯一, 如果不唯一则记住后面的元素, 其不能是列表, 以保证其唯一性要求
- print(d['apple']) # 打印字典的值
- del d['pear'] # 从字典中删除元素
- d['b']=20 # 加入元素到字典
- print(d) # 因为字典采用 hash 存储, 所以字典是一个无序的容器
20import 模块
- # 方法一:
- # import time # 直接使用模块名进行后续操作
- # print(time.localtime())
- # 方法二:
- # import time as t # 如果模块名太长可以使用简称
- # 方法三:
- # from time import localtime 只引入模块的某个功能
- # print(localtime()) # 如果使用本方法, 可以不用写 time.localtime, 而直接写 localtime()
- # 方法四:
- from time import * # 加 * 可以结束
- print(localtime())
21 引入自己的模块
- # 确保自己的模块 (同为. py 文件) 和本文件在同一个目录下,
- # import m1 # 自己的模块名, 其中定义了函数
- # m1.function() 直接调用其函数即可, 在 macox 中, 其包目录在 site-package 中, 如果将自建模块放入其中, 则可以直接调用
- 22break&continue
- a=True
- while a:
- b=input('Please enter something:')
- if b!='':
- print('enter is not blank')
- break
23 错误处理
- try:
- File=open('12','r')
- except Exception as e:
- print('there is no file named 12')
- response=input('do you want to creat a new file?(Y/N)')
- if response =='y'or'Y': # 逻辑运算符 或 or 且 and 非 not
- print('the file is created')
- else:
- pass # 跳过
- 24zip(将两个列表合并为一个列表项) lambda map
- a=[1,2,3]
- b=[4,5,6]
- list(zip(a,b)) #zip 返回为一个对象, 如果想将其可视化, 需要将其转化为 list 进行合并
- for i,j in zip(a,b):
- print(i/2,j/2) # 生成一个迭代器进行输出
- fun1=lambda x,y:print(x+y)
- fun1(2,3)
- def fun1(x,y):
- return(x+y)
- # 实现参数绑定
- print(fun1,[1,3],[2,8])
- 25shallow copy &deep copy
- import copy
- a=[1,2,3]
- b=a
- print(id(a)) # 输出变量的唯一 id, 是赋值, b 只是将 a 的地址进行了复制, 而没有进行实际的变量值的拷贝
- print(id(b))
- c=copy.copy(a)
- print('id of a:',id(a))
- print('id of c:',id(c)) # 浅拷贝, id 不同, 第一层空间地址不同, 但是第二层空间 (数组第二围) 开始地址相同
- d=copy.deepcopy(a)
- print('id of a:',id(a))
- print('id of c:',id(d)) # 深拷贝, id 不同, 从第一层空间开始地址已经完全不同
- # 26threading 线程
- # 27multiprocessing 多核心
- # 28tkinter GUI 界面
29pickle 保存代码
- import pickle
- # a_dic={'fruit':['apple','pear'],'vegetable':['tomato','cumcuber']}
- # file =open('pickle_exm.pickle','wb')
- # pickle.dump(a_dic,file)
- # file.close()
- # file=open('pickle_exm.pickle','rb')
- # a_dic=pickle.load(file) # 将之前保存的代码打开
- # file.close()
- # 或者自动关闭方案
- with open('pickle_exm.pickle','rb') as file:
- a_dic=pickle.load(file)
30 使用 set 寻找不同
- char_list=['a','b','c','c']
- print(set(char_list)) # 使用 set 进行不同查找, 输出结果为非重复序列, 按 hash 排序
- sentence='welcome to shijiazhuang'
- print(set(sentence)) # 可以分辨句子中的不同字母, 并以单个的形式呈现
- # 31 正则表达式(待补充)
- import re # 引入正则表达式
- pattern1="cat"
- pattern2='dog'
- string="dog runs to cat"
- print(pattern1 in string) # 使用 in 来判断单词是否在目标语句中
- # 查找
- print(re.search(pattern1,string))# 使用正则表达式进行查找, 查找到的内容会被以对象的形式返回
- # 匹配多种可能使用[]
- print(re.search(r"r[A-Z0-9]n",'dog runs to the cat'))
来源: http://www.bubuko.com/infodetail-2519188.html