python回到初始位置_python之基础

文章目录

数据类型

6个基本类型

(不)可迭代对象、(不)可变对象

类型转换

字符串

方法总结

在字符串中使用变量:f字符串

运算

多个变量赋值

大数

列表list

操作

元组tuple

字典dist

操作

嵌套(list和dist)

集合set

条件与循环

if

while

函数

参数

位置参数、关键字参数、list参数、dict参数

5个参数类别

默认值

返回值

基类

多个类(继承、封装、多态)

模块

函数模块

类模块

文件

6种读写模式参数

读文件(r、r+)

写文件(w、w+、a、a+)

异常

测试

unittest模块

函数的测试

类的测试

其他

输入:input()

静默处理:关键字pass

数据类型

6个基本类型

Python3 中有六个标准的数据类型:

字符串

列表list

元组tuple

字典dist

集合set

(不)可迭代对象、(不)可变对象

可迭代对象:字符串、list、tuple、dist

不可迭代对象:数

可变对象:list、dist

不可变对象:字符串、数、tuple

类型转换

内置函数

参数

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

在字符串中使用变量:f字符串

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

列表list

操作

重点操作:列表解析、切片、复制、排序

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]

元组tuple

不可变的list,没有:增、删、改、排序、反转等等

元组由逗号标识,而不是小括号

sex = ()

sex = (male,)# 元组创建,当只有一个元素时,必须加逗号

字典dist

键:不可变对象(字符串、数、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)

不要嵌套过多,最多两层

# 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)

集合set

区分集合和字典

sex = {'male', 'male', 'female'}

print(sex) # 乱序

条件与循环

if

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)

while

循环: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

参数

位置参数、关键字参数、list参数、dict参数

参数:任何数据类型(字符串、数、list、dist…)

永久性修改原来, 参数为:list、dict

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

5个参数类别

关键字参数

位置参数

默认值(关键字/位置)参数

任意数量的位置参数(*args:空tuple)

任意数量的关键字参数(**kwargs:空dist)

实形参的匹配顺序:

非默认值参数 --> 默认值参数

位置参数 --> *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

返回值

return 任何数据类型(list、dist…)

基类

函数__init__()

两个下划线,默认方法。类中必有,当创建类的实例时,python首先自动调用它

形参self

一个指向实例的引用

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)

多个类(继承、封装、多态)

创建实例时,若子类有__init__(),则python不会调用父类的__init__()

若子类没有,则调用父类的__init__()

子类自动继承父类的属性和方法,self.即可

也可通过内置函数 super() 调用父类的属性和方法

super(). __init__()的位置很重要,如:

# 子类

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()

模块

函数和类的导入相似

import python标准库或第三方模块

【空行】

import 自己写的模块

函数模块

模块名: 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()

文件

文件路径:/ (windows:/或\\)

f:文件对象,输出可查看编码

with open("files/text_file.txt") as f:

print(f)

#

6种读写模式参数

以字符串读写

模式参数

描述

若文件不存在

若文件已存在

r (模式参数省略,默认为’r’)

w

创建

覆盖

a

创建

末尾追加,不覆盖

r+

读、写

覆盖

w+

读、写

创建

覆盖

a+

读、写

创建

末尾追加,不覆盖

以二进制读写

基本6种模式参数+‘b’,如 rb、rb+

读文件(r、r+)

读文件(r、r+)一定要要异常处理(FileNotFoundError)

# 全部读取 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)

写文件(w、w+、a、a+)

# 全部写 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

测试

unittest模块

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中

函数的测试

一个测试类:测试一个函数(全覆盖 or 测试用例)

一个测试类的方法:测试一个函数的某个方面(单元测试),方法名为

“test_”

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()

类的测试

测试一个类,主要是测试类中的所有方法

python先运行TestCase类的setUp()方法,再运行其他"test_"方法

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()

其他

输入:input()

s = input('Please input: ')

print(s)

prompt= 'Please input: '

s = input(prompt)

print(s)

静默处理:关键字pass

x = 2

y = 0

try:

z = x/y

except ZeroDivisionError:

pass

else:

print(z)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值