Python基础(有C语言基础者)
一、Python基础
1. 起步
1.1 Windows终端退出Python的2种方式
① ctrl + z、再 Enter(回车)
② exit()
2.2 配置 Sublime Text 使用正确的Python版本
如果python命令启动的是python3 就无须配置,否则
Tools -> Build System -> New Build System -> 新建一个配置文件(如下) -> 保存到默认目录。
{
"cmd": ["python3", "-u", "$file"],
}
2. 变量和简单数据类型
2.1 字符串
-
可以用单引号或者双引号 括起 字符串。如下 定义字符串变量
string1 = 'He says that "Python is good!"' string2 = "He says that 'Python is good!'" string3 = ''' He syas that input in next line''' #字符串可以包含换行 -
字符串方法
message = "python" message.lower() #改为全部小写 message.upper() #改为全部大写 message.title() #首字母大写 message.strip() #剔除字符串两边的空白 message.lstrip() #剔除字符串左边的空白 message.rstrip() #剔除字符串右边的空白 -
字符串中使用变量
要在字符串中插入变量的值,可在字符串的引号前加字母f(只有pthon3.6及以上支持),再将插入的变量放在花括号内,如
first_name = "ada" last_name = "lovelace" full_name = f"{first_name} {last_name}" print(f"Hello, {full_name.title()}!")输出
Hello, Ada Lovelace!
2.2 数
2.2.1 整数、运算符
运算符 + 、- 、 *、 /、**(乘方运算符)、%(求模运算符)
2.2.2 浮点数
① 任意两个数(包括两个数都是整数)相除,结果总为浮点数
② 任何运算,只要操作数是浮点数,python默认得到的总是浮点数。
2.2.3 数中下划线
方便人阅读
count= 1_000_000 #1000000
number = 1_00_0 #1000
2.3 多个变量定义
x,y,z = 1,2,3 #用逗号将变量名分开,值也一样用逗号分开
3. 列表
3.1 列表的表示
列表由一系列按特定顺序排列的元素组成。用方括号[]表示列表,各元素用逗号分开,如
list = [] #空列表
list = ['English','Chinese','Japanese']
3.2 访问列表的元素
使用索引(类似C语言的数组),索引从0开始。[i]表示正数第 (i+1) 个元素,[-i]表示倒数第 i 个元素,如
list = ['A','B','C']
list[0] #'A'
list[1] #'B'
list[-1] #'C'
list[-2] #'B'
3.3 修改列表
-
添加元素
list = ["AB", "CD", "EF"] list.append("GH") #使用方法append在列表末尾追加一个元素 list.insert(0, "IJ") #使用方法insert向列表索引0处(列表头)插入一个元素 -
删除元素
del list[0] #del语句 和 元素索引 删除元素, 无法用变量再接收该元素 last = list.pop() #末尾元素出列表,同 last = list.pop(-1) last = list.pop(0) #通过 索引0 删除 last = list.remove("CD") #通过 方法remove 和 元素的值 来删除, #remove只能删除第一个值,列表中有多个重复值时需重复调用remove
3.4 组织列表(排序)
length = len(list) #函数len获取列表长度,即元素个数,长度计数从1开始
st = sorted(list) #函数sorted,临时排序,list中元素顺序不变
list.sort() #按升序永久排序,同 list.sort(reverse=False),list元素的顺序被重排
list.reverse() #翻转列表元素顺序
3.5 操作列表
-
函数 range()
range(6) #同 range(0, 6), 生成 0 1 2 3 4 5 (不包含6) range(0,9,2) #从0开始,按步长2生成一系列数字 0 2 4 6 8 -
list + range 生成列表
list(range(0, 100, 3)) #将range()结果转换为列表 min(list) #列表中最小值 max(list) #列表中最大值 sum(list) #列表值总和 -
列表解析
将for循环和创建新元素的代码合并成一行。
squares = [value**2 for value in range(1,11)] #同 squares = [] for value in range(1,11): squares.append(value**2) -
切片(列表的一部分)
list = ['A', 'B', 'C', 'D'] list[0:3] #取列表索引0~3的元素(不包含3) list[:3] #从索引0开始 list[1:] #从索引1开始,到最后一个元素(含最后一个) list[0:4:2] #从索引0开始,到4(不含4),每个2个元素取一个 list[-3:] #取最后三个元素 -
复制列表
list = ['A', 'B', 'C', 'D'] list_copy = list[:] #拷贝一个列表副本存在list_copy,与list是独立的两个列表 list_alias = list #没有拷贝副本,只是将新变量list_alias关联到list, 两个变量指向同一个列表
3.6 元组(不可修改的列表)
dimensions = (200,) #元组实际是以逗号标识的,圆括号只是让元组看起来更整洁
#只定义1个元素时,必须在元素后面加一个逗号
dimensions = (200,300,500) #元组不可修改,但元组变量可以被重新赋值
print(dimensions[0]) #用索引0访问元组元素
4. if 语句
4.1 if 表达式 与 结构
-
判断相等 == (字符大小写敏感)
-
判断不等 !=
-
数值比较 >、<、 >=、<=
-
检查多个条件 and 、 or (同C语言的 && 、||)
-
检查特定值是否在列表 in、not in
-
布尔值 True 、False
-
if结构
if-elif-...-elif-else (elif 可以任意多个, else 可选)
4.2 if语句处理列表
列表名作为条件表达式时, 列表为空 返回 False,否则返回 True。
list = []
if list:
print("list is not empty")
else:
print("list is empty") #会打印此句
5. 字典
5.1 字典的定义
字典是一系列键值对,每个键值对见用逗号隔开,放在花括号中。
dictionary = {} #空字典
dictionary = {'amee': 12, 'sandy':'children'}
5.2 访问字典
- dictionary_name[key_name] = new_value
- dictionary_name.get(key_name, returned_value_when_key_isnot_exist)
dictionary = {'amee': 12, 'sandy':'children'}
print(dictionary['amee']) #访问字典中的某个键值。 当key不存在时,会抛异常
print(dictionary.get('amee', 'amee is not exist')) #当key不存在时,get方法返回入参字符串
print(dictionary.get('amee') #当key不存在时,get方法返回特殊值None
dictionary['amee'] = 24 #修改key为amee的值
dictionary['sex'] = 'boy' #添加键值对 'sex':'boy'
del dictionary['sex'] #删除键值对
5.3 遍历字典
- 方法 items()
- 方法 keys()
- 方法 values()
- 字典可以嵌套:字典列表、字典中存储列表、字典中存储字典
dictionary = {'amee': 12, 'sandy':'children'}
#遍历键值对
for k,v in dictionary.items():
#do something
#遍历键方式1
for k in dictionary:
#do something
#遍历键方式2
for k in dictionary.keys():
#do something
#遍历字典中的所有值(不剔除重复值)
for v in dictionary.values():
#do something
#遍历字典中的所有值(剔除重复值)
for v in set(dictionary.values()): #方法set 使用字典值创建一个集合
#do something
6. 集合
用花括号定义,元素用逗号隔开 且 元素不重复,与字典的区别是 集合没有键值对。
numset = {1, 2, 3, 44, 55}
7. 用户输入与while循环
7.1 接收用户输入文本—— 函数input()
message = input(obj) #input接收一个参数obj——向用户显示的提示,不只限于字符串
7.2 整数字符串转为整数—— 函数int()
number = "343"
number = int(number)
7.3 while
break、continue (同C语言,但没有do...while)
7.4 while循环处理列表
不应在for循环中修改列表,否则将导致Python难以跟踪其中的元素。
-
遍历弹出列表
unconfirmed_users = ["alice", "brian", "candace"] while unconfirmed_users: current_user = unconfirmed_users.pop() #从后往前弹出 -
删除为特定值的所有列表元素
pets = ['dog', 'cat', 'lion', 'cat', 'rabbit', 'cat'] while 'cat' in pets: pets.remove('cat')
8. 函数
8.1 函数定义
def 函数名(形参1, 形参2, 形参3=默认值):
""" 文档字符串 """
函数代码块
def display(thing, descript):
print(thing)
print(descript)
8.2 函数调用
8.2.1 位置实参
display("hello", 'world')
8.2.2 关键字实参
使用关键字实参时,务必准确指定函数定义中的形参名。
display(descript = 'world', thing = "hello")
8.3 传递任意数量的实参
- 形参名 *toppings 中的星号让Python创建一个名为toppings的空元组,并将收到的所有值都封装到这个元组中。接收任意数量实参的形参必须放在最后。
def make_pizza(*toppings):
print(toppings)
make_pizza('pepperoni')
make_pizza('pepperoni', 'green peppers')
-
形参 **user_info 中的两个星号让Python创建一个名为user_info 的空字典,并将收到的所有的名称值对都放到这个字典中。
def build_profile(first, last, **user_info): user_info['firstname'] = first user_info['last_name'] = last return user_info user_profile = build_profile('albert', 'einstein', location='princeton', field='physics') #location='princeton', field='physics' 自动存入字典user_info中
8.4 将函数存储在模块中
模块是扩展名为.py的文件,包含要导入到程序中的代码。
8.4.1 导入整个模块
import module #让Python打开文件module.py,并将其中的所有函数都复制到这个程序中
module.func1() #使用句点表示法调用模块内的函数
module.func2()
8.4.2 导入特定的函数
from module import func1, func2, func3 #导入多个函数用逗号隔开
from module import * #导入模块中的所有函数
func1() #直接调用
8.4.3 使用as给模块、函数指定别名
import module as m #给模块指定别名
m.func()
from module import func as f #给函数指定别名
f()
9. 类
9.1 类的定义
class Dog:
'''文档字符串,类的功能描述'''
def __init__(self, name, age = 10): #创建对象时, python会自动运行__init()__ 方法,销毁对象为 __del__()方法
self.name = name #self.name 类的成员变量
self.age = age #self.age 类的成员变量
def display(self):
print(self.name) #以self为前缀的变量可在类的所有方法使用
9.2 修改属性的值
-
直接修改。 如
dog = Dog('Andy') dog.age = 4 #直接修改 -
通过方法修改。
9.3 继承
通常要在子类的__init__()方法中调用父类的__init__方法。
class Dog: #采用驼峰命名法
'''文档字符串,类的功能描述'''
def __init__(self, name, age = 10):
self.name = name
self.age = age
def display(self):
print(self.name)
class Songshi(Dog): #必须在圆括号中指定父类的名称
def __init__(self, name, age, color):
super().__init__(name,age) #通过super()调用父类的初始化方法
def display(self): #可以重写与父类的方法同名的方法
print(self.age)
9.3 导入类
from car import Car #导入单个类Car
from car import Car, ElectricCar #导入多个类,用逗号隔开
import car #导入整个模块, 引用时带上模块名,如 car.Car()
from car import * #导入模块内所有类
from car import ElectricCar as EC #使用别名 EC代表car模块的类ElectricCar
10. 文件和异常
10.1 读取文件
with open('digist.txt') as f: #使用with打开文件时,Python会负责关闭文件,文件对象赋给了f
str = f.read() #读取文件所有内容,作为字符串存在str,读到文件尾,会返回字符串。
with open('digist.txt') as f_object:
line_list = f_object.readlines() #读取每一行,存入列表中
for line in f_object: #逐行读取文件
print(line)
10.2 写文件
with open('p.txt', 'w') as f: #写入模式(打开时会先清空文件)'w' 追加模式'a'
#读写模式(文件不存在会自动创建)'r+' 读取模式(默认)'r'
f.write("First Line")
10.2 异常处理
try:
with open(filename, encoding='utf-8') as f
contents = f.read()
except FileNotFoundError:
print('Tips') #异常处理代码,也可以用 pass 来静默失败(表示什么都不做)
else:
print('无异常的处理') #try代码块无异常,才执行else中的代码
10.3 存储数据
import json
nums = [1, 2, 3]
with open('x.txt', 'w') as f:
json.dump(nums, f) #将列表存储为文件
with open('x.txt') as rf:
num_list = json.load(rf) #将列表读取到内存
11. 单元测试
11.1 测试函数
import unittest # ① 导入模块unittest 和 要测试的函数
from func_mod import func_will_be_test
class NamesTestCase(unittest.TestCase): # ② 定义子类继承类unittest.TestCase
def test_func(self): # ③ 定义test_ 开头的函数, 调用测试函数进行测试
ret = func_will_be_test() # test_开头的函数会被自动运行
self.assertEqual(ret, None) # ④ 使用断言检查测试函数的运行结果
if __name__ == '__main__': #如果当前文件作为主程序运行, __name__ 会被置为'__main__'
unittest.main() #否则,若该文件被测试框架导入, __name__ 将不为'__main__'
11.2 测试类
import unittest
from car import Car
class NamesTestCase(unittest.TestCase):
def setUp(self): #TestCase包含的方法setUp,可让我们创建一个对象,在所有test_ 测试方法中使用
self.carobj = Car()
def test_func(self):
n = car.name()
self.assertIn(n, "Audio")
def test_func(self):
a = car.age()
self.assertNotEqual(a, 3)
if __name__ == '__main__': #如果当前文件作为主程序运行, __name__ 会被置为'__main__'
unittest.main() #否则,若该文件被测试框架导入, __name__ 将不为'__main__'
11.3 断言的方法
assertEqual(a,b) # a == b
assertNotEqual(a,b) # a != b
assertTrue(x) # x 为 True
assertFalse(x) # x 为 False
assertIn(x, list) # x 在 list 中
assertNotIn(x, list) # x 不在 list 中
12. match...case语句
match string: #Python 3.10及以上支持
case 'china':
print('china')
case 'english':
print('english')
13. 装饰器
13.1 闭包
什么叫闭包? 在函数中再嵌套一个函数,并且引用外部函数的变量,外部函数的返回值为内部函数,这就是一个闭包了。
def outer(x):
def inner(y):
return x + y
return inner
print(outer(6)(5))
-----------------------------
>>>11
13.2 装饰器
python装饰器总结一句话:采用了闭包的思路(内外函数嵌套,内函数引用外函数作用域下的非全局变量,外函数返回内函数的引用),在不改变原函数代码的前提下为函数增添新的功能。
def debug(func):
def wrapper():
print(f"[DEBUG]: enter {func.__name__}()")
return func()
return wrapper
@debug
def hello():
print("hello")
hello()
-----------------------------
>>>[DEBUG]: enter hello()
>>>hello
13.3 带参数的装饰器
def logging(level): #装饰器也可以传入参数
def outwrapper(func): #装饰函数
def wrapper(*args, **kwargs):
print("[{0}]: enter {1}()".format(level, func.__name__))
return func(*args, **kwargs)
return wrapper
return outwrapper
@logging(level="INFO")
def hello(a, b, c):
print(a, b, c)
hello("hello,","good","morning")
-----------------------------
>>>[INFO]: enter hello()
>>>hello, good morning
13.4 类装饰器
装饰器也不一定只能用函数来写,也可以使用类装饰器,用法与函数装饰器并没有太大区别,实质是使用了类方法中的call魔法方法来实现类的直接调用。
class logging(object):
def __init__(self, level):
self.level = level
def __call__(self, func):
def wrapper(*args, **kwargs):
print("[{0}]: enter {1}()".format(self.level, func.__name__))
return func(*args, **kwargs)
return wrapper
@logging(level="TEST")
def hello(a, b, c):
print(a, b, c)
hello("hello,","good","morning")
-----------------------------
>>>[TEST]: enter hello()
>>>hello, good morning
13.5 带参数的类装饰器
class logging(object):
def __init__(self, level):
self.level = level
def __call__(self, func):
def wrapper(*args, **kwargs):
print("[{0}]: enter {1}()".format(self.level, func.__name__))
return func(*args, **kwargs)
return wrapper
@logging(level="TEST")
def hello(a, b, c):
print(a, b, c)
hello("hello,","good","morning")
-----------------------------
>>>[TEST]: enter hello()
>>>hello, good morning

浙公网安备 33010602011771号