一、print
print("1"+"2"+"3")
print("---------------------")
print('Let\'s go')
print("---------------------")
print('1\n2换行')
print("---------------------")
print("""131231231
13123换行
123123
"""+"s水水水水")
注意三引号可以输出整个文本二、变量
greet="你好,"
greet_english=greet+"hello,"
my_love="12345678"
print(greet+"拨打:"+my_love)
print(greet_english+"拨打:"+my_love)
三、计算
import math
a=-1
b=-2
c=3
delte=b**2-4*a*c
print((-b+math.sqrt(delte))/(2*a))
print((-b-math.sqrt(delte))/(2*a))
四、注释 # """ """
#一元二次方程计算
""""22222222222"""
五、数据类型
1、字符串
(1) "哈哈" 'hh'(2) len('hhh!!') 5(3) "Hello"[2]="l"2、整数 int 浮点型float
3、 布尔类型bool
True False 大写4、空值类型 NoneType
None六、数据转换 int() str()
# BMI = 体重/(身高**2)
weight = float(input("请输入您的体重(单位:kg)"))
height = float(input("请输入您的身高(单位:m)"))
BMI = weight / (height ** 2)
print("你的BIM值为:"+str(BMI))
七、条件判断 if elif else
if_bool=int(input("和10比较的数:"))
if if_bool>10:
print(11)
print("hahaha")
print("大于10")
else:
print("小于10")
# BMI = 体重/(身高**2)
weight = float(input("请输入您的体重(单位:kg)"))
height = float(input("请输入您的身高(单位:m)"))
BMI = weight / (height ** 2)
print("你的BIM值为:" + str(BMI))
if BMI <= 18.5:
print("偏瘦")
elif 18.5 < BMI <= 25:
print("正常")
elif 25 < BMI < 30:
print("偏胖")
else:
print("肥胖")
八、逻辑运算 and or not
优先级 not > and > or九、列表 list
append 添加remove 去除len 长度max 最大值min 最小值sorted 排序shop_list=[]
shop_list.append("键盘")
shop_list.append("键帽")
shop_list.append("音响")
shop_list.remove("键帽")
print(shop_list)
shop_list[1]="电竞椅"
print(shop_list)
print(len(shop_list))
print(shop_list[0])
price=[799,233,323,6666]
max_price=max(price)
print(max_price)
min_price=min(price)
print(min_price)
sorted_price=sorted(price)
print(sorted_price)
十、字典
d = {key1 : value1, key2 : value2 }
slang_dict={"需求 id":"24682642","需求名称":"BSBM分支保养规则优化"}
slang_dict["需求描述"]="1、在保养规则管理页面的编辑弹窗中删除所需备件和保养内容字段"
slang_dict.key() #所有键
slang_dict.values() #所有值
slang_dict.items() #所有键值对
temp_dict={"小米":36.7,"小黑":37.7,"小红":38.7,"小哈":40.7}
for name,temp in temp_dict.items():
if temp>=38:
print(name,temp)
tinydict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
del tinydict['Name'] # 删除键是'Name'的条目
tinydict.clear() # 清空字典所有条目
del tinydict # 删除字典
十一、循环语句
1、for
# 定义一个列表
fruits = ["apple", "banana", "cherry"]
# 使用for循环遍历列表中的元素
for fruit in fruits:
print(fruit)
apple
banana
cherry
# 遍历字符串中的字符
for char in "Python":
print(char)
P
y
t
h
o
n
2、while
a=1
while a<10:
print(a)
a+=2
totol = 0
count = 0
user_input = input("请输入数字 q结束: ")
while user_input != "q":
num = float(user_input)
totol = totol + num
count = count + 1
user_input = input("请输入数字 q结束: ")
if count == 0:
result = 0
else:
result = totol / count
print("平均值:" + str(result))
十二、range
不包括结束值totol=0
for i in range(1,101):
totol=totol+i
print(totol)
十三、format 方法 格式化字符串
# 使用format()方法格式化字符串
name = "Alice"
age = 30
height = 5.8
# 使用位置参数
result_pos = "Name: {0}, Age: {1}, Height: {2}".format(name, age, height)
# 使用关键字参数
result_key = "Name: {n}, Age: {a}, Height: {h:.2f}".format(n=name, a=age, h=height)
# 使用 f-string 格式化字符串
result_stringf = f"Name: {name}, Age: {age}, Height: {height}"
# 控制浮点数的小数位数
result_float = "Height: {:.2f}".format(height)
# 打印结果
print(result_pos) #Name: Alice, Age: 30, Height: 5.8
print(result_key) #Name: Alice, Age: 30, Height: 5.80
print(result_stringf) #Name: Alice, Age: 30, Height: 5.8
print(result_float) #Height: 5.80
十四、函数
def bmi_fun(weight, height):
# BMI = 体重/(身高**2)
bmi = weight / (height ** 2)
if bmi <= 18.5:
return "偏瘦"
elif 18.5 < bmi <= 25:
return "正常"
elif 25 < bmi < 30:
return "偏胖"
else:
return "肥胖"
# 使用函数参数而不是外部变量
weight_input = float(input("请输入您的体重(单位:kg)"))
height_input = float(input("请输入您的身高(单位:m)"))
print(bmi_fun(weight_input, height_input))
十五、引用模块 import
1、官方
import statistics
print(statistics.median([1,3,5]))
Python 标准库 — Python 3.13.0a2 文档https://docs.python.org/zh-cn/3.13/library/index.html 2、第三方
PyPI · The Python Package Indexhttps://pypi.org/import akshare
print(akshare.get_cffex_daily("20240103"))
十六、类和对象
class MyClass:
# self 用于表示对象自身
def __init__(self, name, age):
self.name = name
self.age = age
def print_info(self):
print(f"Name: {self.name}, Age: {self.age}")
my_class = MyClass("xw", 25)
my_class2 = MyClass("xw", "点紧急") #可以任何类型
my_class.print_info()
my_class2.print_info()
Python 是一种动态类型语言,而C# 是一种静态类型语言。在动态类型语言中,变量的类型是在运行时动态确定的,而在静态类型语言中,变量的类型是在编译时静态确定的。这就是为什么在 Python 中你可以在运行时将不同类型的值赋给同一个属性,而在 C# 中则需要在编译时指定属性的类型十七、继承
继承、重写、多继承class ParentClass1:
def __init__(self, name):
self.name = name
def display_name(self):
print(f"Name: {self.name}")
def speak(self):
print("Parent speaking")
def talk(self):
print("Parent1 talk")
class ParentClass2:
def talk(self):
print("Parent2 talk")
class ChildClass(ParentClass1, ParentClass2):
def __init__(self, name, age):
# 调用父类的构造函数
super().__init__(name)
self.age = age
def display_info(self):
# 调用父类的方法
self.display_name()
print(f"Age: {self.age}")
def speak(self):
print("Child speaking")
# 创建子类的实例
child_instance = ChildClass("Alice", 25)
# 调用子类的方法
child_instance.display_info() #Name: Alice Age: 25
# 调用子类的方法,将调用重写的方法
child_instance.speak() #Child speaking
# 多父类 存在相同的方法 ?????
child_instance.talk() #Parent1 talk
# 类的解析顺序 MRO
print(ChildClass.mro()) #[<class '__main__.ChildClass'>, <class '__main__.ParentClass1'>, <class '__main__.ParentClass2'>, <class 'object'>]
注意:多父类 存在相同的方法 涉及到类的方法解析顺序(Method Resolution Order,MRO)通过 print(M.mro()) 输出MROsuper() 连接 继承链 在 Python 中,super() 是一个用于调用父类方法的特殊函数。它的主要目的是解决多重继承中的方法调用顺序问题,以及确保每个类的方法都被正确调用且不会重复class A:
def method(self):
print("A method")
class B(A):
def method(self):
print("B method")
super().method()
class C(A):
def method(self):
print("C method")
super().method()
class D(A):
def method(self):
print("D method")
#super().method()
class M(B,D, C):
def aaa(self):
print("aaa")
# 打印 D 类的 MRO
print(M.mro())
# 创建 D 类的实例并调用 method 方法
d_instance = M()
d_instance.method()
输出[<class '__main__.M'>, <class '__main__.B'>, <class '__main__.D'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>]
B method
D method
十八、文件
1、Open 函数
open (file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
(1) file(文件名或路径):
- 字符串,包含文件名或文件路径。
- 可以是相对路径或绝对路径。
(2) mode(打开文件的模式):
- 'r': 只读模式,打开文件进行读取。
- 'w': 写入模式,创建新文件或截断已存在文件。(覆盖)
- 'a': 追加模式,打开文件用于写入,将数据写到文件末尾。
- 'b': 二进制模式,用于处理二进制文件。
- 'x': 独占创建模式,如果文件已存在则创建失败。
(3) encoding(文本文件的编码格式):
- 指定文本文件的编码,例如 'utf-8'。
- 如果不指定,默认使用系统默认编码。
filetxt = "C:\\Users\\xingwang\\Desktop\\183.txt" #绝对路径
file_open= open(filetxt,"r",encoding="utf-8")
print(file_open.read(2)) #读2个字符
print(file_open.readline()) #读一行
print(file_open.readlines()) #一次读完全部行
print(file_open.read()) #会读全部的文件内容,并打印
print(file_open.read()) #会读空字符串,并打印 因为读到末尾了
file_open.close() #打开open 就要关闭 释放资源
释放资源 类似C# usingfiletxt = "C:\\Users\\xingwang\\Desktop\\183.txt"
with open(filetxt,"r",encoding="utf") as file_open:
print(file_open.read())
2、相对路径 绝对路径
十九、异常处理
从上往下运行try:
file_txt = "C:\\Users\\xingwang\\Desktop2\\183.txt"
with open(file_txt, "r+", encoding="utf") as file:
file.write("Hello!\n")
file.write("000000")
#except IOError:
#print("Error:没有找到文件或者读取文件失败")
except Exception as e:
print(f"发生了异常:{e}")
except:
print("error")
else:
print("success")
finally:
print("finally")
二十、单元测试 unittest(库) assert
1、引用其他文件from 模块 ipmort 函数2、测试单元 文件名字 test_开头 函数名字 test_开头3、终端使用 python -m unittest 测试开始一个点 代表 运行一个测试用例成功F. 代表错误 失败 标签:基本,name,self,语法,file,print,method,def From: https://www.cnblogs.com/buzheng11/p/17980184