基础知识
-
字符串
-
"这个整体是字符串" 字符串可以用 + 连接
-
转义符
- ""='',但是混用需要注意,最外面的为字符串标识符
- 里面的一对引号可以直接用,如果里面多个引号,在引号前加上\转义符
-
换行符
- \n
-
将代码换行识别为打印换行
- """xxx"""或'''xxx'''
-
-
变量
-
赋值操作
-
X1 = "123" 下面是重新赋值 X2 = X1 X1 = "1234"
-
-
变量名规则
- 英文(区分大小写)、数字、下划线
- 不能数字开头
- 通常使用英文单词做变量名,字母全部小写,下划线分隔不同单词
- 避免关键词
-
-
数字运算
-
字符串、数值、浮点数
- "6"、6、6.0
-
运算顺序:()>** **(1/2) > />+-
-
math 函数库
-
import math result = math.函数名() print 求根公式 delta = b ** 2 -4 * a * c (-b + math.sqrt(delta)) / (2 * a) (-b - math.sqrt(delta)) / (2 * a)
-
-
-
注释
-
# 这是一行注释,只是一行,下一行不归我管 修改为注释快捷键:ctrl+/
-
-
数据类型
-
字符串 str
- len('666')→3:查询字符串长度
- 'hello'[0] →h:索引获取单个字符
-
整数 int 浮点数 float
- 6、6.0
-
布尔类型 bool
- True、False
- 注意首字母大写
-
空值类型 NoneType
-
type()返回数值类型
-
基本语句
条件语句
if [条件]:
[执行语句]
[执行语句]
else:
[执行语句]
[执行语句]
#需要有缩进
#[条件]可以是属于布尔数值的变量
#如:a = True
#if a:
#比较运算符
== != > >= < <=
#范围
15 < a <= 16
#嵌套条件语句1
if []:
if[]:
[]
else:
[]
else:
[]
#嵌套条件语句2
if []:
[]
elif []:
[]
elif []:
[]
else:
[]
逻辑算法
- and、or、not
- and、or 多个对象
- not 单个对象
数据列表
列表 list(可变)
shopping_list = ["keyboard", "mouse"]
# 添加元素进列表的方法
shopping_list.append("monitor")
# 去除元素的方法
shopping_list.remove("monitor")
# 求列表中元素数的函数
len(shopping_list)
# 索引列表中第一个个元素
shopping_list[0]
# 常用方法:max\min\sorted
元组 tuple(不可变)
example_tuple =("键盘”,"键帽")
字典 dict(可变)
键值对:Key: value
contacts = {"key1" : "1"}
# 将元组作为键
contacts = {("张伟",23):"15000000000"
("张伟",34):"150000O0001"
("张伟",56):"15000000002"
# 查询键名
print(contacts[("张伟",23)])
得到15000000000
# 往字典中添加键值对,如果已有键则覆盖原值
contacts["美女A"] ="18600000000"
# 是否存在键
"小明” in contacts
# 删除,输入的键不存在会报错
del contacts["小明"]
# 查询键值对数
len(contacts)
# 所有键
temperature_dict.keys()
# 所有值
temperature dict.values()
# 所有键值对
temperature dict.items()
循环迭代
for 循环
temperature list = [36.4,36.6,36.5]
for temperature in temperature list
if temperature >= 38:
print(temperature)
print("完球了")
temperature_dict = ["111":36.4, "112":36.6, "113":36.2, "113":36.2]
# .items()行为运行时,变量会被赋值给对应元组。下面是将键赋值给staff_id,值赋值给temperature。
for staff_id, temperature in temperature dict.items():
if temperature >= 38:
print(staff_id)
#上面等于下面的程序
for temperature_tuple in temperature_dict.items():
staff_id = temperature_tuple[0]
temperature = temperature_tuple[1]
if temperature >= 38:
print(staff id)
#range(开始值, 结束值, 步长),结束值不在范围内
#1+2+3+···+100=?
total = 0
for i in range(1,101):
total = total + i
print(total)
while 循环
while 条件A:
行动B
# while循环,行动直至条件A为假
# for与while的转换
# 1
for char in list1:
print(char)
# 2
for i in range(len(list1)):
print(list1[il)
# 3
i=0
while i < len(list1):
print(list1[il)
i=i+1
# for循环适用于有明确的条件和循环次数
# while适用于不明确循环次数
格式化字符串
name = "老林"
year = "虎"
message_content = f'''
律回春渐,新元肇启。
新岁甫至,福气东来。
金{year}贺岁,欢乐祥瑞。
金{year}敲门,五福临门。
给{name}及家人拜年啦!
新春快乐,{year}年大吉!'''
gpa_dict = {"小明":3.251,"小花":3.869,"小李":2.683
"小张":3.685}
for name, gpa in gpa_dict.items():
print("{0}你好,你的当前绩点为: {1:.2f}".format(name,gpa))
# 2f表示保留两位小数
函数
input 函数
user_input = input("这是给用户的提示")
# input返回的是字符串
# 转换参数类型
int(user_input) str(user_input)
定义函数
def calculate sector_1():
# 接下来是一些定义函数的代码
central_angle_1 = 160
radius_1 = 30
sector_area_1 = central angle_1 / 360 *3.14 * radius_1 ** 2
print(f"此扇形面积为: {sector_area_1}")
# 以下是设参后的函数定义
def calculate_sector(central_angle, radius):
# 接下来是一些定义函数的代码
sector_area = central angle / 360 * 3.14 * radius ** 2
print(f"此扇形面积为: {sector_area}")
# 定义函数中定义的变量,只是局部定义,需要全局定义,加上return返回变量
# print append返回值为None
# len sum 具有返回值
return sector_area
导入模块
# 导入后需要引用函数名
import statistics
statistics.median()
# 导入后不需要引用(不推荐导入所有,无需引用会弄乱)
from statistics import median
from statistics import *
median()
# 安装第三方库
pip instal aken
import aken
面对对象编程
对象绑定属性(变量)
#定义ATM类
class ATM:
def __init__(self,编号,银行,支行):
self.编号 = 编号
self.银行 = 银行
self.支行 = 支行
# 创建两个ATM对象
atm1 = ATM("001","招商银行","南园支行")
atm2 = ATM("002",“中国银行",“北园支行")
#定义纸币类
class 纸币:
def __init__(self,编号,面值,发行年
self.编号 =编号
self.面值 = 面值
self.发行年份 = 发行年份
# 创建两个纸币对象
纸币1 = 纸币("AA0000000O", 50, "2015")
纸币2 = 纸币(“AA00000001", 100, “2020")
def 存钱(ATM对象,纸币对象):
打印记录("存钱”, ATM对象, 纸币对象份)
def 取钱(ATM对象,纸币对象):
打印记录("存钱”, ATM对象, 纸币对象份)
存钱(atm1, 纸币1)
取钱(atm2, 纸币2)
对象绑定方法(函数)
class 洗衣机:
def __init__(self,容量):
self.容量 = 容量
def 清洗(self,需清洗物品):
# 需要通过容量计算烘干时长
洗衣机容量 = self.容量
def 烘干(self,需烘干物品):
# 需要通过容量计算烘干时长
洗衣机容量 = self.容量
面对对象编程的封装、继承和多态
封装:简化代码
继承:存在父类和子类
多态:不同类执行不同方法
命名方法
-
下划线命名法
- 适用于变量名
- eg. user_name
-
Pascal命名法
- 适用于类型名
- eg. UserName
创建对象
# 定义一个类别
class ATM:
def __init__(self,编号,银行,支行, bank_name):
self.编号 = 编号
self.银行 = 银行
self.支行 = 支行
self.name = bank_name
def speak(self)
# ATM编号多少就发多少个感谢
print("感谢" * self.编号)
# 创建对象
atm1 = ATM("0123", "柳州银行", "北京朝阳支行", bjcyzh)
print(f"我在{atm1.银行}{atm1.支行},进行了操作,银行标识为{atm1.编号}和{atm1.bank_name}")
# 练习题:属性包括学生名称、学号、成绩,能够设置学生成绩,打印相关属性
class Student:
def __init__(self, name, student_id):
self.name = name
self.student_id = student_id
self.grades ={"语文":0,"数学":0,"英语": 0}
def set_grade(self, course, grade):
if course in self.grades:
self.grades[course]= grade
def print_grades(self):
print("学生{self.name}(学号:{self.student_id})的成绩为:")
for course in self.grades:
print(f"{course}:{self.grades{course}}分")
chen = Student("小陈","100618")
zeng = Student("小曾","100622")
print(chen.name)
zeng.set_grade("数学",95)
print(zeng.grades)
print(chen.print_grades)
创建有继承关系的类
# 在子类后面加上括号父类,属性构造或方法调用优先自身
class Human(Mammal):
# A是B,即写为
class A(B)
文件操作
路径与目录
-
绝对路径
-
linux
- /home/data
-
windows
- C:\home\data
-
-
相对路径
- ../(上级目录)
- ./(当前目录,可省略)
- ./data
- ./data/a.py
读取文件
# 读取
f = open("./xyz.txt", "r", encoding="utf-8")
# 读取全文,并以字符串打印
print(f.read())
# 第二次read,会读空字符串
print(f.read())
# 读取1-10个字节内容
print(f.read(10))
# 第二次read接着往下读,读取11-20个字节内容
print(f.read(10))
# 会读一行内容,包括换行符(会和下一行空一行)
print(f.readline())
# 会读再一行内容,包括换行符
print(f.readline())
# 读第一行
line = f.readline()
# 判断当前行是否为空
while line != "":
#不为空则打印当前行
print(line)
# 读取下一行
line = f.readline()
# readlines会读全部文件内容,并把每行作为列表元素返回
print(f.readlines())
#把每行内容储存到列表里
lines = f.readlines()
for line in lines:
# 打印当前行
print(line)
f = open("./data.txt")
#对文件的操作
print(f.read())
# 关闭文件,释放资源
f.close()
# 命名打开,无需调用close,自动关闭释放
with open("./data.txt") as f:
#对文件的操作
print(f.read())
写文件
# w写入,如果文件不存在,程序自动创建;如果已存在,原文件会被清空
f = open("./xyz.txt", "w" encoding="utf-8")
with open("./xyz.txt", "w" encoding="utf-8") as f:
# 写入不会自动换行,需要手动加换行符
f. write("Hello!\n")
f. write("Yoooo" )
# a写入,如果文件不存在,程序报错;如果已存在,原文件会被补充
f = open("./xyz.txt", "a" encoding="utf-8")
with open("./xyz.txt", "a" encoding="utf-8") as f:
# 写入不会自动换行,需要手动加换行符
f. write("\nHello!\n")
f. write("Yoooo" )
# r+读写模式,如果文件不存在,程序自动创建;如果已存在,原文件会被补充,并可以进行读操作
f = open("./xyz.txt", "r+" encoding="utf-8")
with open("./xyz.txt", "r+" encoding="utf-8") as f:
Debug
捕捉异常
try:
user_weight = float(input("请输入您的体重(单位:kg)")
user_height = float(input("请输入您的身高(单位:m)")
user BMI =user weight /user height ** 2
except ValueError:
print("输入不为合理数字,请重新运行程序,并输入正确的数字。")
except ZeroDivisionError:
print("身高不能为零,请重新运行程序,并输入正确的数字。")
except:
print("发生了未知错误,请重新运行程序。")
else:
print("您的BMI值为:" + str(user BMI))
finally:
print("程序结束")
测试
# assert加布尔表达式,True运行,False报错并终止
assert 1+2>6
# unittest 对最小可测试单元进行测试
import unittest
# 通常另外建立文件进行测试
# 在测试文件中调用同一目录下的文件my_calculatord的函数my_adder
import unittest
from my_calculator import my_adder
class TestMyAdder(unittest.Testcase):
def test_positive_with_positive(self):
self.assertEqual(my_adder(5,3), 8)
def test_negative_with_positive(self):
self.assertEqual(my_adder(-5,3), -2)
# 在终端中运行unittest
python -m unittest
# 各种方法
assertEqual(A,B)→assert A == B
assertTrue(A)→assert A is True
assertIn(A, B)→assert A in B
assertNotEqual(A,B)→assert A != B
assertFalse(A)→assert A is False
assertNotIn(A, B)→assert A not in B
# 创建测试对象属性
def setUp(self):
self.sentence =Sentence("hello world!")