Python基础速成
打印字符串
#字符串连接
print ("hello"+" world"+"!") #hello world!
#单双引号转移
print("He said'good!'") #He said'good!'
print('He said"good!"') #He said"good!"
print("He said\"Let\'s go!\"") #He said"Let's go!"
#换行
print("hello!\nhi!") '''hello!
hi'''
#三引号跨行字符串
print("""君不见,黄河之水天上来,奔流到海不复回。
君不见,高堂.....
......
.....""")
数学运算
2**3 #2的三次方
import math
result=math.log2(8)
print(result) #3
//:除完后向下取整
3/2=1.5 3//2=1
数据类型
#len函数
s="hello"
print(len(s)) #5
#bool类型
b1=True #第一个字母大写
b2=False
#空值类型
n=None
#type函数
print(type(s)) #<class 'str'>
print(type(b1)) #<class 'bool'>
print(type(n)) #<class 'NoneType'>
Input
#BMI = 体重 /(身高**2)
user_weight = float(input("请输入你的体重:")) #input默认字符串类型
user_height = float(input("请输入你的身高:"))
user_BMI=user_weight/(user_height**2)
print("您的BMI值为:"+ str(user_BMI))
条件语句
mood_index=int(input("对象的心情指数:"))
if mood_index >= 60:
print("恭喜你,可以去打游戏了!")
print("^_^")
else:
print("不能打!")
#多条件判断
user_weight = float(input("请输入你的体重:")) #input默认字符串类型
uesr_height = float(input("请输入你的身高:"))
user_BMI=user_weight/(user_height**2)
print("您的BMI值为:"+ str(user_BMI))
if user_BMI<=18.5:
print("偏瘦")
elif 18.5<user_BMI<=25:
print("正常")
elif 25<user_BMI<=30:
print("偏胖")
else:
print("肥胖")
#逻辑运算
not and or
列表
shopping_list = []
shopping_list.append("键盘") #添加
shopping_list.append("键帽")
shopping_list.remove("键帽") #删除
shopping_list.append("音响")
shopping_list.append("电竞椅")
shopping_list[1]="硬盘" #改变第二个元素值
#print(shopping_list)
#print(len(shopping_list)) #3
#print(shopping_list[0])
price=[799,1024,200,800]
max_price=max(price)
min_price=min(price)
sorted_price=sorted(price)
print(max_price)
print(min_price)
print(sorted_price)
字典
字典名.keys() #所有键
字典名.values() #所有值
字典名.items() #所有键值对
tvshow_dict={"张三":"奔跑吧兄弟","李四":"你好星期六"}
tvshow_dict["王五"]="极限挑战"
tvshow_dict["小红"]="全员加速中"
people=input("请输入您想要了解的人:")
if people in tvshow_dict:
print("您查询的"+people+"最喜欢的节目是:")
print(tvshow_dict[people])
else:
print("您查询的人暂未收录")
print("当前本词典收录人数:"+str(len(tvshow_dict)))
for循环
for 变量名 in 可迭代对象 :
...
temperature_dict={"111":36.4,"112":36.6,"113":36.2}
for staff_id,temperature in temperature_dict.items():
if temperature>=38:
print(staff_id)
range(起始值,结束值)
range(起始值,结束值,步长)
for i in range(5,10):
print(i) #5~9
for num in range(1,10,2):
print(num) #1~9的奇数
格式化字符串
#format
message_content="""
...
金{0}贺岁,欢乐祥瑞。
金{0}敲门,五福临门。
给{1}及家人拜年啦!
新春快乐,{0}年大吉!
""".format(year,name) #0表示第一个参数,1表示第二个参数
message_content="""
...
金{current_year}贺岁,欢乐祥瑞。
金{current_year}敲门,五福临门。
给{receiver_name}及家人拜年啦!
新春快乐,{current_year}年大吉!
""".format(current_year=year,receiver_name=name)
gpa_dict={"小明":3.251,"小花":3.869,"小梨":2.653,"小张":3.685}
for name,gpa in gpa_dict.items():
print("{0}你好,你的当前绩点为:{1}".format(name,gpa))
#f-字符串
name="老林"
year="龙"
message_content=f"""
...
金{year}贺岁,欢乐祥瑞。
金{year}敲门,五福临门。
给{name}及家人拜年啦!
新春快乐,{year}年大吉!
"""
gpa_dict={"小明":3.251,"小花":3.869,"小梨":2.653,"小张":3.685}
for name,gpa in gpa_dict.items():
print("{0}你好,你的当前绩点为:{1:.2f}".format(name,gpa)) #.2f:保留两位小数
print(f"{name}你好,你的当前绩点为:{gpa:.2f}")
自定义函数
def 函数名(参数1,参数2):
...
return 变量 #如果没有这句默认返回None
引入模块
#1
import 模块名
模块名.函数名/变量名
#2
from 模块名 import 函数名/变量名...
不需要 模块名.
#3
from 模块名 import*
所有都 不需要 模块名.
#第三方库安装引用
网站:pypi.org
终端输入pip install 库名
类
#创建类
class CuteCat:
def __init__(self,cat_name,cat_age,cat_color): #构造函数
self.name=cat_name
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('Jojo',2,"橙色")
print(f"小猫{cat1.name}的年龄是{cat1.age}岁,花色是{cat1.color}")
cat1.speak()
cat1.think("抓沙发还是撕纸箱")
#继承
class 父类名: #哺乳类
def __init__(self,name,sex):
self.name=name
self.sex=sex
def ...
class 子类名1(父类名):
def __init__(self,name,sex,has_tail):
super().__init__(name,sex) #super:返回当前类的父类
self.has_tail=False
def...
class 子类名2(父类名):
def __init__(self,name,sex,has_tail):
super().__init__(name,sex)
self.has_tail=True
def...
文件操作
#绝对路径:以根目录为基准
Linux、macOS等类Unix系统:/../../目标目录
Windows:分区名:\..\..目标目录
#相对路径
.表示参照文件当前所在目录
..更上一层的父目录
..斜杠或反斜杠..上一层父目录的父目录
.斜杠或反斜杠..下一层目录 ./data==data
./data/2.txt #./可以省略 data/2.txt
#打开文件
f=open("路径","r",encoding="utf-8") #"r"表示只读 w:只写
#1
print(f.read()) #会读文件的全部内容,并打印
print(f.read()) #会读空字符串,并打印
#2
print(f.read(10)) #会读第1-10个字节的文件内容
print(f.read(10)) #会读第11-20个字节的文件内容
#3
print(f.raedline()) #会读一行文件内容,并打印
line =f.readline() #读第一行
while line!=" ": #判断当前行是否为空
print(line) #不为空则打印当前行
line=f.readline() #读取下一行
#4
#readlines会读取全部文件内容,并把每行作为列表元素返回
print(f.readlines())
lines=f.readlines() #把每行内容存储在列表里
for line in lines: #遍历每行内容
print(line) #打印当前行
#关闭文件
#1
f=open("./data.txt")
print(f.read())
f.close()
#2
with open("./data.txt") as f:
print(f.read())
#"w"
'''如果文件不存在,则自动创建传入文件名的那个文件
如果文件存在,原本文件被清空'''
with open("./data.txt","w",encoding="utf-8") as f:
f.write("hello!\n")
f.write("Yoooo")
#"a"附加模式,不会清空原文件内容
#"r+"读写,执行写操作时也不会清空内容而是追加
with open("./data.txt","w",encoding="utf-8") as f:
print(f.read())
f.write("Yoooo")
异常处理
索引错误、除零错误、找不到文件错误…
#捕捉异常 except只会执行一条
try:#有可能产生错误的代码
user_weight = float(input("请输入你的体重:"))
user_height = float(input("请输入你的身高:"))
user_BMI=user_weight/(user_height**2)
except ValueError: #产生值错误时会运行
print("输入为不合理数字,请重新运行程序,并输入正确的数字")
except ZreoDivisionError: #产生除0错误时会运行
print("身高不能为0,请重新运行程序,并输入正确的数字")
except: #产生其他错误时运行
print("发生了未知错误,请重新运行程序")
else: #没有错误时运行
print("您的BMI值为:"+str(user_BMI))
finally:
print("程序结束运行") #不管发生错误与否都会运行
测试
【你觉得自己这辈子都学不会编程?超超超基础Python课程,3小时快速入门 【自学Python教程合集】【3小时快速入门Python】】 https://www.bilibili.com/video/BV1944y1x7SW/?p=35&share_source=copy_web&vd_source=02e5301949f3350a922ce19d8d7122a5
代码太长了,有点麻烦也不太清楚以后会不会用到(
##备注
本笔记基于b站视频【你觉得自己这辈子都学不会编程?超超超基础Python课程,3小时快速入门 【自学Python教程合集】【3小时快速入门Python】】 https://www.bilibili.com/video/BV1944y1x7SW/?share_source=copy_web&vd_source=02e5301949f3350a922ce19d8d7122a5
所写,因为本人学过c/c++有一点基础,所以只记录本人学习此视频存在疑惑或不熟之处,仅供本人复习所用