Python基础
1.基础语法
-
range(a, b): 包含a但不包含b
-
range(a, b, c):c是步长
-
==:等于
-
!=:不等于
-
定义函数:
def function(参数):
-
调用函数
function(参数)
-
print()的时候,有逗号会自动空格
-
在给函数传参数的时候,可以先给参数赋一个默认值。有默认值的参数应该排在最后面(在没有默认值的参数后面)。在传参的时候也可以重新给有默认值的参数赋值
-
在全局定义了一个变量a,在函数中使用全局变量a的时候,需要在a前面加上global
2.文件读写
(1)文件写入
text = "This is my first test.\nThis is the next line.\nThis is the last line."
# open(文件名, 以什么样的形式打开文件)
# 若没有文件会自动创建一个
# w:文件写入
my_file = open("my_file.txt", "w")
my_file.write(text)
my_file.close()
(2)追加内容
append_text = "\nThis is appended file."
# open(文件名, 以什么样的形式打开文件)
# 若没有文件会自动创建一个
# a:追加内容
my_file = open("my_file.txt", "a")
my_file.write(append_text)
my_file.close()
(3)文件读取
# 将文件存入file
file = open("my_file.txt", "r")
# 读出文件的内容
content = file.read()
# 逐行读取
content_1 = file.readline()
content_2 = file.readline()
# 读取文件所有行,并放入到一个列表中
contents = file.readlines()
print(content)
print(content_1)
print(content_2)
print(contents)
3.类
class Calculator:
# 类中有自己的属性
name = "good calculator"
price = 18
# self 类里面的默认参数
def add(self, x, y):
# 在类里面调用类的属性时要加self
print(self.name)
result = x + y
return result
def minus(self, x, y):
result = x - y
return result
def times(self, x, y):
result = x * y
return result
def divide(self, x, y):
result = x / y
return result
# 定义一个变量代表这个类
calcul = Calculator()
# 打印类的属性
print(calcul.name)
print(calcul.price)
# 调用类的功能
add = calcul.add(10, 11)
print(add)
class Calculator:
# 类中有自己的属性
# 属性的默认值
name = "good calculator"
price = 18
# 可以赋默认值,类似函数传参
def __init__(self, name, price, hight, width, weight):
# 会覆盖掉之前定义的默认值
self.name = name
self.price = price
self.hight = hight
self.w = width
self.we = weight
# 在给类实体化的时候就会自动执行该功能
self.add(1, 2)
# self 类里面的默认参数
def add(self, x, y):
# 在类里面调用类的属性时要加self
print(self.name)
result = x + y
return result
def minus(self, x, y):
result = x - y
return result
def times(self, x, y):
result = x * y
return result
def divide(self, x, y):
result = x / y
return result
# 定义一个变量代表这个类
calcul = Calculator('good', 12, 30, 15, 19)
# 打印类的属性
print(calcul.name)
print(calcul.price)
# 调用类的功能
add = calcul.add(10, 11)
print(add)
4.input输入
# input()返回值是一个字符串
a_input = input("Please input a number:")
print("this input number is:", a_input)
5.元组 列表
a_tuple = (1, 2, 3, 4, 5, 6)
another_tuple = 2, 4, 6, 8
a_list = [12, 13, 14, 15]
for content in another_tuple:
print(content)
for index in range(len(a_list)):
print(a_list[index])
列表:
- list.append(a):添加a
- list.insert(index, a):在index下标处插入a
- list.remove(a):删除列表中第一个a
- list[-1]:列表最后一位
- list[a: b]:列表中下标a到下标b-1的值;a,b可省略,也可为负数
- list.index(a):列表中第一次出现a的下标
- list.count(a):列表中出现a的次数
- list.sort():列表从小到大排序,会覆盖掉原有的列表
- list.sort(reverse=True):列表从大到小排序
多维列表
- multi_list[a]
- multi_list[a][b]
6.字典
- dictionary = {key:value, key:value}
- dictionary[key]:取value值
- del dictionary[key]:删除某个值
- dictionary[key] = value:添加某个值
- 没有顺序
- value可以是一个列表,字典,函数等
7.import
import xxx
import xxx as xxx
from xxx import xxx
from xxx import *
还可以import自己的模块
8.错误处理
try:
file = open("eeee", "r")
# 有错误执行except
except Exception as e:
print(e)
print("There is no file named as eeee")
response = input("a new file?(y/n)")
if response == 'y':
file = open('eeee', 'w')
else:
pass
# try后面的代码顺利执行了没有错误,执行else
else:
file.write('ssss')
file.close()
9.zip lambda map
-
zip:合并元素
a = [1, 2, 3] b = [4, 5, 6] # zip(a, b); zip(a, a, b) for i, j in zip(a, b): print(i, j)
-
lambda:定义方程
func = lambda x, y:x + y print(func(2, 3))
-
map:绑定函数和参数
def func(x, y): return x + y # 1 + 2 map(func, [1], [2]) # 1 + 2; 3 +5 map(func, [1, 3], [2, 5])
10.浅复制,深复制
import copy
a = [1, 2, 3]
# 深复制
b = a
# id(a) 和 id(b)相同,改变a或b中的值,b或a会跟着改变
print(id(a), id(b))
# 浅复制
c = copy.copy(a)
# id(a) 和 id(c)不相同,改变a或c中的值,c或a不会跟着改变
print(id(c), id(a))
import copy
a = [2, 4, [1, 3]]
b = copy.copy(a)
print(b)
# [2, 4, [1, 3]]
a[0] = 6
print(b)
# [2, 4, [1, 3]]
a[2][0] = 5
print(b)
# [2, 4, [5, 3]]
import copy
a = [1, 2, 4]
# 完完全全copy,任何东西都不会被重复
e = copy.deepcopy(a)
11.pickle存放数据
import pickle
a_dict = {"da": 111, 2: [23, 1, 4], "23": {1: 2, 'd': 'sad'}}
# 把数据存起来
file = open('pickle_example.pickle', 'wb')
pickle.dump(a_dict, file)
file.close()
# 把数据读出来继续加工
file = open("pickle_example.pickle", 'rb')
b_dict = pickle.load(file)
file.close()
print(b_dict)
# 用with不用考虑file.close(),运行完之后自动close
with open('pickle_example.pickle', 'rb') as file:
c_dict = pickle.load(file)
12.set
- set(list):去除掉list中的重复元素,type为set
- set(String):去除掉字符串中的重复元素,区分大小写字母
- set_demo.add(a):添加a值,若a有重复,仍只有一个a
- set_demo.clear():清除所有值
- set_demo.remove(a):减掉a值,返回值为None,若不含a则报错
- set_demo.discard(a):减掉a值,若不含a不会报错
- set_demo_1.difference(set_demo_2):返回set_demo_1中set_demo_2没有的元素
- set_demo_1.intersection(set_demo_2):返回set_demo_1和set_demo_2的交集
13.RegEx正则表达式
import re