排序
hello = "hello python"
print(hello[::-1])
print(hello.lower())
print(hello.upper())
print(hello.find(hello, "hello", 1, 8))
运算符
price = float(input("橘子的单价是:"))
weight = float(input("顾客所买重量是:"))
print("您需要支付", weight * price, "元")
字符串查找
hello = "hello python"
# find 和 index 区别
print(hello.find("tython")) # 找不到返回-1
print("----------------------")
print(hello.index("tython")) # 找不到直接报错
格式化输出
price = 12.42
weight = 12.51
# # 占位符输出
print("{} * {} = {}".format(price, weight, price * weight))
# # 下标占位符输出
print("{0} * {0} = {1}".format(price, price * weight))
# # 指定小数点位数输出
print("{} * {} = {:.2f}".format(price, weight, price * weight))
# # 指定百分比位数输出
print("{} * {} = {:.2%}".format(0.5, 0.5, 0.53 * 0.5))
简洁版格式化输出
price = 12.42
weight = 12.51
# # 简洁格式化输出
print(f"{price} * {weight} = {price * weight}")
# # 指定小数点位数输出
print(f"{price} * {weight} = {price * weight :.2f}")
print(f"我吃饭了吗? {1 == 1}")
列表操作
Student_List = ["杨", "黄", "李", "张", "刘", "王"]
# 查找字符串
print(Student_List.index("黄"))
# # 切片,2开始,4结束,步长为1
print(Student_List[2:4:1])
# # 倒叙
print(Student_List[::-1])
# # 追加
Student_List.append("赵")
print(Student_List)
# # 插入
Student_List.insert(1, "何")
print(Student_List)
# # 合并
Student_List2 = ["哈哈哈"]
Student_List.extend(Student_List2)
print(Student_List)
# # 修改值
Student_List[1] = "尤"
print(Student_List)
# # 删除值
Student_List.remove("哈哈哈")
print(Student_List)
# # 通过下标删除值
del Student_List[1]
print(Student_List)
# # 删除列表最后一个
Student_List.pop()
print(Student_List)
# # 删除列表指定的值
Student_List.pop(-2)
print(Student_List)
# 查看成员是否存在
print("杨" in Student_List)
print("杨" not in Student_List)
# 排序sort,对源列表进行修改
Student_number = [1, 2, 4, 3, 5]
Student_number.sort()
print("升序后:", Student_number)
Student_number.sort(reverse=True)
print("降序后", Student_number)
#
# # 排序sorted,不修改源列表,生成新的列表
Student_number2 = [1, 2, 4, 3, 5]
list2 = sorted(Student_number2)
print("升序后:", list2)
list3 = sorted(Student_number2,reverse=True)
print("降序后", list3)
# 列表切片(生成新列表)
Student_number2 = [1, 2, 4, 3, 5]
# # 倒叙
print("倒叙后:", Student_number2[::-1])
# # 切片
print("切片后:", Student_number2[2:4:1])
# # 列表反转(对源列表修改)
print("反转前:", Student_number2)
Student_number2.reverse()
print("反转后:", Student_number2)
count = Student_number2.count(2)
print(count)
# 分隔符split(生成新的字符串,字符串是不可更改的)
Student_info = "姓名:可乐,年龄:22,岗位:测开工程师"
Student_info2 = Student_info.split(",")
print(Student_info2)
# 列表中的字符拼接
Student_item = ["哈哈哈", "呵呵呵", "嘻嘻嘻"]
Student_item2 = "?".join(Student_item)
print(Student_item2)
遍历列表
work = ["周一", "周二", "周三", "周四", "周五"]
for index in range(len(work)):
print(f"索引为: {index} , 值为: {work[index]}")
列表去重(两种方法)
# 列表去重
# 方法一:通过新的列表判断是否重复
list_arr = [1, 3, 4, 5, 1, 4, 22, 4, 8, 10]
new_list = []
for item in range(0, len(list_arr)):
if list_arr[item] not in new_list:
new_list.append(list_arr[item])
print(new_list)
# # 方法二:通过集合进行去重(高效)
res = set(list_arr)
print(res)
字典操作
person = {"name": "cola", "sex": "man", "age": "22"}
student = {"name2": "cola", "sex2": "man", "age2": "22"}
print(person["age"])
# # 修改(存在则修改,不存在则添加)
person["hobby"] = "basketball"
person["name"] = "yang"
print(person)
# 字典嵌套
student = {"name": "yang", "num": ["a", "b", "c"], "teacher": {"name": "huang"}}
print(student)
# 字典设置默认值,存在则不修改,不存在则新增
person.setdefault("name", "cola")
person.setdefault("hobby", "play game")
print(person)
# 字典合并,key唯一,如果key相同,则修改,否则就添加到字典末尾
teacher = {"Teacher_name": "zhangsan", "Teacher_age": "32"}
person.update(teacher)
print(person)
# 字典中获取内容
# 获取所有的keys
print("keys :", person.keys())
# # 获取所有的values
print("values :", person.values())
# # 获取所有键值对
print("全部为:", person.items())
# # 成员运算符
print("name" in person)
print("22" in person.values())
print("name" not in person.keys())
print(("name", "cola") in person.items())
遍历字典
# 遍历字典
# 键、值、键值对
# 1、键
for key in person:
print("键:", key)
# # 2、值
print("--------------")
for value in person.values():
print("值:", value)
print("--------------")
# # 3、键值对
for key, value in person.items():
print("键:", key, "值:", value)
元组
# # 第一种定义方法
data1 = (1,)
# # 第二种定义方法
data2 = 1, 2, 3
print(data1)
print(data2)
字符串反转操作
# 操作题1:i am cola 变成 cola am i
text = "i am cola"
text2 =text.split(" ")
print(text2)
text2.reverse()
" ".join(text2)
print(text2)
If条件判断
score = input("请输入分数")
if int(score) == 100:
print("nice!")
elif 60 <= int(score) <= 99:
print("good")
else:
print("oh no !")
number = input("请输入账户名")
if number == "admin":
password = input("请输入密码")
if int(password) == 123456:
print("welcome")
else:
print("密码错误")
列表判断
work = ["周一", "周二", "周三", "周四", "周五"]
wekk = ["周六", "周日"]
text = "休息"
day = input("周几啊?")
if day in work:
print("要上班")
else:
print("不用上班,周末咯!")
while循环
#while循环
number = 15
while number >= 10:
print("我还在跑呢")
number -= 1
if number == 12:
print("我不跑了")
break
# break和continue
for day in work:
if day == "周五":
print("今天不上班,美滋滋")
if day == "周一":
continue
print(day == "周三")
print("今天要上班哦")
if day == "周三":
break
双重for循环
for item in range(2, 6):
for index in range(1, item):
print(index, end=" ")
print()
九九乘法表
for item in range(1, 10):
for index in range(1, item+1):
print(f"{index}*{item}={index * item} ", end="\t")
print()
方法
# # 方法def
input_day = input("请输入当前是周几")
#
#
def get_day(input_day):
if input_day in work:
print("今天需要上班")
elif input_day in wekk:
print("今天是周末")
else:
print("错误输入")
# 调用方法
get_day(input_day)
冒泡排序
个人理解:
冒泡排序 思维:先遍历整个数组,就是第一个for循环,然后在遍历数组的同时,里面的相邻每一项对下一个值进行对比从而每一次循环的时候,得出一个最大的值
因为有7个值,其实只需要找出6个最大的即可,这就是为什么len(number)-1-item,需要减1,然后最大的就不需要再比了,就减去i,意思是比了几个最大的,就少比几个,就这样循环,每次得出一个最大的,最后就形成了冒泡排序
number = [1, 3, 4, 34, 11, 2, 55, 42]
for item in range(0, len(number)):
for index in range(0, len(number)-1-item):
if number[index] > number[index+1]:
temp = number[index]
number[index] = number[index+1]
number[index+1] = temp
print(number)
方法传参(两种方法)
# 方法传参(一)-加了星号 * 的参数会以元组(tuple)的形式导入,存放所有未命名的变量参数。
def add(num, *args):
number = num
for item in args:
number += item
print(number)
#
add(1, 2, 3, 4)
# 方法传参(二)-加了两个星号 ** 的参数会以字典的形式导入。
def add(**args):
print(args)
#
add(name="张三", age="16")
return语句
def get_ID(id, password):
login = False
if id == "admin":
if password =="123":
login = True
return login
else:
login = False
return login
status = get_ID("admin2", "123")
print(status)
拆包(列表,字典)
number_list = [1, 3, 4, 5]
number_dit = {"salar": "12000", "award": "3000"}
def sum(*args):
print("我的格式是元组:", args)
number = 0
for item in args:
number += item
print(number)
def money(**args):
print("我的格式是字典:", args)
print(args)
range用法
sum_num = 0
for item in range(0, 10):
sum_num += item
print(item)
print("最终结果为:", sum_num)
文件操作(读取,写入),打开后需要关闭
# 读取
new_file = open("hello.txt", encoding="UTF-8")
# 全部读取,由于底层是C实现,考虑到指针问题,读取到最后一行时,后面再读取时指针已经到了末尾,不会重新读取
# 在写入的时候也一样,到了最后一行,这个时候去读取,也是读不到数据的,需要先close,再打开,这样指针就到了开头
print(new_file.read())
# 单行读取
print(new_file.readline())
# 多行读取
print(new_file.readlines())
# # 写入
new_file = open("hello2.txt", encoding="UTF-8", mode="w")
new_file.write("aaa\n")
new_file.write("bbb\n")
new_file.close()
# # 列表写入
data_list = ["哈哈哈\n", "呵呵呵"]
new_file.writelines(data_list)
new_file.close()
# 写入追加
new_file = open("hello2.txt", encoding="UTF-8", mode="a")
new_file.write("呵呵呵呵呵。")
new_file.close()
# with自动关闭文件操作
with open("hello2.txt", encoding="UTF-8", mode="a") as new_file:
new_file.write("\n我是自动关闭的")
文件操作题
# 文件操作练习题
# 遍历字典中的内容,写入txt中
people_list = [{"name": "张三", "age": "18", "sex": "man"}, {"name": "呵呵", "age": "18", "sex": "man"}]
with open("hello2.txt", encoding="utf-8", mode="w") as person_list:
for item in people_list:
print(item)
person_list.write(f"{item['name']}, {item['age']}, {item['sex']}\n")
# 将文件中的内容,写入到字典中,格式为[{```,```,```}, {```,```,```}]
people_list = []
with open("hello3.txt", encoding="utf-8", mode="r") as person_list:
for data in person_list.readlines():
new_data = data.strip("\n")
new_people_str = new_data.split("@")
people_dit = {}
for item in new_people_str:
new_item = item.split(":")
people_dit[new_item[0]] = new_item[1]
people_list.append(people_dit)
print(people_list)
导库、导库
导库规范PEP8,代码顺序优先级:标准库>第三方>自定义
导包(在包下) from ···· import···· as 别名
# from 文件夹 import 模块名 as 别名
from sumFunction import sum
# 标准os包导入
import os
file_path = os.listdir(f"F:\pythonWorkSpace\pythonProject")
print(file_path)
文件目录操作
# # 文件的绝对目录
file_abspath = os.path.abspath(__file__)
print(file_abspath)
# # 文件的所在目录
file_path_2 = os.path.dirname(__file__)
print(file_path_2)
# # 路径拼接
file_abspath_join = os.path.join(file_abspath, "hello.txt")
print(file_abspath_join)
异常处理
try:
res = 100 / 20
res2 =100 / "h2"
print(res2)
# # 抛出异常时,需要标注错误类型,否则会报PEP8错误,没有指明错误类型,不标注的话为Base exception
except ZeroDivisionError as zero:
print("异常捕捉")
print("ZeroDivisionError错误", zero)
except Exception as e:
print("Exception错误", e)
else:
print(res)
finally:
print("运算完毕")
类和方法、属性
方法包括(类方法、实例方法、静态方法)
属性(类属性,实例属性)
class People:
# 类方法
@classmethod
def People(cls):
print("没改之前是:", cls.name)
cls.name = "我改成类名了"
print(cls.name)
# 类属性
name = "可乐"
# 静态方法
@staticmethod
def People_name():
print("hhhh")
# 生成对象时,自动初始化
def __init__(self, name, age, sex):
"""
:param name:
:param age:
:param sex:
"""
# 实例属性
self.myname = name
self.myage = age
self.mysex = sex
# 私有化包括两种,浅度私有化(_属性)子类可以继承,深度私有化(__属性)子类无法继承,(类,函数,属性,都可以私有化,外部无法访问,只能内部提供方法给外部访问)
# 浅度
_people_age = "18"
# 深度
__people_money = "100,000,000"
# 提供外部访问方法
def get_people_money(self):
print(self.__people_money)
def eat(self):
print("eat方法")
self.People_name()
def look(self):
print("look方法")
def eat_look(self):
# 类里面,方法可以互相调用但是不能修改,属性可以互相拿并修改
self.eat()
self.look()
类的继承
class Man(People):
# 重写
def eat(self):
print("我是子类的eat方法")
# 当有和父类同名的函数时,需要使用到super
super(Man, self).eat()
zhangsan = Man("张三", 18, "男")
print(zhangsan.myname)
zhangsan.eat()
类的实际操作
class Student:
def __init__(self, name, age, garde):
self.name = name
self.age = age
self.grade = garde
def info(self):
print(self.name, self.age, self.grade)
class School:
def __init__(self):
self.Student_number = []
def addStudent(self, Student_obj: Student):
if Student_obj not in self.Student_number:
self.Student_number.append(Student_obj)
print("添加成功")
Student_obj.info()
else:
print("已存在")
zhangsan = Student("张三", "16", "三年级")
lisi = School()
lisi.addStudent(zhangsan)
日志
# 日志
# 日志级别:debug(代码调式级别)-info(基本信息)-warning(警告)-error(报错)-critical(内存溢出等严重错误)
# root收集器可以收集warning级别以上的日志
# 导入日志模块的包
import logging
logging.info("INFO")
logging.debug("DEBUG")
logging.warning("warning")
logging.error("ERROR")
logging.critical("CRITICAL")
# 自定义日志
# 定义一个日志类
mylog = logging.getLogger("mylog")
# 设置日志级别
mylog.setLevel(logging.INFO)
# 设置日志输出格式
mylog_formatter = "%(asctime)s %(name)s %(levelname)s %(lineno)d "
# 生成日志格式类
mylog_Format = logging.Formatter(mylog_formatter)
# 使用控制台/文件输出
handel = logging.FileHandler("D:/log.txt", encoding="UTF-8")
handel = logging.StreamHandler()
# 设置控制台输出的格式
handel.setFormatter(mylog_Format)
# 将自定义类绑定到控制台输出中
mylog.addHandler(handel)
mylog.info("INFO")
mylog.debug("DEBUG")
mylog.warning("warning")
mylog.error("ERROR")
mylog.critical("CRITICAL")
# 滚动日志
from logging import handlers
handlers.RotatingFileHandler
handlers.TimedRotatingFileHandler
handel2 = handlers.RotatingFileHandler("D:/log2.txt", maxBytes=1, backupCount=10, encoding="UTF-8")
handel2.setFormatter(mylog_Format)
# # 将自定义类绑定到控制台输出中
mylog.addHandler(handel2)
mylog.info("INFO")
mylog.debug("DEBUG")
mylog.warning("warning")
mylog.error("ERROR")
mylog.critical("CRITICAL")
自定义日志操作
from Log.Logs import log
class LogTest:
def __init__(self, username, pwd):
self.name = username
self.password = pwd
def logging(self):
if self.name == "admin":
if self.password == "123":
print("登录成功")
log.info(f"当前登录账号为{self.name},密码为{self.password}")
else:
print("用户名或者密码错误")
log.warning(f"当前登录账号为{self.name},密码为{self.password}")
log.error(f"当前登录账号为{self.name},密码为{self.password}")
else:
print("用户名或者密码错误")
log.warning(f"当前登录账号为{self.name},密码为{self.password}")
test =LogTest("admin", "1234")
test.logging()
扩展(pytest)参数化执行用例
class TestParam:
list_arr = [{"username": "admin", "pwd": "123"},
{"username": "admin", "pwd": "123"},
{"username": "admin", "pwd": "1234"},
{"username": "admin2", "pwd": "123"},
{"username": "admin", "pwd": "admin"}]
@pytest.mark.parametrize("data", list_arr)
def test_add(self, data):
return_code = 1
if data["username"] == "admin":
if data["pawd"] == "123":
return_code = 0
assert 0 == return_code
else:
assert 0 == return_code
else:
assert 0 == return_code
总结
以上是学习python基础中的一些个人代码笔记,以及对于基础知识的一些理解,菜鸟编写不好的地方请多多谅解,欢迎评论交流🤤
{"username": "admin", "passwd": "123"},
{"username": "admin", "passwd": "1234"},
{"username": "admin2", "passwd": "123"},
{"username": "admin", "passwd": "admin"}]
@pytest.mark.parametrize("data", list_arr)
def test_add(self, data):
return_code = 1
if data["username"] == "admin":
if data["passwd"] == "123":
return_code = 0
assert 0 == return_code
else:
assert 0 == return_code
else:
assert 0 == return_code
总结
以上是学习python基础中的一些个人代码笔记,以及对于基础知识的一些理解,菜鸟编写不好的地方请多多谅解,欢迎评论交流🤤