Python快速入门教程
文章目录:
一:软件环境安装
1.软件环境
2.运行第一个程序
二:语法基础
1.注释
2.变量
3.数学运算
4.数据类型
5.数据输入input
6.逻辑运算
7.程序控制结构
7.1 if选择
7.1.1 条件语句if else
7.1.2 嵌套语句
7.1.3 多条件判断if elif else
7.2 for循环
7.3 while循环
8.列表(数组)
9.字典
10.格式化字符串format
11.函数
12.引入模块
三:语法进阶
1.OOP面向对象
1.1 创建类
1.2 继承类
2.文件
2.1 读文件r
2.2 写文件w
3.异常
3.1 常见错误
3.2 异常处理
4.测试库unittest
参考:3小时快速入门Python
一:软件环境安装
1.软件环境
第一步:环境Downloads_Windows installer (64-bit)(安装好后命令行输入Python查看是否安装成功)
第二步:软件PyCharm
第三步:长久使用、汉化(插件里面安装Chinese然后重启软件就是)
python解释器:把代码转换成字节码后再执行代码编辑器:pycharm
2.运行第一个程序
创建工程a 位置:选择自己需要保存工程的位置b 基础解析器:选择上面环境安装的解释器c 取消勾选“创建Main.py”目录结构venv:这个项目独立的python虚拟环境,不同的项目考研用不同的解释器版本和第三方库写代码选择最上面的文件夹——>右键——>新建——>python文件——>取名.py——>回车取消将文件添加到git举例print("hello world!")print('hello world!')print('hello world!'+"欢迎来到python"+'的编程世界')print("你在\"干\'什么")print ("\n")print ("123\n456")print("""离离原上草,一岁一枯荣野火烧不尽,春风吹又生""")print('''鹅鹅鹅,曲项向天歌白毛浮绿水,红掌拨清波''')print(100)
二:语法基础
1.注释
第一种:#快捷键:ctrl+/ 第二种:“”“这里面的内容是会被注释的”“”
2.变量
# 变量取名:文字、数字、下划线 a="吃饭了" print("刘鑫磊"+a) print("周星驰"+a) print("刘德华"+a)
3.数学运算
import math #math.函数名(...) print(math.sin(1))#一元二次方程:ax^2+bx+c=0 -x^2-2x+3=0 # -b±√(b^2-4ac) #x= ˉˉˉˉˉˉˉˉˉˉˉˉ # 2a a=-1 b=-2 c=3 print((-b+math.sqrt(b*b-4*a*c))/(2*a)) print((-b-math.sqrt(b*b-4*a*c))/(2*a))
4.数据类型
字符串:str "hello" 'world' 整数:int 100 浮点数:float 1.0 2.01 布尔类型:bool True False 空值类型:NoneType None返回数据类型:type(表达式) 得到字符串的长度:len("字符串信息")布尔类型(必须大写):True False 空值类型(必须大写):None
5.数据输入input
a=input("请输入:") print(a)b=input("请输入一个整数:") print(int(b))c=input("请输入一个浮点数:") print(float(c))d=input("请输入一个字符串:") print(str(d))
6.逻辑运算
and与 or 或 not非优先级:not——>and——>or
7.程序控制结构
7.1 if选择
7.1.1 条件语句if else
if [条件]:[执行语句] else:[执行语句]
7.1.2 嵌套语句
if [条件一]:if[条件二]:[语句A]else:[语句B] else:[语句C]
7.1.3 多条件判断if elif else
if [条件一]:[语句A] elif [条件二]:[语句B] elif [条件三]:[语句C] else:[语句D]
7.2 for循环
num=[100,10,1000,99,66,1,88] for a in num:if a==max(num):print(a)print("它是最大的数")for b in range(1,10,2):print(b)
7.3 while循环
a=input("请请输入你的成绩:") a=int(a) while a > 90:print("优秀")
8.列表(数组)
# 方法:对象.方法名(...) a.append("橘子") # 函数:函数名(对象) len(a)a=["苹果","梨子","香蕉"] b=[100,10,1000,99,66,1,88]a.append("橘子") print(a)a.remove("苹果") print(a)print(a[1])a[2]="芒果" print(a)print(max(b)) print(min(b)) print(sorted(b))
9.字典
#字典contacts 键key:值value a={"1":"刘鑫磊","2":"刘德华","3":"刘亦菲","4":"刘诗诗"}a["5"]="刘能"print("1" in a)del a["2"] print(a)print(len(a))print(a["3"])a.keys() a.values() a.items()# 元组tuple a=("苹果","梨子","香蕉")
10.格式化字符串format
name="刘鑫磊" fromhome="四川" a=""" 大家好,我叫{0} 来自{1}省 """.format(name,fromhome) print(a)shuiguo="西瓜" shucai="土豆" b=f""" 喜欢吃的水果是{shuiguo} 喜欢的蔬菜是{shucai} """ print(b)
11.函数
def sum(a,b):print(a+b)return a+ba=input("请1""输入a:") b=input("请输入b:")sum(a,b)
12.引入模块
Pyhon第三方库
安装库在终端里面输入:pip install 库名引用import statisticsprint(statistics.median([111,125,134,129])) #统计数组元素的中位数print(statistics.mean([111,125,134,129])) #对所有元素求均值from statistics import median,meanprint(median([111,125,134,129])) print(mean([111,125,134,129]))from statistics import*print(median([111,125,134,129])) print(mean([111,125,134,129]))
三:语法进阶
1.OOP面向对象
OOP面向对象封装、继承、多态类是创建对象的模板,对象是类的实例
1.1 创建类
class CuteCat:def __init__(self,cat_name,cat_age,cat_color): #构造属性self.name=cat_nameself.age=cat_ageself.color=cat_colordef speak(self): #构造方法print("喵"*self.age)def think(self,context):print(f"小猫{self.name}在考虑吃{context}")cat1=CuteCat("花花",3,"橘色") #创建对象 cat1.think("吃鱼") print(f"小猫名{cat1.name}的年龄是{cat1.age}它的颜色为{cat1.color}") #获取对象的属性 cat1.speak()
1.2 继承类
class employee: #父类(职工)def __init__(self,name,id):self.name=nameself.id=iddef print_info(self):print(f"员工的名字:{self.name},工号:{self.id}")class fullTimeEmployee(employee): #继承(全职员工)def __init__(self, name, id,monthly_salary):super().__init__(name, id)self.monthly_salary=monthly_salarydef monthly_pay(self):return self.monthly_salaryclass partTimeEmployee(employee): #继承(兼职员工)def __init__(self, name, id,daily_salary,work_days):super().__init__(name,id)self.daily_salary=daily_salaryself.work_days=work_daysdef monthly_pay(self):return self.daily_salary*self.work_days#创建对象 zhangsan=fullTimeEmployee("张三","001",6000) lisi=partTimeEmployee("李四","002",4000,15)#调用输出 zhangsan.print_info() lisi.print_info() print(zhangsan.monthly_pay()) print(lisi.monthly_pay())
2.文件
磁盘目录:cd cd~ cd- cd. cd.. cd/ cd./ cd../.. cd!$ cd /home的区别
a=open("./data.txt","r",encoding="utf-8") #相对路径 r:读(默认)# r+:读写(写入东西是追加的形式) b=open("/usr/demo/data.txt","w") #绝对路径 w:写# a:附加追加内容
2.1 读文件r
print(a.read(10)) #读取多少字节 print(b.readline()) #读取一行的内容 print(b.readlines()) #读取全部文件内容#关闭文件 a.close() #第一种方法 with open("./data.txt") as a: #第二种方法:执行完就会自动关闭print(a.read())
举例
#正常读取逻辑 c=open("./data.txt","r",encoding="utf-8") line=c.readline() #读取第一行 while line !="": #判断当前行是否为空print(line) #不为空则打印当前行line=c.readline() #继续读取下一行 c.close() #关闭文件,释放资源#正常读取逻辑 d=open("./data.txt","r",encoding="utf-8") lines=d.readlines() #把每行内容存储到列表里 for line in lines: #遍历每行内容print(line) #打印当前行 c.close()
2.2 写文件w
#若文件不存在,就会自动创建这个文件;若文件存在会把里面的东西清空覆盖 with open("./data.txt","w",encoding="utf-8") as a:a.write("hello world!\n")
3.异常
3.1 常见错误
IndentationError:缩进错误 ImportError:导入模块错误 ArithmeticError:计算错误 IndexError:索引错误 ZeroDivisionError:分母为零错误 SyntaxError:语法错误 AttributeError:属性错误 ValueError:值错误 KeyError:键错误 ZeroDivisionError:分母为零错误AssertionError:断言错误
3.2 异常处理
try:a=float(input("请输入1——100:"))b=float(input("请输入100——200:"))c=a/b except ValueError:print("你输入的数据不合理,无法转换成数字的字符串") except ZeroDivisionError:print("分母不能为零") except:print("程序发生错位,请检查后重新运行") else: #没有错误时运行print("除法的结果为:"+str(c)) finally: #都会执行的程序print("程序执行结束")
4.测试库unittest
#断言 assert 表达式 #单元测试库 import unittest#测试代码和写的功能分文件写来进行测试 import unittest from filename1 import sumclass TestMyclass(unittest.TestCase):def setUp(self):self.renyi=renyi("hello world") #都会执行的def test_x(self):assert sum(1,2)==3def test_y(self):self.assertEqual(sum(2,8),10) #assert a=b assertNotEqualdef test_z(self):self.assertTrue(a) #assert a is true assertFalsedef test_n(self):self.assertIn(a,b) #assert a in b assertNoIn#终端运行(视图——>工具窗口——>终端):python -m unittest#会返回运行了几个测试、每一个点代表一个测试通过(没有通过有一个点就会变成F)