python学习笔记

python学习笔记

1。如何进行注释

#这是行注释

#也可以多加几个#进行块注释

print("Hello Word !")

#
''' 三个单引号
这是块注释
'''

#
""" 三个双引号
这也是块注释
"""

2.输出

#输入和输出

#输入
#name=input()
#print(name)

a="世界"
b="你好 \n"
c=a+b
print(c)

#反斜杠将下面打印为了一行
d="~\n世界"
e="你好"
f="啊"
print(
      d+\
      e+\
      f
)
#
'''
print('let\'s go')
反斜杠转义字符

print("""
ni
hao
!""")
三引号将其自动换行
'''

# 实例 6      
a = True
print(a and 0 or 66)
#会输出66

3.python的关键字

False      class      finally    is         return

None       continue   for        lambda     try

True       def        from       nonlocal   while

and        del        global     not        with 

as         elif       if         or         yield

assert     else       import     pass

break      except     in         raise

4.条件语句(1)

#if语句
score=int(input("请输入你的成绩:"))

if score>=60:
    print("恭喜你没有挂科,去玩吧~")
else:
    print("很抱歉,你还需要补考,加油!")
#elif
score=int(input("请输入你的成绩:"))

if score<60:
    print("很遗憾,你需要补考。")
elif 60<=score<70:
    print("恭喜你,你的成绩及格啦!")
elif 70<=score<80:
    print("恭喜你,你的成绩为良好,")
elif 80<=score<90:
    print("恭喜你,你的成绩很好!")
elif 90<=score<=100:
    print("恭喜你,你的成绩为优秀。")
else :
    print("你输入的成绩无效!")
#not and or 对应c语言! && ||

4.条件语句(2)

a=int(6)

while (a>1):
    print(a)
    a=a-1
else:#会在while循环结束后执行else
    print("gameover")
print("**********\n")

for name in "hello word":
    print("遍历输出:%s " %name)

names=['h','e','l','l','o']
for n in names:
    pass
    print("遍历输出:%c" %n)
    
for i in range(1,10,2):#rangw(1开始 9结束 每步跨2)
    print(i)#打印出 1 3 5 7 9

#这里pass是一个占位符 当你编写一个函数时没有实现功能就可以使用pass避免错误
#如果是嵌套循环 break跳出最深层的循环
#continue跳出本次循环

4.条件语句(3)

print("这是一个求平均值的小程序。")
user_input=input("请输入数字(完成数组输入后,输入q结束程序)")

cout=0;
total=0;
while user_input != "q":
    num=float(user_input)
    cout=cout+1
    total=total+num
    user_input=input("请输入数字(完成数组输入后,输入q结束程序)")

if cout == 0:
    result=0
else:
    result=total/cout

print("所求平均数为 :"+str(result))

###############         

5.导入库

#用以下格式导入库函数
import math
#使用时 math.sqrt()

from math import sqrt
#使用时sqrt()

from math import*
#全部引用过来 但引入库过多时 容易造成命名的混乱
#使用时 sqrt()

a=math.sqrt(4)
print(a)
#
'''
a=2**3   2的三次方
print(a)
'''

6.类型


#len求长度 下面打印出3
a="你好啊"
print(len(a))

#通过索引取值 2为数组下标
print(a[2])

#布尔类型
A=True
B=False

#空类型
n=None

#type函数 返回变量的类型
print(type(a))
print(type(A))
print(type(n))

7.输入

#input 一律返回字符串

age=input("请输入你的年龄")
print(age)

#可以强制类型转化
str(5)
int("9")
float(3)

#print内的类型要保持一致 不一致要强制类型转换

8.列表

#列表
shopping_list = [] #定义一个新的列表
shopping_list.append("键盘") #往列表里添加内容
shopping_list.append("键帽")
shopping_list.append("音箱")
shopping_list.append("电竞椅")

shopping_list.remove("键帽")#移除列表所存在内容

shopping_list[1]="硬盘" #替换

print(shopping_list)
print(len(shopping_list))
print(shopping_list[0]) #查看列表第一个内容
     
price=[799,1024,200,800]
max_price=max(price) #最大值
min_price=min(price) #最小值
shorted_price=sorted(price) #排序 从大到小
print(max_price)
print(min_price)
print(shorted_price)

9.字典

#字典 dictionary
contact={ "小明" : "137878",
          "张三" : "2134435"}
contact["李四"]="345665346" #添加元素 也可以进行更新
del contact["小明"] #删除
len(contact) #多少对
#元组 tuple ()
#元组不可变 不能添加删除元素 这是与列表的区别
#而列表是可变的对列表可以执行添加 删除
#字典的键也不可变 
s="hello"
print(s.upper()) #转大写
print(s)
#字符串也是不可变的 转大写并没有改变s内容

###########
mean={"小" : "small"}
mean["大"] = "big"
mean["蓝"] = "blue"
mean["白"] = "white"
mean["黑"] = "black"

query=input("请输入要查询的词语 : \n")
if query in mean: #输入的内容在字典里面会返回True
    print("您查询的"+query+"意思是:")
    print(mean[query])
else:
    print("您查询的值不在本字典中")
    print("当前词典收录数为"+str(len(mean)))

#字典名.keys()  返回所有键 
#字典名.values()  返回所有值
#字典名.items()  返回所有键值对

10.format方法

#format() 方法

year="龙"
time="周二"
messsge="""
{0}年大吉
恭喜发财
红包拿来
今天是{1}
""".format(year,time)
#year会替换{0} time会替换{1}的内容
#也可以用下面这种方法
messsge="""
{current_year}年大吉
恭喜发财
红包拿来
今天是{current_time}
""".format(current_year=year,current_time=time)
#更简洁的
messsge="""
{year}年大吉
恭喜发财
红包拿来
今天是{time}
""".format(year=year,time=time)

##另一种方法字符串前加f
m=f"""
{year}年大吉
恭喜发财
红包拿来
今天是{time}"""
#加了f 里面的内容会被直接求值

score={"小明" : 66.2,
       "大明" : 78.3,
       "张三" : 67.4}
for name,total in score.items():#用items方法返回的是键值对
    print("{0}您好,您的成绩为{1:.3f}".format(name,total))
    #:.3f 表示保留三位小数
    
    

11.函数

#函数
def calculate_BMI(weight,hight):
    BMI=weight/hight ** 2
    if BMI<=18.5:
        category="偏瘦"
    elif BMI<=25:
        category="正常"
    elif BMI<=30:
        category="偏胖"
    else:
        category="肥胖"
    print(f"您的BMI结果为{category}")
    return BMI

calculate_BMI(95,1.8)

12.面向对象编程OOP

c’语言就是面向过程的,c++添加了class来进行面向对象编程。

面向过程可以理解为把要实现的内容拆分成一个一个的步骤,依次完成

比如我们要往ATM里面存50,取100,我们就可以写存钱和取钱两个函数来实现。但传的参数多了不利于理解。

面向对象编程并不会拘泥于具体步骤,而是会比较现实的模拟,

比如你要去ATM存钱和取钱,我们就可以提取ATM的性质,来定义一个ATM的类,然后用类来创建对象

类是创建对象的模板,对象是类的实例。

可以把类想象成建筑图纸,而对象就是根据这个图纸来建造的建筑

这样我们就可以定义ATM和钱两个类,存多少钱,ATM编号,钱的编号就能清晰的表示出来

方法就是放在类里面的函数

面向对象有三个被反复提及的特性 封装 继承 和多态

封装指写类的人将内部实现细节隐藏起来,使用类的人只通过外部接口访问和使用

比如有人写了洗衣机这个类 你只需要知道如何使用洗衣机 而不用知道洗衣机内部如何运转

继承是指面向对象编程允许创建有层次的类。比如要创建小学生和大学生两个类 我们就可以先创建一个学生的父类,让小学生和大学生去继承学生这个父类,这样父类的属性和方法都可以继承,不需要重复定义。

多态是指同样的接口因为对象具体类的不同而有不同的表现,

比如小学生和大学生都需要写作业,但写作业的内容肯定不同,所以我们要把写作业这个方法定义在子类里面,这样大学生和小学生里面可以定义两个不同的方法。这样调用写作业方法时就会因为所属类的不同而调用不同的类。执行不同的写作业方法。

#类定义属性
#下面这个在创造实例时就会已经返回了定义好的值
class Cutecat:
    def __init__(self):
        self.name="Lambton"
cat1 = Cutecat()
print(cat1.name)

#下面这个在创造实例时会根据传进去的值而相应的改变
class Cutecat:
    def __init__(self,CatName,Cat_age,Cat_color):
        self.name=CatName
        self.age=Cat_age
        self.color=Cat_color
cat1 = Cutecat("我叫小白",23,"白色")
print(cat1.color)
#定义方法
class Cutecat:
    def __init__(self,CatName,Cat_age,Cat_color):
        self.name=CatName
        self.age=Cat_age
        self.color=Cat_color
    def speak(self):#第一个参数被占用表示对象自身  这是定义方法
        print("喵" * self.age)#字符串乘以数字表示把字符串重复那么多次
    def think(self,content):
        print(f"小猫{self.name}在思考{content}..")

cat1 = Cutecat("小白",23,"白色")
cat1.think("我要吃鱼")
cat1.speak()
print(cat1.color)
#实战
class Student:
    def __init__(self,name,student_id):
        self.student_id=student_id
        self.name=name
        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(f"学生{self.name} (学号:{self.student_id})的成绩为:")
        for course in self.grades:
            print(f"{course}:{self.grades[course]}分")

chen=Student("小陈","100618")
zeng=Student("小曾","100622")
chen.set_grade("语文",98)
chen.set_grade("数学",100)
chen.set_grade("英语",120)
chen.print_grades()
print("chen.name")
zeng.set_grade("数学",95)
print(zeng.grades)

继承

#类继承练习:人力系统
#-员工分为两类:全职员工 FullTimeEmployee,兼职员工 PartTimeEmployee
#-全职和兼职都有“姓名 name”,“工号 id ”属性
#-都具备"打印信息 print_info"(打印姓名工号方法)。
#-全职有”月薪 monthly_salary“属性
#-兼职有”日薪 daily_salary”属性,“每月工作天数 work_days”的属性
#-全职和兼职都有“计算月薪 calculate_monthly_pay”的方法,但具体计算过程不一样

class Employee:
    def __init__(self, name, id):
        self.name=name
        self.id=id
    def print_info(self):
        print(f"员工名字;{self.name},工号:{self.id}")

class FullTimeEmployee(Employee):#继承父类
    def __init__(self,name,id,monthly_salary):
        super().__init__(name,id)#用父类的初始化 个人理解将name id 传过去
        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_monthly_pay(self):
        return self.daily_salary*self.work_days

zhangsan = FullTimeEmployee("张三","1001",6000)
lisi=PartTimeEmployee("李四","1002",230,15)
zhangsan.print_info()#这是调用的父类里面的方法
lisi.print_info()

print(zhangsan.calculate_monthly_pay())#这是调用的子类里面的方法
print(lisi.calculate_monthly_pay())

读文件

#绝对路径:c:\home\data\a.py

#相对路径从一个是参考位置出发:.当前目录 ..当前目录的上一级目录          

f=open("./data.txt","r",encoding="utf-8")#.当前目录 r可读 encooding 编码格式
content=f.read()#f.read 会讲文件所有内容以字符串返回
print(content)
f.close()#关闭文件 释放资源

with open("./data.txt","r",encoding="utf-8") as f:#这样写会自动关闭文件
    content=f.read()
    print(content)

with open("./data.txt","r",encoding="utf-8") as f:
    print(f.readline())#打印出第一行
    print(f.readline())#打印出第二行

with open("./data.txt","r",encoding="utf-8") as f:
    print(f.readlines())#会返回一个列表 全部内容 结合for循环使用

with open("./data.txt","r",encoding="utf-8") as f:
    lines=f.readlines()
    for line in lines:
        print(line)

写文件

#w如果文件已经存在 就会把原有的文件内容清空 不想清空可以用a附加模式 也可以用r+进行读写操作会以追加的模式进行写入
with open("./poem.txt","w",encoding="utf-8") as f:
    f.write("我欲乘风归去,\n又恐琼楼玉宇,\n高处不胜寒。\n")

with open("./poem.txt","a",encoding="utf-8") as f:
    f.write("起舞弄清影,\n")
    f.write("何似在人间。")

捕捉异常

#捕捉异常
#可以提前预判由于用户输入不规范而产生的错误 避免程序报错(不执行)
try:#有可能产生错误的代码
    user_weight=float(input("请输入您的体重(单位u:kg):"))
    user_height=float(input("请输入您的身高(单位u:m):"))
    user_BMI=user_weight/user_height ** 2
except ValueError: #产生值错误时会运行
    print("输入的不是合理数字,请重新运行程序,并输入正确的数字。")
except ZeroDivisionError: # 产生除零错误时会执行
    print("身高不能为0,请重新运行程序,并输入正确的数字")
except : #产生其他错误时执行
    print("发生了未知错误,请重新运行程序。")
else:#没有错误时执行
    print("您的BMI值为:"+str(user_BMI))
finally: #不管反发生错误与否都会执行
    print("程序运行结束。")
    

assert断言和unittest(不想写了 自行百度)

爬虫

1.不要爬取公民数据

2.不要爬取受著作权保护的内容

3.不要爬取国家事务,国防建设尖端科学技术领域的计算机系统等

你还要确保自己写的爬虫是一只温柔善良的爬虫

1.它的请求数量和频率不能过高 否则可能无异于DDos攻击

2.有反爬机制或验证码登录 不要去强行突破

3.可以通过查看网站的robots.txt文件了解可爬取的网页路径范围

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

打开pycharm编辑器在终端输入pip install requests 下载这个外部库

import requests
"""
URL="https://www.bilibili.com/"
resopnse=requests.get(URL)#会返回一个Response实例
print(resopnse)
print(resopnse.status_code)#这个实例包括这个状态码

if resopnse.ok:#也可以根据状态码来判断 不过这个更简洁
    print("请求成功")
else :
    print("请求失败")
"""
#上面的无法访问 可以伪装成用户去访问
url1="https://movie.douban.com/top250"
headers = {
    #在浏览器检查代码里面找到User-Agent 将其内容复制下来
    "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 Edg/122.0.0.0"
}#用请求头进行伪装
response1=requests.get(url1,headers=headers)
print(response1.text)#拿到了那个页面的HTML源码

html练习

<!DOCTYPE html>
<html>
    <head>
       <title>这是一个网页标题</title>
    </head>
    <body>
        <div style="background-color: red;">
        <h1>我是一级标题</h1>
        <h2>我是二级标题</h2>
        <h6>我是最小号六级标题</h6>
        </div>
        <p>这是一个文本段落这是一个文本段落
            这是一个<br>换行文本段落
            <b>加粗字体</b>
            <i>斜体</i>
            <u>这样可以加下划线</u>
        </p>
        <p>这样<span style="background-color: red;">这是一块红色</span>也可以换行 下面加载图片</p>
        <img src="https://tse2-mm.cn.bing.net/th/id/OIP-C.7KW5GT7NQ8yUGlBbCHEm0gHaNK?rs=1&pid=ImgDetMain" width="500 px">
        <a href="https://www.baidu.com">百度</a>

        <ol>
            <li>我是第一项</li>
            <li>我是第二项</li>
            <li>我是第三项</li>
        </ol>
        <ul>
            <li>我是无序的1</li>
            <li>我是无序的2</li>
            <li>我是无序的3</li>
        </ul>

        <table border="1" calss="data-table">
            <thead>
                <tr>
                    <td>头部1</td>
                    <td>头部2</td>
                    <td>头部3</td>
                </tr>
            </thead>

            <tbody>
                <tr>
                    <td>111</td>
                    <td>222</td>
                    <td>333</td>
                </tr>
                <tr>
                    <td>444</td>
                    <td>555</td>
                    <td>666</td>
                </tr>
                <tr>
                    <td>777</td>
                    <td>888</td>
                </tr>
            </tbody>
        </table>
    </body>
</html>

bs库

#这是外部库 解析HTML
#安装命令 pip install bs4
from bs4 import BeautifulSoup
import requests
content=requests.get("http://books.toscrape.com/").text
soup=BeautifulSoup(content,"html.parser") #后面这个是指定解析器
#这个库函数有很多实用的方法 比如可以根据html中的某一个值获得对应的属性(键值对)
#print(soup.p)#就能看到这个HTML中里的第一个<p>元素 即文本段落元素
#print(soup.img)#第一个img元素
all_prices=soup.findAll("p",attrs={"class":"price_color"})
#源网页代码 <p calss ="price_color">$53.74</p>
#第一个参数p表示找p标签 可选参数arrars赋值为一个字典 键值对就对应你想找的属性和值
#findAll返回一个可迭代对象 可通过for循环打印
#如果我们只想要中间的价格 可以用方法string 会把标签包围的文字返回给我们
for price in all_prices:
    print(price.string[2:])#切片操作 能获得索引值大于等于2所有剩下的字符串
all_titles=soup.findAll("h3")
for title in all_titles:
    link = title.find("a")#find 返回的不是可迭代对象
    print(link.string)

爬取豆瓣电影

import requests
from bs4 import BeautifulSoup

#豆瓣电影top250
#url1="https://movie.douban.com/top250"
headers = {
    "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 Edg/122.0.0.0"
}

for start_num in range(0,250,25):
    response1=requests.get(f"https://movie.douban.com/top250?start={start_num}",headers=headers)
    html=response1.text
    soup=BeautifulSoup(html,"html.parser")#传入bs函数搜寻
    #分析想提取信息特点 在网页检查
    #看到所有标题都是sapan元素并且它们的class值都是title
    #我们就可以根据这个条件提取

    all_titles=soup.findAll("span",attrs={"class":"title"})#返回一个可迭代对象
    for title in all_titles:
        title_string=title.string
        if "/" not in title_string:
            print(title_string)

BeautifulSoup

#豆瓣电影top250
#url1=“https://movie.douban.com/top250”
headers = {
“User-Agent”:“Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 Edg/122.0.0.0”
}

for start_num in range(0,250,25):
response1=requests.get(f"https://movie.douban.com/top250?start={start_num}",headers=headers)
html=response1.text
soup=BeautifulSoup(html,“html.parser”)#传入bs函数搜寻
#分析想提取信息特点 在网页检查
#看到所有标题都是sapan元素并且它们的class值都是title
#我们就可以根据这个条件提取

all_titles=soup.findAll("span",attrs={"class":"title"})#返回一个可迭代对象
for title in all_titles:
    title_string=title.string
    if "/" not in title_string:
        print(title_string)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值