Python3 中有六个标准的数据类型:
内置函数 | 参数 |
---|---|
int() | 字符串(整数)、数 |
float() | 字符串、数 |
str() | 任何对象 |
list() | 可迭代对象 |
tuple() | 可迭代对象 |
# int():字符串(整数)、数
n = int('3')
# n = int('3.5') # 报错
n = int(2.2)
print(n)
# float():字符串、数
f = float('3.5')
f = float('3')
f = float(3)
print(f)
# str():任何对象
s = str(2.2)
s = str([1, 2, 3])
s = 'abc'
print(s)
# list:可迭代对象
x = list('123')
print(x)
定义:引号(单引号 or 双引号)
链接:字符串的所有方法查询
字符串的方法 | 描述 |
---|---|
str = str.title() | 首字母大写,eg:Abc Def |
str = str.upper() | 全大写 |
str = str.lower() | 全小写 |
str = str.strip() str = str.lstrip() str = str.rstrip() |
删除首尾处所有 空白 删首 删尾 |
+ | 拼接 |
\n 、\r、\t 、 空格 | 统称为“空白” |
lists = str.split(x) | 以字符串x为分隔(默认空格),返回一个元素是字符串的list |
s1 = "abc"
s2 = "def"
s3 = f"{s1}----{s2}"
print(s3)
数:包括整数、浮点数
运算中,若有一个操作数是浮点数,结果也是浮点数
# /:返回浮点数
x = 2 / 3
print(x) #0.6666666666666666
x = 3 / 3
print(x) #1.0
#乘方
x = 10**-3
print(x) #0.001
# 支持表达式
x = ((1+2)-5)*6
print(x)
x, y, z = 0, 0, 0
#科学计数
MAX_NUM = 2.5e6 #2*10^6
MAX_NUM = 2.5*10**6 #同上
#下划线
MAX_NUM = 1_000_000_000
重点操作:列表解析、切片、复制、排序
students = []
# 访问
students = [['David', ['Bob', 'Mike'], 'Joe'], ['Jack', 'Amy'], ['Tom']]
print(students) # 全部
print(students[0]) # ['David', ['Bob', 'Mike'], 'Joe']
print(students[-1]) # 最后一个元素 ['Tom']
print(students[-2]) # 倒数第二个元素 ['Jack', 'Amy']
print(students[0][1][1]) # Mike
# 修改
students[-1] = 'Tom'
# 添加
students.append(['Kris', ['Candy']]) # 末尾
students.insert(0, 'AAA') # 任意位置
# 删除
# 1. 根据索引位置
del students[1] # 任意位置
x = students.pop() # 末尾
print(x)
x = students.pop(1) # 任意位置
print(x)
# 2. 根据值
students.remove('BBB') # 报错:ValueError: list.remove(x): x not in list
students.remove(['David', ['Bob', 'Mike'], 'Joe']) # 只删除第一个出现的,若要删除多个重复,用循环
# 排序
# 1. 临时 内置函数:sorted()
students = ['a', 'c', 'b']
x = sorted(students, reverse=True)
print(students)
print(x)
# 2. 永久 lis.sort()
students.sort(reverse=True)
print(students)
# 长度
print(len(students))
# 逆序
students.reverse() # 永久
print(students)
# 遍历
for item in students:
print(item)
# range
for item in range(10): # 0,1,...,9
print(item)
for item in range(0, 10): # 0,1,...,9
print(item)
for item in range(9, -1, -1): # 9,8,...,0
print(item)
numbers = list(range(10))
print(numbers)
# 列表解析:创建list+for,一行代码
numbers = [item*2+1 for item in range(10)]
print(numbers)
# 切片
numbers = list(range(5))
print(numbers[0:3]) # 0,1,2
print(numbers[:3]) # 0,1,2
print(numbers[1:]) # 从1开始,到最后
print(numbers[-2:]) # 从倒数第二个开始
# 复制
# 方法1:切片
numbers2 = numbers # 指向同一个列表内存,浅拷贝
numbers2 = numbers[:] # 生成副本,深拷贝
# 方法2:list.copy()
x = [1, 2, 3]
y = x.copy()
y.append(4)
print(x) # [1, 2, 3]
print(y) # [1, 2, 3, 4]
sex = ()
sex = (male,) # 元组创建,当只有一个元素时,必须加逗号
键:不可变对象(字符串、数、tuple)
值:任何对象
重点操作:==dist.get()、sorted()、set()
# 访问
student = {
'name': 'Amy', 'age': 20}
print(student['age'])
# dist.get():当键不存在时,不报错
print(student.get('parents')) # None
print(student.get('parents', 'not exit')) # not exit
# 添加
student['sex'] = 'male'
print(student)
# 修改
student['sex'] = 'female'
print(student)
# 删除
del student['sex']
print(student)
# 复制
x = {
"a": 1, "b": 2}
y = x.copy()
y["c"] = 3
print(x) # {'a': 1, 'b': 2}
print(y) # {'a': 1, 'b': 2, 'c': 3}
# 遍历
student_age = {
'Amy': 18,
'Jack': 17,
'Bob': 17,
}
print(student_age)
print(student_age.items())
print(student_age.keys())
print(student_age.values())
if 'Mike' not in student_age.keys():
print('student_age has not this key.')
# 1. 键、值
for name, age in student_age.items():
print(name)
print(age)
for name in student_age: # 默认遍历键
print(name)
for name in student_age.keys(): # 等同上
print(name)
for age in student_age.values():
print(age)
# 2. 按排序遍历:内置函数sorted()
for name in sorted(student_age.keys()):
print(name)
for age in sorted(student_age.values()):
print(age)
# 3. 去重遍历:内置函数set()
for age in set(student_age.values()):
print(age)
不要嵌套过多,最多两层
# list中存放dist
students = [
{
'name': 'Jack', # 所有dist键最好相同(相同结构)
'age': 18,
},
{
'name': 'Bob',
'age': 16,
},
]
print(students)
# dist中存放list
student = {
'name': 'Amy', 'courses': ['Math', 'English']}
print(student)
# dist中存放dist
students = {
'Jack': {
'sex': 'male', # 所有dist键最好相同(相同结构)
'age': 18,
},
'Bob': {
'sex': 'male',
'age': 16,
},
}
print(students)
区分集合和字典
sex = {
'male', 'male', 'female'}
print(sex) # 乱序
if-elif-else结构(else可省略)
x = None / 0 / False/ “” / [] / () / {},都可用if x: 判断
# 判断一个元素是否在list中:in、not in
numbers = list(range(10))
if 2 in numbers:
print('2')
elif 3 not in numbers:
print('3')
else:
print('no')
# 判断为空
x = None
x = ""
x = 0
x = []
if x:
print(True)
else:
print(False)
循环:for、while
操作:continue、break
# 输入循环
s = ''
while s != 'exit':
s = input('Please input: ')
print(s)
# 标志循环
tag = True
while tag:
print(tag)
tag = False
# 删除list中的所有特定元素
numbers = [1, 2, 3, 2, 3, 2, 4]
while 2 in numbers:
numbers.remove(2)
print(numbers)
def func_name(x, y):
"""文档字符串"""
pass
def func_name2(x, y):
"""
文档字符串
文档字符串
"""
pass
def func_name(x, y, z=0): # 默认值形参放在最后
"""文档字符串"""
pass
# 位置实参:实参和形参位置顺序一致,一一对应
func_name(1, 2)
func_name(1, 2, 3)
# 关键字实参:无关实参顺序
func_name(y=2, x=1)
func_name(y=2, z=3, x=1)
# 参数:list
list_name = [1, 2, 3]
func_name(list_name, 2) # 永久性修改原来list
func_name(list_name[:], 2) # 传递副本,禁止修改原来list
# 参数:dist
dict_name = {
'a': 1, 'b': 2}
func_name(dict_name, 2) # 永久性修改原来dict
实形参的匹配顺序:
非默认值参数 --> 默认值参数
位置参数 --> *args
关键字参数 --> **kwargs
位置参数 --> 关键字参数
*args --> **kwargs
*args --> 默认值参数(且为关键字参数)
默认值参数 --> **args
所有参数情况:
# 位置参数
def func1(a, b, *args, c=None):
# 默认值参数和*args同时出现:*args --> 默认值参数,且必须将默认值参数转为关键字参数
print('---func1------------')
print(a)
print(b)
print(c)
print(args)
func1('a', 'b', 1, 2, 3, c='c')
func1('a', 'b', 1, 2, 3)
# 关键字参数
def func2(kwa, kwb, kwc=None, **kwargs):
print('---func2------------')
print(kwa)
print(kwb)
print(kwc)
print(kwargs)
func2(kwa='kwa', kwb='kwb', kwargs1=1, kwargs2=2)
func2(kwa='kwa', kwb='kwb', kwc='kwc', kwargs1=1, kwargs2=2)
# 位置参数和关键字参数
def func3(a, b, kwa, kwb):
print('---func3------------')
print(a)
print(b)
print(kwa)
print(kwb)
func3('a', 'b', kwa='kwa', kwb='kwb')
# *args 和 **kwargs
def func4(*args, **kwargs):
print('---func4------------')
print(args)
print(kwargs)
func4(1, 2, 3, kwargs1=1, kwargs2=2)
# 位置参数和关键字参数
def func5(a, b, *args, kwa, kwb, **kwargs):
print('---func5------------')
print(a)
print(b)
print(args)
print(kwa)
print(kwb)
print(kwargs)
func5('a', 'b', 1, 2, 3, kwa='kwa', kwb='kwb', kwargs1=1, kwargs2=2)
# 位置参数和关键字参数
def func6(a, b, *args, c=None, kwa, kwb, kwc=None, **kwargs):
print('---func6------------')
print(a)
print(b)
print(c)
print(args)
print(kwa)
print(kwb)
print(kwc)
print(kwargs)
func6('a', 'b', 1, 2, 3, c='c', kwa='kwa', kwb='kwb', kwc='kwc', kwargs1=1, kwargs2=2)
func6('a', 'b', 1, 2, 3, kwa='kwa', kwb='kwb', kwargs1=1, kwargs2=2)
默认值等号两边不要有空格(实、形参)
# 字符串设置为空
def func_name(x, y, s=""):
"""文档字符串"""
if s:
pass
else:
pass
# 其余数据类型均设置为None
def func_name2(x, y, z=None):
"""文档字符串"""
if x:
pass
else:
pass
class Student:
"""文档字符串"""
def __init__(self, name, age):
self.name = name
self.age = age
self.professional = 'student' # 属性默认值(区别参数默认值)
def study(self):
print(f"{self.name} is studying.")
def update_age(self, age):
self.age = age
a_student = Student("Amy", 18)
print(a_student.name)
a_student.study()
# 修改属性的值
# 方法1:直接修改
a_student.age = 20
print(a_student.age)
# 方法2:通过方法
a_student.update_age(25)
print(a_student.age)
# 子类
def __init__(self, name): # 最终self.name = "Jack"
super().__init__(name)
self.name = "Jack"
# 子类
def __init__(self, name): # 最终self.name = name
self.name = "Jack"
super().__init__(name)
重写与重载
父类的函数func()
子类的函数func()
重写:子类的func()与父类的函数名和参数均相同,子类只有自己的func(),父类的被覆盖
重载:子类的func()与父类的函数名相同,参数不同,子类有父类的func()和自己的func()
单继承:super()
多继承:子类的属性是某个类的实例
class Student:
"""文档字符串"""
def __init__(self, name, age):
self.name = name
self.age = age
self.professional = 'student' # 属性默认值(区别参数默认值)
def study(self):
print(f"{self.name} is studying.")
def update_age(self, age):
self.age = age
class Hobby:
"""这是一个爱好"""
def __init__(self, hobby_name="reading"):
self.hobby_name = hobby_name
def print_hobby(self):
print(self.hobby_name)
class Girl(Student):
"""文档字符串"""
def __init__(self, name, age, hobby_name):
super().__init__(name, age) # 显示调用父类的__init__()
self.sex = 'female'
self.hobby = Hobby(hobby_name) # 属性为某个类的实例
# 重写父类的方法
def study(self):
print(f"A girl {self.name} is studying in.")
a_girl = Girl("Amy", 18, "dancing")
a_girl.study()
a_girl.update_age(20) # 调用父类的方法
print(a_girl.age)
a_girl.hobby.print_hobby()
模块名: my_function.py
def func1():
print("func1")
def func2():
print("func2")
调用:main.py
# 导入整个模块
import my_function # import 模块名
my_function.func1() # 模块名.函数名
my_function.func2()
# 导入整个模块,起别名
import my_function as myf # import 模块名 as 别名
myf.func1() # 别名.函数名
myf.func2()
# 导入模块的特定函数
from my_function import func1, func2 # from 模块名 import 函数名1, 函数名2
func1() # 函数名
func2()
# 导入模块的特定函数,起别名
from my_function import func1 as f1, func2 as f2
# from 模块名 import 函数名1 as 别名1, 函数名2 as 别名2
f1() # 别名
f2()
# 导入模块的所有函数
from my_function import * # from 模块名 import *
func1()
func2()
模块名: my_class.py
class A:
pass
class B:
pass
实例:main.py
# 导入整个模块
import my_class # import 模块名
a = my_class.A() # 模块名.类名
b = my_class.B()
# 导入整个模块,起别名
import my_class as myc # import 模块名 as 别名
a = myc.A() # 别名.类名
b = myc.B()
# 导入模块的特定类
from my_class import A, B # from 模块名 import 类名1, 类名2
a = A() # 类名
b = B()
# 导入模块的特定类,起别名
from my_class import A as MyA, B as MyB
# from 模块名 import 类名1 as 别名1, 类名2 as 别名2
a = MyA() # 别名
b = MyB()
# 导入模块的所有类
from my_class import * # from 模块名 import *
a = A()
b = B()
with open("files/text_file.txt") as f:
print(f)
# <_io.TextIOWrapper name='files/text_file.txt' mode='r' encoding='cp936'>
以字符串读写
模式参数 | 描述 | 若文件不存在 | 若文件已存在 |
---|---|---|---|
r (模式参数省略,默认为’r’) | 读 | ||
w | 写 | 创建 | 覆盖 |
a | 写 | 创建 | 末尾追加,不覆盖 |
r+ | 读、写 | 覆盖 | |
w+ | 读、写 | 创建 | 覆盖 |
a+ | 读、写 | 创建 | 末尾追加,不覆盖 |
以二进制读写
基本6种模式参数+‘b’,如 rb、rb+
# 全部读取 f.read()
file_name = "files/text_file.txt"
try:
with open(file_name) as f:
content = f.read() # read():字符串
except FileNotFoundError:
print(f"{file_name} does not exist.")
else:
print(content)
# 逐行读取 f.readlines()
try:
with open(file_name) as f:
for line in f: # line:字符串
print(line)
except FileNotFoundError:
print(f"{file_name} does not exist.")
try:
with open(file_name) as f:
contents = f.readlines() # read():列表,每个元素为字符串(一行)
except FileNotFoundError:
print(f"{file_name} does not exist.")
else:
print(contents)
# 全部写 file_object.write()
content = "abc.def\n\t123\n\t345"
with open("text_file.txt", "w") as file_object:
file_object.write(content) # 字符串
# 逐行写
with open("text_file.txt", "w") as file_object:
file_object.write("abc.def\n")
file_object.write("\t123\n")
file_object.write("\t345")
# 追加写
with open("text_file.txt", "a") as file_object:
file_object.write("\n\t678")
try - except - else
x = 2
y = 0
z = x/y # 查看 异常名称:ZeroDivisionError: division by zero
# 异常处理
try:
z = x/y # 可能出错的代码
except ZeroDivisionError:
print("can't divide by zero") # 不抛出traceback,正常运行
else:
print(z) # 若try中正常执行
print("end")
# 静默处理
x = 2
y = 0
try:
z = x/y
except ZeroDivisionError:
pass
TestCase类的方法:常用断言
方法名 | 符合条件,则测试通过 |
---|---|
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中 |
my_function.py
def get_age(age):
if age >= 18:
return "adult"
else:
return "child"
test.py
import unittest
from my_function import get_age
# 测试类
class AgeTestCase(unittest.TestCase): # 父类:unittest.TestCase
"""测试一个函数"""
# 一个单元测试
def test_adult(self):
age = get_age(20)
self.assertEqual("adult", age) # 断言:判断函数的结果是否正确
# 一个单元测试
def test_child(self):
age = get_age(15)
self.assertEqual(age, "child")
if __name__ == "__main__":
unittest.main()
my_class.py
class Student:
"""文档字符串"""
def __init__(self, name):
self.name = name
self.courses = []
def add_course(self, c):
"""添加课程"""
self.courses.append(c)
test.py
import unittest
from my_class import Student
# 测试类
class StudentTestCase(unittest.TestCase):
"""测试一个类"""
def setUp(self): # 为所有test_方法创建一系列共用的实例,和需要的测试用例
self.student = Student("Amy")
self.courses = ["English", "Math"]
def test_add_course(self):
for c in self.courses:
self.student.add_course(c)
# 断言
for c in self.courses:
self.assertIn(c, self.student.courses) # 判断课程是否都已添加
if __name__ == "__main__":
unittest.main()
s = input('Please input: ')
print(s)
prompt= 'Please input: '
s = input(prompt)
print(s)
x = 2
y = 0
try:
z = x/y
except ZeroDivisionError:
pass
else:
print(z)