
1. 引言Python 作为一门简洁优雅、功能强大的高级编程语言其核心语法是每一位开发者必须掌握的基础。本文将从分类讲解的角度系统梳理 Python 的核心语法要素帮助初学者建立清晰的知识框架也为有经验的开发者提供复习和查漏补缺的参考。我们将 Python 核心语法分为以下几个主要类别进行讲解基础语法与数据类型流程控制结构函数与模块面向对象编程异常处理文件操作常用内置函数与标准库2. 基础语法与数据类型2.1 变量与赋值Python 是动态类型语言变量无需声明类型直接赋值即可。# 变量赋值namePythonversion3.12is_awesomeTrue# 多重赋值a,b,c1,2,3xyz0# 交换变量值a,bb,a2.2 基本数据类型Python 内置了丰富的数据类型主要包括数值类型整数 (int):42,-10,0浮点数 (float):3.14,2.0,-0.5复数 (complex):12j序列类型字符串 (str):hello,world列表 (list):[1, 2, 3],[a, b, c]元组 (tuple):(1, 2, 3),(x, y)映射类型字典 (dict):{name: Alice, age: 25}集合类型集合 (set):{1, 2, 3}不可变集合 (frozenset):frozenset([1, 2, 3])布尔类型布尔值 (bool):True,False空类型空值 (NoneType):None2.3 类型转换# 显式类型转换int(42)# 42float(3.14)# 3.14str(100)# 100list(abc)# [a, b, c]tuple([1,2,3])# (1, 2, 3)2.4 运算符算术运算符:,-,*,/,//,%,**比较运算符:,!,,,,逻辑运算符:and,or,not成员运算符:in,not in身份运算符:is,is not3. 流程控制结构3.1 条件语句# if-elif-else 结构score85ifscore90:gradeAelifscore80:gradeBelifscore70:gradeCelse:gradeDprint(f成绩等级:{grade})3.2 循环语句for 循环# 遍历序列fruits[apple,banana,cherry]forfruitinfruits:print(fruit)# 使用 range()foriinrange(5):# 0, 1, 2, 3, 4print(i)foriinrange(1,6):# 1, 2, 3, 4, 5print(i)foriinrange(1,10,2):# 1, 3, 5, 7, 9print(i)while 循环# 基本 while 循环count0whilecount5:print(count)count1# 带 break 和 continuewhileTrue:user_inputinput(输入 quit 退出: )ifuser_inputquit:breakifnotuser_input:continueprint(f你输入了:{user_input})3.3 循环控制语句break: 完全终止循环continue: 跳过当前迭代继续下一次else子句: 循环正常结束时执行非 break 退出# for-else 示例foriinrange(5):ifi10:# 这个条件永远不会成立breakelse:print(循环正常结束没有遇到 break)4. 函数与模块4.1 函数定义与调用# 基本函数定义defgreet(name):向指定的人问好returnfHello,{name}!# 调用函数messagegreet(Alice)print(message)# Hello, Alice!# 带默认参数的函数defpower(base,exponent2):计算幂默认指数为2returnbase**exponentprint(power(3))# 9print(power(3,3))# 27# 关键字参数调用defdescribe_person(name,age,city):returnf{name}is{age}years old, living in{city}.# 使用关键字参数顺序无关describe_person(age25,cityBeijing,nameBob)4.2 参数类型位置参数:def func(a, b, c)默认参数:def func(a, b10)可变位置参数:def func(*args)可变关键字参数:def func(**kwargs)# 可变参数示例defprint_info(*args,**kwargs):print(位置参数:,args)print(关键字参数:,kwargs)print_info(1,2,3,nameAlice,age25)# 输出:# 位置参数: (1, 2, 3)# 关键字参数: {name: Alice, age: 25}4.3 返回值# 返回多个值实际上是返回元组defget_min_max(numbers):returnmin(numbers),max(numbers)min_val,max_valget_min_max([3,1,4,1,5,9])print(f最小值:{min_val}, 最大值:{max_val})4.4 模块导入# 导入整个模块importmathprint(math.sqrt(16))# 4.0# 导入特定函数/类fromdatetimeimportdatetime nowdatetime.now()# 给模块或函数起别名importnumpyasnpfrommatplotlibimportpyplotasplt# 导入模块中的所有内容不推荐frommathimport*4.5 自定义模块# mymodule.py 文件内容 这是一个自定义模块示例 defadd(a,b):返回两个数的和returnabdefmultiply(a,b):返回两个数的积returna*b# 主程序中使用if__name____main__:# 模块测试代码print(add(2,3))# 55. 面向对象编程5.1 类与对象# 定义类classDog:# 类属性speciesCanis familiaris# 初始化方法def__init__(self,name,age):# 实例属性self.namename self.ageage# 实例方法defbark(self):returnf{self.name}says: Woof!defget_info(self):returnf{self.name}is{self.age}years old.# 创建对象my_dogDog(Buddy,3)print(my_dog.bark())# Buddy says: Woof!print(my_dog.get_info())# Buddy is 3 years old.print(my_dog.species)# Canis familiaris5.2 继承# 父类classAnimal:def__init__(self,name):self.namenamedefspeak(self):raiseNotImplementedError(子类必须实现此方法)# 子类classCat(Animal):defspeak(self):returnf{self.name}says: Meow!classDog(Animal):defspeak(self):returnf{self.name}says: Woof!# 使用animals[Cat(Kitty),Dog(Buddy)]foranimalinanimals:print(animal.speak())5.3 封装与属性classBankAccount:def__init__(self,owner,balance0):self.ownerowner self.__balancebalance# 私有属性defdeposit(self,amount):ifamount0:self.__balanceamountreturnTruereturnFalsedefwithdraw(self,amount):if0amountself.__balance:self.__balance-amountreturnTruereturnFalse# 属性装饰器propertydefbalance(self):returnself.__balance# 使用accountBankAccount(Alice,1000)account.deposit(500)print(account.balance)# 15006. 异常处理6.1 基本异常处理try:# 可能引发异常的代码result10/0print(这行不会执行)exceptZeroDivisionError:# 处理特定异常print(不能除以零)except(ValueError,TypeError)ase:# 处理多种异常print(f值或类型错误:{e})exceptExceptionase:# 处理所有其他异常print(f发生未知错误:{e})else:# 没有异常时执行print(计算成功)finally:# 无论是否异常都会执行print(清理资源)6.2 自定义异常classInsufficientFundsError(Exception):余额不足异常def__init__(self,balance,amount):self.balancebalance self.amountamountsuper().__init__(f余额不足: 当前余额{balance}, 需要{amount})defwithdraw_money(balance,amount):ifamountbalance:raiseInsufficientFundsError(balance,amount)returnbalance-amount# 使用try:withdraw_money(100,200)exceptInsufficientFundsErrorase:print(e)# 余额不足: 当前余额100, 需要2007. 文件操作7.1 文件读写# 写入文件withopen(example.txt,w,encodingutf-8)asf:f.write(Hello, World!\n)f.write(这是第二行\n)# 读取整个文件withopen(example.txt,r,encodingutf-8)asf:contentf.read()print(content)# 逐行读取withopen(example.txt,r,encodingutf-8)asf:forlineinf:print(line.strip())# 去除换行符# 读取所有行到列表withopen(example.txt,r,encodingutf-8)asf:linesf.readlines()print(lines)7.2 文件模式r: 只读默认w: 写入覆盖a: 追加x: 创建新文件写入b: 二进制模式t: 文本模式默认: 读写模式8. 常用内置函数与标准库8.1 常用内置函数# 输入输出nameinput(请输入你的名字: )print(f你好,{name}!)# 类型相关type(42)# class intisinstance(42,int)# Truelen([1,2,3])# 3# 数学运算abs(-10)# 10round(3.14159,2)# 3.14max(1,5,3)# 5min(1,5,3)# 1sum([1,2,3])# 6# 迭代相关range(5)# range(0, 5)enumerate([a,b,c])# 枚举器zip([1,2],[a,b])# 配对# 转换函数int(42)# 42str(100)# 100list(abc)# [a, b, c]tuple([1,2])# (1, 2)dict([(a,1),(b,2)])# {a: 1, b: 2}8.2 常用标准库模块# os - 操作系统接口importos os.getcwd()# 当前工作目录os.listdir(.)# 列出目录内容# sys - 系统相关参数和函数importsys sys.version# Python版本sys.argv# 命令行参数# datetime - 日期时间处理fromdatetimeimportdatetime,date,timedelta nowdatetime.now()todaydate.today()tomorrowtodaytimedelta(days1)# json - JSON处理importjson data{name:Alice,age:25}json_strjson.dumps(data)# 序列化parsedjson.loads(json_str)# 反序列化# re - 正则表达式importre patternr\d# 匹配数字matchesre.findall(pattern,abc123def456)# [123, 456]9. 总结Python 核心语法虽然简洁但功能强大。掌握这些基础语法分类后你可以编写清晰的代码利用 Python 的简洁语法表达复杂逻辑构建模块化程序通过函数和类组织代码结构处理各种数据灵活运用内置数据类型和标准库编写健壮的程序使用异常处理增强程序稳定性进行文件操作读写各种格式的数据文件建议的学习路径先掌握基础语法和数据类型熟练使用流程控制结构理解函数和模块的用法深入学习面向对象编程实践异常处理和文件操作探索常用内置函数和标准库通过不断练习和实践你将能够熟练运用 Python 解决实际问题为进一步学习数据分析、Web 开发、人工智能等方向打下坚实基础。