无论你是刚接触编程的新手,还是从其他语言转过来的开发者,掌握Python3的基础语法都是绕不开的第一步。这篇文章帮你把最核心的语法规则一次性梳理清楚,附代码示例,建议收藏。
一、编码与标识符
Python3源码文件默认以UTF-8编码,所有字符串都是Unicode字符串。你也可以在文件头部指定其他编码:
# -*- coding: cp-1252 -*-
标识符的命名规则:
- 第一个字符必须是字母或下划线_
- 其他部分可以由字母、数字和下划线组成
- 对大小写敏感(name和Name是两个不同的变量)
- Python3支持非ASCII标识符,比如可以用中文做变量名(但不建议)
保留字(关键字) 不能用作标识符。用以下代码可以查看当前版本所有关键字:
import keyword print(keyword.kwlist)
二、注释
单行注释以#开头:
# 这是一个单行注释
print("Hello, World!") # 行尾注释多行注释用三对单引号'''或三对双引号""":
''' 这是多行注释 可以写多行内容 ''' """ 这也是多行注释 用双引号也可以 """
三、缩进——Python最具特色的语法
Python用缩进来表示代码块,不需要大括号{}。缩进的空格数可以变,但同一个代码块内的语句必须保持相同的缩进空格数。
if True:
print("True") # 缩进4个空格
print("继续执行")
else:
print("False")缩进不一致会直接报错:
if True:
print("Answer")
print("True") # 这一行缩进不一致,运行报错官方推荐的缩进方式是4个空格。
四、多行语句
Python通常一行写一条语句。如果语句太长,可以用反斜杠\续行:
total = item_one + \ item_two + \ item_three
在[]、{}、()中的多行语句不需要反斜杠:
items = [ "apple", "banana", "orange" ]
同一行可以写多条语句,用分号;分隔:
a = 1; b = 2; print(a + b)
五、六个标准数据类型
Python3有六个标准数据类型-12-13:
类型 | 说明 | 示例 |
Number(数字) | 整数、浮点数、布尔、复数 | 1 , 3.14 , True , 1+2j |
String(字符串) | 文本 | "hello" |
List(列表) | 有序可变集合 | [1, 2, 3] |
Tuple(元组) | 有序不可变集合 | (1, 2, 3) |
Set(集合) | 无序不重复集合 | {1, 2, 3} |
Dictionary(字典) | 键值对 | {"name": "Tom"} |
不可变与可变:
- 不可变(3个):Number、String、Tuple——修改值会创建新对象
- 可变(3个):List、Dictionary、Set——修改值不会创建新对象
用type()可以检查变量类型:
x = "hello" print(type(x)) # <class 'str'>
数字类型细分-14-10:
- int:整数,Python3只有这一种整数类型(没有Long)
- float:浮点数,如1.23、3E-2
- bool:布尔值,只有True和False
- complex:复数,如1+2j
六、字符串
字符串的几个关键点:
# 单引号和双引号完全等价 s1 = 'hello' s2 = "world" # 三引号表示多行字符串 s3 = """这是 多行 字符串""" # 转义符 \ s4 = "hello\nworld" # \n换行 # 原始字符串(不转义) s5 = r"hello\nworld" # 输出 hello\nworld # 字符串连接 s6 = "hello" + "world" # helloworld # 字符串重复 s7 = "ha" * 3 # hahaha # 字符串不可变 s = "hello" # s[0] = "H" # 这会报错! # 切片:变量[头下标:尾下标:步长] s = "HelloWorld" print(s[0:5]) # Hello print(s[-5:]) # World print(s[::2]) # HloWr(隔一个取一个)
七、运算符
Python支持以下运算符类型:
算术运算符:+ - * / % // **
print(10 / 3) # 3.333...(浮点数除法) print(10 // 3) # 3(整数除法) print(10 % 3) # 1(取余) print(2 ** 3) # 8(幂运算)
比较运算符:== != > < >= <=
赋值运算符:= += -= *= /= %= //= **=
a = 10 a += 5 # 等价于 a = a + 5
逻辑运算符:and or not(优先级:not > and > or)
成员运算符:in not in
print("a" in "hello") # False
print(2 in [1, 2, 3]) # True身份运算符:is not is
a = [1, 2, 3] b = [1, 2, 3] print(a is b) # False(不同对象) print(a == b) # True(值相同)
运算符优先级:算术运算符 > 比较运算符 > 逻辑运算符-
八、输入与输出
输出:print()
print("Hello")
print("a =", a)输入:input()返回字符串
name = input("请输入你的名字:")
print("你好,", name)
# 一次性输入多个值
a, b = input().split() # 输入 "10 20"九、条件控制(if)
age = 18
if age < 18:
print("未成年")
elif age < 60:
print("成年")
else:
print("老年")注意:Python没有switch语句,用if-elif-else代替。
十、循环(for / while)
for循环:遍历可迭代对象
# 遍历列表 for i in [1, 2, 3]: print(i) # 遍历字符串 for ch in "hello": print(ch) # range()生成数字序列 for i in range(5): # 0,1,2,3,4 print(i) for i in range(2, 6): # 2,3,4,5 print(i) for i in range(0, 10, 2): # 0,2,4,6,8 print(i)
while循环:
i = 0 while i < 5: print(i) i += 1
break / continue / else:
# break:跳出循环
for i in range(10):
if i == 5:
break
print(i) # 只输出0-4
# continue:跳过本次迭代
for i in range(5):
if i == 2:
continue
print(i) # 输出0,1,3,4
# else:循环正常结束时执行(未触发break)
for i in range(3):
print(i)
else:
print("循环正常结束")十一、函数
定义与调用:
def 函数名(参数列表): """函数说明文档""" 函数体 return 返回值
def add(a, b): """返回两数之和""" return a + b result = add(3, 5) # 8
默认参数:
def greet(name, msg="你好"):
print(msg, name)
greet("Tom") # 你好 Tom
greet("Tom", "Hello") # Hello Tom返回值:可以返回任意类型,不写return默认返回None-。可以返回多个值:
def get_name_and_age(): return "Tom", 18 name, age = get_name_and_age()
十二、几个初学者最容易踩的坑
- 缩进混用空格和Tab——编辑器里统一用4个空格,不要混用
- 中文注释报错——文件头部加# -*- coding: utf-8 -*-
- ==和is分不清——==比较值,is比较内存地址
- 字符串是不可变的——s[0] = 'a'会报错,要用切片重新赋值
- /和//搞混——/返回浮点数,//返回整数
- 变量名用了关键字——比如class、def、if都不能做变量名
以上就是Python3基础语法的核心内容。把这些规则吃透,你就能读懂和写出大部分Python代码了。接下来就可以去学习流程控制、数据结构、面向对象等进阶内容了。
