Python基础笔记

随机数

需要先引入: import random

1~100的整数:random.randint(1,100)

1~100的小数:random.uniform(1,100)

直接获取0~1的随机数: radom.radom

input输入 以及强制转换

age = input("输入年龄:")
after_age= int(age)+10      #input输入为字符串类型需要转换为数值类型才可加减
print("十年后年龄为:"+str(after_age)+"岁") 	#print必须为同类型

次方

a的次方:a = a**10 / a **= 10

布尔值

与运算:and

或运算:or

非对应:not

字符串复制/拼接

复制: 字符串 * 2

拼接:直接相加 +

python严格的格式缩减

a = 11

if a % 2 == 0:

    print("是偶数")          # 一个TAB或者四个空格

else:

    print("不是偶数")

print("end")

for循环另一写法

for i in range(10):        #range(10)表达的为一个0~9的一个迭代器[0,10)

    print(i)

arr = [1,3,5,7]

for i in arr:

    print(i)

string = "CSGONB"

for i in string:
    print(i)

字符串切片

s = "my name is csz"

a = s[1:5]

b = s[1:3:1]    # 第三个数表示步长   **1表示依次输出**   **2表示间隔1输出**

c = s[::-1]     # 表示倒取字符串

d = s[-3:]     # 表示下标倒取

字符串替换、分割、拼接

s = "my name is csz"
a = s.replace("csz","csz666")
print(a)
b = s.split(" ")
print(b)
c = "-".join(b)
print(c)

字符串方法

#转换大小写
a = "hellO python"
b = a.capitalize()
c = a.title()
d = a.lower()
e = a.upper()

#删除空白字符
f ="    hello".lstrip()
g ="hello    ".rstrip()
h ="  hello  ".strip()
print(b+"\n"+c+"\n"+d+"\n"+e+"\n"+f+"\n"+g+"\n"+h+"\n")

使用下标从字符串中获取字符/列表

str = "csz"
s = str[1]
print(s)

arr = [1,2,3,4]
a = arr[2]
print(a)

#列表嵌套
arr = [[1,2,3],[4,5,6],[7,8,9]]
a = arr[2]
b = arr[2][2]
print(b)

arr = [
    [[1,2,3],[4,5,6],[7,8,9]],
    [[2,2,3],[4,5,6],[7,8,9]],
    [[1,2,3],[4,5,6],[8,8,9]]
]
b = arr[2][2][0]
print(b)
#遍历arr
for a in arr:
    for b in a:
        for c in b:
            print(c)

f字符串

name = "Alice"
age = 30
print(f"Hello, {name}! You are {age} years old.")  # 输出:Hello, Alice! You are 30 years old.

#用f字符串循环打印出对应信息
scores = {"csz":98,"yk":66,"yr":100}
for name,score in scores.items():
    print(f"您好{name}您的成绩为{score}")

判断元素是否在列表里

c = 12
a = [1, True, "nice", c, [1, 2, 3]]
if "nice" in a:			#判断不在为 not in 
    print("YES")
else:
    print("NO")

操作列表元素

a = [1, True, "nice", 12, [1, 2, 3]]

b = a.copy()		#复制列表
a.append("csz666")   #列表最后插入csz666
a.insert(1,'csz666')  #在下标1之前插入csz666
a.pop(0)				#移除下标为0的元素
a.remove(12)			#移除值为12的
a.clear()				#移除整个列表
a[0] = 123				#直接替换下标为0的数值

#列表排序
a = [4,2,1,5,3]
a.sort()
a = sorted(a)
print(a)

元组

a = (1,2,1.2,"string")
print (a[0])

for i in a:    #for循环遍历元组
    print(i)

集合

s = {1,2,3,3,2,1}
print(s)
#{1, 2, 3}

字典

d = {"name":"pig","age":"22"}
print(d.keys()) 		#输出键
print(d.values())		#输出值
print(d.items())		#输出整个字典

for k,v in d.items():    #遍历输出键和值
    print(k)
    print(v)

print(d["name"])		#输出键name的值
d["age"]="18"			#修改键age的值为18
print(d["age"])			#输出键age的值

del d["age"]			#删除键age

d.clear()				#删除字典的值

del d					#删除字典

函数(方法)

def day():
    print("1")
    print("1")
    print("1")
    print("1")
    print("1")

def isDouble(i):
    if i % 2 == 0:
        print("是偶数")
    else:
        print("是奇数")

isDouble(6)

函数的不定长参数、默认参数

def a(n,*args):		#函数不知道有多少个接收值可以使用 *args来接收
    for i in args:
        print(i)

a(1,3,4,5,2)
-------------------------------------------------------------------------
def a(n,age=18,*args):
    if  age >= 18:
        print(age)
    else:
        for i in args:
            print(i)

a(1,20,4,5,2)
-------------------------------------------------------------------------
def a(n, age=18, *args, **kwargs):    #顺序:普通参数,默认参数,包裹位置参数,包裹关键字参数
    if age >= 18:
        print(kwargs["c"])
        print(kwargs["g"])
    else:
        for i in args:
            print(i)

a(1, 20, 4, 5, 2, c=1, g=21)

拆包

d = {"name":"pig","age":"22"}
z,x = (2,4)
a,b=d
print(a,b,z,x)

python面向对象

class cat:
    def __init__(self,cat_name,cat_age,cat_color):
        self.name = cat_name
        self.age = cat_age
        self.color = cat_color
    def mow(self):			#方法
        print("喵" * cat1.age)

cat1 = cat("jojo",1,"blue")
print(f"小猫的名字叫{cat1.name},{cat1.age}岁了,是{cat1.color}颜色的")

cat1.mow()   #调用方法
class student:
    def __init__(self,name,stu_id):
        self.name = name
        self.id = stu_id
        self.scores = {"语文":0,"数学":0,"英语":0}

    def set_scores(self,course,scores):		#设置分数方法
        if course in self.scores:
            self.scores[course] = scores

    def print_scores(self,):    #打印学号姓名成绩方法
        print(f"{self.id}号同学{self.name}的成绩为:")
        for course in self.scores:
            print(f"{course}:{self.scores[course]}分")

chen = student("小陈",1)
wang = student("小王",2)

wang.set_scores("语文",99)
print(wang.scores)
wang.print_scores()			#调用打印分数方法

python的继承

class Employee:
    def __init__(self,name,id):
        self.name = name
        self.id = id

    def print_nm(self):
        print(f"我叫{self.name},我的工号为{self.id}")

class FullTimeEmployee(Employee):			 #继承Employee父类
    def __init__(self,name,id,monthly_salary):
        super().__init__(name,id)			#使用super() 调用父类的构造函数
        self.monthly_salary = monthly_salary

    def calculate_monthly_pay(self):
        return self.monthly_salary

class PartTimeEmployee(Employee):
    def __init__(self,name,id,daily_salary,work_days):
        super().__init__(name, id)
        self.daily_salary = daily_salary
        self.work_days = work_days

    def calculate_daily_pay(self):
        return self.daily_salary * self.work_days

zhangsan = FullTimeEmployee("张三",1,3000)
Lisi = PartTimeEmployee("李四",2,100,20)

zhangsan.print_nm()
print(zhangsan.calculate_monthly_pay())

Lisi.print_nm()
print(Lisi.calculate_daily_pay())

文件读写方法

读文件:

with open("D:/双体的东西/学习笔记/Docker/docker mysql.txt", "r", encoding ="utf-8") as f:    #使用with open() as f可避免忘记f.close()
    print(f.readline())    #读取一行数据
    print(f.readlines())	#读取 并返回一个列表 包含换行符 一般配合循环使用

写文件:

with open("./poem.text","w",encoding="utf-8") as f:				#w 只写模式 会清空之前写的
    for i in range(3):
        f.write("123456\n")

with open("./poem.text","a",encoding="utf-8") as f:				#a 只插入模式 不会清空
    for i in range(3):
        f.write("7890\n")

with open("./poem.text","r+",encoding="utf-8") as f:			#r+ 可读可插入可写
    for i in range(5):
        f.write("54321\n")
        print(f.read())

异常捕获

try:
    zhangsan = FullTimeEmployee("张三",1,input("请输入张三的月工资:"))

    Lisi = PartTimeEmployee("李四",2,int(input("请输入李四的日工资:")),int(input("请输入李四的工作天数工资:")))

    zhangsan.print_nm()
    print(zhangsan.calculate_monthly_pay())

    Lisi.print_nm()
    print(Lisi.calculate_daily_pay())
except ValueError:		#产生错误值时运行
    print("输入错误")
except ZeroDivisionError:	#产生除零错误值时运行
    print("出现了除零错误")
except:
    print("发生未知错误")		#产生其它所有错误值时运行
finally:
    print("程序结束")		#错误与否都会运行

unittest测试

import unittest
from 面向对象 import  PartTimeEmployee		 #from 被测试文件名 import 被测试的类名

class TestFace(unittest.TestCase):			#创建一个测试类

    def setup(self):					#setup方法用作与需重复应用值时 
        self.PartTimeEmployee()     

    def test_calculate_daily_pay(self):		#创建测试方法 必须以 test_ 作为开头才能被当作测试用例
        daily_pay = PartTimeEmployee("张三",1,100,20)			
        self.assertEqual(daily_pay.calculate_daily_pay(),2000)	

在终端使用 python -m unittest 进行测试

高阶函数

def calculate_and_print(num,calculate):		#需设置传入形参
    result = calculate(num)					
    print(f"""
    传入的参数为:{num}
    平方结果为:{result}"""
    )

def calculate_plus(num):
    return num + 10

calculate_and_print(3,calculate_plus)		#传入函数不能加括号

匿名函数

calculate_and_print(3,lambda num:num+20)

calculate_and_print(3,lambda num1,num2:num1+num2+20)

pyecharts(图标生成)

from pyecharts.charts import Line    	#导入pyecharts包  终端pip install pyecharts
from pyecharts.options import TitleOpts

line = Line()										#创建一个折线图对象
line.add_xaxis(["China","American","England"])		#添加x轴的数据
line.add_yaxis("GDP",[30 ,20 ,10])					#添加y轴的数据
line.set_global_opts(								#全局配置
    title_opts=TitleOpts(title="GDP Show",pos_left="center",pos_bottom="3%") #设置标题
)
line.render()										#通过render方法,将代码转换为图像

详细可查询官网: https://pyecharts.org/