Python 语法
│
├── 基本结构
│ ├── 语句(Statements)
│ │ ├── 表达式语句(如赋值、算术运算)
│ │ ├── 控制流语句(if , for , while )
│ │ ├── 定义语句(def , class )
│ │ └── 导入语句(import , from . . . import )
│ ├── 代码块(由缩进定义)
│ └── 注释(单行
│
├── 数据类型
│ ├── 基本类型
│ │ ├── 数字(int , float , complex )
│ │ ├── 字符串(str )
│ │ ├── 布尔值(bool )
│ │ └── 空值(NoneType)
│ ├── 复合类型
│ │ ├── 列表(list )
│ │ ├── 元组(tuple )
│ │ ├── 字典(dict )
│ │ └── 集合(set )
│ └── 类型转换(如 int ( ) , str ( ) , list ( ) )
│
├── 运算符
│ ├── 算术运算符(+ , - , * , / , // , % , ** )
│ ├── 比较运算符(== , != , < , > , <= , >= )
│ ├── 逻辑运算符(and , or , not )
│ ├── 位运算符(& , | , ^ , ~ , << , >> )
│ └── 赋值运算符(= , += , -= , 等)
│
├── 控制流
│ ├── 条件语句(if - elif - else )
│ ├── 循环语句(for , while )
│ ├── 跳转语句(break , continue , pass )
│ └── 异常处理(try - except - finally - else )
│
├── 函数
│ ├── 定义(def )
│ ├── 参数(位置参数、默认参数、可变参数)
│ ├── 返回值(return )
│ ├── 作用域(局部变量、全局变量)
│ └── 匿名函数(lambda )
│
├── 类与对象
│ ├── 类定义(class )
│ ├── 继承(单继承、多继承)
│ ├── 方法(实例方法、类方法、静态方法)
│ ├── 特殊方法(如 __init__, __str__)
│ └── 属性(@property )
│
├── 模块与包
│ ├── 模块(. py 文件)
│ ├── 导入(import 模块名, from 模块名 import 成员)
│ ├── 包(包含 __init__. py 的目录)
│ └── 标准库与第三方库
│
└── 其他特性├── 迭代器与生成器(iter , next , yield )├── 装饰器(@decorator)├── 上下文管理器(with 语句)└── 元编程(如 type , exec , eval )
一、基础语法规则
1. 缩进与代码块
Python使用缩进(4个空格 )代替大括号 {}
表示代码块。 错误示例 :
if True :
print ( "错误!" )
if True : print ( "缩进正确!" )
2. 注释
单行注释 :以 #
开头。多行注释 :用三引号 """
或 '''
包裹。
"""
这是多行注释
可以写多行内容
"""
3. 语句分隔
一行写多条语句时用分号 ;
分隔(不推荐,多条语句最好是分行写):
a = 5 ; b = 10 ; print ( a + b)
4. 变量命名
规则:字母/数字/下划线组成,不能以数字开头。 区分大小写:name
和 Name
是不同变量。 命名惯例: 小写+下划线(如 user_name
)。 类名用大驼峰(如 ClassName
)。
二、数据类型与操作
1. 基本数据类型
类型 示例 说明 int
5
, -3
整数 float
3.14
, -2.5
浮点数 str
"Hello"
, 'Python'
字符串 bool
True
, False
布尔值 NoneType
None
空值
2. 复合数据类型
nums = [ 1 , 2 , 3 ]
nums[ 0 ] = 10
point = ( 10 , 20 )
user = { "name" : "Alice" , "age" : 25 }
print ( user[ "name" ] )
unique_nums = { 1 , 2 , 2 , 3 }
3. 类型转换
a = int ( "10" )
b = float ( 5 )
c = str ( 3.14 )
d = list ( "abc" )
三、运算符
1. 算术运算符
print ( 5 + 3 )
print ( 5 ** 2 )
print ( 10 % 3 )
2. 比较运算符
print ( 3 > 2 )
print ( 5 == 5.0 )
print ( 5 is 5.0 )
3. 逻辑运算符
print ( True and False )
print ( not True )
4. 成员运算符
nums = [ 1 , 2 , 3 ]
print ( 2 in nums)
print ( 4 not in nums)
四、流程控制
1. 条件语句
age = 18
if age < 13 : print ( "儿童" )
elif age < 18 : print ( "青少年" )
else : print ( "成年人" )
2. 循环语句
for i in range ( 3 ) : print ( i)
fruits = [ "apple" , "banana" ]
for fruit in fruits: print ( fruit)
count = 0
while count < 3 : print ( count) count += 1
3. 循环控制
for i in range ( 5 ) : if i == 3 : break print ( i)
for i in range ( 5 ) : if i == 2 : continue print ( i)
五、函数
1. 定义与调用
def greet ( name) : """返回问候语(文档字符串)""" return f"Hello, { name} !" print ( greet( "Alice" ) )
2. 参数传递
def power ( base, exp= 2 ) : return base ** expprint ( power( 3 ) )
print ( power( 3 , 3 ) )
def sum_all ( * args) : return sum ( args) print ( sum_all( 1 , 2 , 3 ) )
3. Lambda函数
square = lambda x: x ** 2
print ( square( 5 ) )
六、面向对象编程(OOP)
1. 类与对象
class Dog : species = "Canis familiaris" def __init__ ( self, name, age) : self. name = name self. age = agedef bark ( self) : print ( f" { self. name} 汪汪叫!" )
my_dog = Dog( "Buddy" , 3 )
my_dog. bark( )
2. 继承
class GoldenRetriever ( Dog) : def __init__ ( self, name, age, color) : super ( ) . __init__( name, age) self. color = colordef bark ( self) : print ( "温柔的汪汪!" ) golden = GoldenRetriever( "Max" , 2 , "金色" )
golden. bark( )
七、异常处理
try : num = int ( input ( "输入数字:" ) ) result = 10 / num
except ValueError: print ( "输入的不是数字!" )
except ZeroDivisionError: print ( "不能除以0!" )
else : print ( f"结果是 { result} " )
finally : print ( "程序执行完毕" )
八、文件操作
with open ( "test.txt" , "w" ) as f: f. write( "Hello, Python!" )
with open ( "test.txt" , "r" ) as f: content = f. read( ) print ( content)
九、模块与包
1. 导入模块
import math
print ( math. sqrt( 16 ) ) from datetime import datetime
print ( datetime. now( ) )
2. 自定义模块
def say_hello ( ) : print ( "Hello from mymodule!" )
import mymodule
mymodule. say_hello( )
十、Pythonic技巧
1. 列表推导式
squares = [ x** 2 for x in range ( 5 ) ]
2. 字典推导式
square_dict = { x: x** 2 for x in range ( 3 ) }
3. 上下文管理器
with open ( "file.txt" , "r" ) as f: data = f. read( )
常见错误与规范
缩进错误 :代码块必须严格对齐。变量未定义 :使用前需先赋值。修改不可变对象 :如字符串、元组不可修改。PEP8规范 :