Skip to content

Python 基础语法

1. Python 是什么

Python 是一种高级编程语言,特点是:

  • 语法简洁
  • 可读性强
  • 上手快
  • 生态丰富

常见应用方向:

text
自动化脚本
Web 开发
数据分析
人工智能
爬虫
运维
测试

查看 Python 版本:

bash
python --version

有些系统需要:

bash
python3 --version

2. 第一个 Python 程序

创建:

text
hello.py

写入:

python
print("Hello, Python!")

运行:

bash
python hello.py

或者:

bash
python3 hello.py

输出:

text
Hello, Python!

3. print() 输出

Python 使用:

python
print()

输出内容。

例如:

python
print("Hello")
print(123)
print(3.14)

输出:

text
Hello
123
3.14

也可以一次输出多个内容:

python
name = "Tom"
age = 18

print(name, age)

输出:

text
Tom 18

4. 注释

单行注释使用:

python
#

例如:

python
# 这是一个注释
print("Hello")

代码后面也可以写:

python
print("Hello")  # 输出 Hello

注释不会被 Python 执行。


5. 变量

变量用于保存数据。

例如:

python
name = "Tom"
age = 18
height = 1.75

这里:

text
name
age
height

就是变量。

Python 不需要提前声明变量类型。

例如:

python
x = 10

Python 会自动判断:

text
x

是整数。


6. 变量命名规则

变量名可以包含:

text
字母
数字
下划线

例如:

python
name = "Tom"
user_name = "Tom"
age2 = 18

变量名不能以数字开头:

python
2age = 18

这是错误的。

推荐使用:

text
snake_case

例如:

python
user_name = "Tom"
student_age = 18
total_score = 100

7. Python 区分大小写

Python 区分大小写。

例如:

python
name = "Tom"
Name = "Jerry"

这两个变量完全不同:

text
name
Name

同样:

python
print()

不能写成:

python
Print()

8. 基本数据类型

Python 常见基础数据类型:

类型含义示例
int整数10
float浮点数3.14
str字符串"Hello"
bool布尔值True
NoneType空值None

例如:

python
age = 18
height = 1.75
name = "Tom"
is_student = True
result = None

9. type() 查看类型

可以使用:

python
type()

查看数据类型。

例如:

python
age = 18

print(type(age))

输出:

text
<class 'int'>

再例如:

python
print(type(3.14))
print(type("Hello"))
print(type(True))

分别对应:

text
float
str
bool

10. 整数 int

整数:

python
a = 10
b = -20
c = 0

它们都是:

text
int

可以进行数学运算:

python
a = 10
b = 3

print(a + b)
print(a - b)
print(a * b)

11. 浮点数 float

带小数的数据通常是:

text
float

例如:

python
price = 19.99
height = 1.75
pi = 3.14159

查看:

python
print(type(price))

输出:

text
<class 'float'>

12. 字符串 str

字符串可以使用:

text
""
''

例如:

python
name = "Tom"
city = 'Beijing'

两种方式都可以。

字符串可以拼接:

python
first_name = "Moonlit"
last_name = "Boy"

print(first_name + last_name)

输出:

text
MoonlitBoy

如果需要空格:

python
print(first_name + " " + last_name)

13. 多行字符串

可以使用三引号:

python
text = """
Hello
Python
Linux
"""

例如:

python
print(text)

可以输出多行内容。


14. 字符串索引

字符串中的字符可以通过下标访问。

例如:

python
text = "Python"

下标:

text
P  y  t  h  o  n
0  1  2  3  4  5

获取第一个字符:

python
print(text[0])

输出:

text
P

获取最后一个字符:

python
print(text[-1])

输出:

text
n

15. 字符串切片

格式:

python
字符串[开始:结束]

例如:

python
text = "Python"

print(text[0:3])

输出:

text
Pyt

注意:

text
包含开始位置
不包含结束位置

所以:

python
text[0:3]

实际上取:

text
0
1
2

16. 常见字符串方法

例如:

python
text = "hello python"

转大写:

python
print(text.upper())

转小写:

python
print(text.lower())

首字母大写:

python
print(text.capitalize())

替换:

python
print(text.replace("python", "linux"))

查找:

python
print(text.find("python"))

17. f-string

Python 中推荐使用:

text
f-string

格式化字符串。

例如:

python
name = "Tom"
age = 18

print(f"My name is {name}, I am {age} years old.")

输出:

text
My name is Tom, I am 18 years old.

比字符串拼接更加清晰。


18. 布尔值 bool

布尔值只有两个:

python
True
False

注意首字母必须大写。

例如:

python
is_student = True
is_admin = False

19. None

Python 中:

python
None

表示没有值。

例如:

python
result = None

可以理解为:

text
当前还没有有效数据

判断:

python
if result is None:
    print("没有结果")

20. 类型转换

字符串转换为整数:

python
age = int("18")

整数转换为字符串:

python
number = str(100)

整数转换为浮点数:

python
number = float(10)

浮点数转换为整数:

python
number = int(3.14)

结果:

text
3

注意:

python
int("hello")

会报错,因为:

text
hello

不能转换成整数。


21. 用户输入 input()

获取用户输入:

python
name = input("请输入名字:")

print(name)

例如用户输入:

text
Tom

那么:

text
name

保存的就是:

text
Tom

22. input() 返回字符串

需要特别注意:

python
input()

默认返回:

text
str

例如:

python
age = input("请输入年龄:")

print(type(age))

即使输入:

text
18

类型依然是:

text
str

如果需要整数:

python
age = int(input("请输入年龄:"))

23. 算术运算符

常见数学运算:

运算符含义
+
-
*
/
//整除
%取余
**

例如:

python
a = 10
b = 3

普通除法:

python
print(a / b)

结果大约:

text
3.3333333333

整除:

python
print(a // b)

输出:

text
3

取余:

python
print(a % b)

输出:

text
1

幂:

python
print(2 ** 3)

输出:

text
8

24. 比较运算符

运算符含义
==等于
!=不等于
>大于
<小于
>=大于等于
<=小于等于

例如:

python
a = 10

print(a == 10)
print(a > 5)
print(a < 3)

输出:

text
True
True
False

注意:

text
=

是赋值。

text
==

才是判断是否相等。


25. 逻辑运算符

Python 常见逻辑运算:

text
and
or
not

例如:

python
age = 20

print(age >= 18 and age <= 60)

两个条件都满足才为:

text
True

使用 or

python
score = 95

print(score < 60 or score >= 90)

只要有一个成立,就是:

text
True

使用 not

python
is_admin = False

print(not is_admin)

输出:

text
True

26. if 条件判断

基本格式:

python
if 条件:
    代码

例如:

python
age = 20

if age >= 18:
    print("成年人")

Python 使用:

text
缩进

表示代码块。


27. if...else

例如:

python
age = 16

if age >= 18:
    print("成年人")
else:
    print("未成年人")

28. if...elif...else

例如:

python
score = 85

if score >= 90:
    print("优秀")
elif score >= 80:
    print("良好")
elif score >= 60:
    print("及格")
else:
    print("不及格")

29. Python 缩进

Python 不使用:

text
{}

划分代码块。

而使用缩进。

例如:

python
if True:
    print("Hello")

推荐使用:

text
4 个空格

例如:

python
if age >= 18:
    print("成年人")
    print("可以继续")

这两行都属于:

text
if

代码块。


30. for 循环

基本格式:

python
for 变量 in 数据:
    代码

例如:

python
for i in range(5):
    print(i)

输出:

text
0
1
2
3
4

31. range()

常见:

python
range(5)

产生:

text
0 1 2 3 4

指定开始位置:

python
range(1, 5)

产生:

text
1 2 3 4

指定步长:

python
range(0, 10, 2)

产生:

text
0 2 4 6 8

32. 遍历字符串

例如:

python
for char in "Python":
    print(char)

输出:

text
P
y
t
h
o
n

33. while 循环

基本格式:

python
while 条件:
    代码

例如:

python
i = 0

while i < 5:
    print(i)
    i += 1

输出:

text
0
1
2
3
4

34. break

break 用于立即结束循环。

例如:

python
for i in range(10):
    if i == 5:
        break

    print(i)

输出:

text
0
1
2
3
4

35. continue

continue 用于跳过当前这一次循环。

例如:

python
for i in range(5):
    if i == 2:
        continue

    print(i)

输出:

text
0
1
3
4

36. 列表 list

列表用于保存多个数据。

例如:

python
names = ["Tom", "Jack", "Alice"]

访问第一个元素:

python
print(names[0])

输出:

text
Tom

列表索引同样从:

text
0

开始。


37. 修改列表

例如:

python
names = ["Tom", "Jack", "Alice"]

names[0] = "Bob"

现在列表变成:

python
["Bob", "Jack", "Alice"]

38. 添加列表元素

使用:

python
append()

例如:

python
names = ["Tom", "Jack"]

names.append("Alice")

结果:

python
["Tom", "Jack", "Alice"]

39. 删除列表元素

使用:

python
remove()

例如:

python
names.remove("Tom")

或者:

python
pop()

例如:

python
names.pop()

默认删除最后一个元素。

也可以:

python
names.pop(0)

删除下标为:

text
0

的元素。


40. 获取列表长度

使用:

python
len()

例如:

python
names = ["Tom", "Jack", "Alice"]

print(len(names))

输出:

text
3

41. 遍历列表

例如:

python
names = ["Tom", "Jack", "Alice"]

for name in names:
    print(name)

输出:

text
Tom
Jack
Alice

42. 元组 tuple

元组和列表类似,但通常不能修改。

例如:

python
point = (10, 20)

访问:

python
print(point[0])

输出:

text
10

元组使用:

text
()

列表使用:

text
[]

43. 字典 dict

字典使用:

text
键: 值

保存数据。

例如:

python
user = {
    "name": "Tom",
    "age": 18
}

获取:

python
print(user["name"])

输出:

text
Tom

44. 修改字典

例如:

python
user["age"] = 20

添加新数据:

python
user["city"] = "Beijing"

现在:

python
print(user)

可能得到:

text
{'name': 'Tom', 'age': 20, 'city': 'Beijing'}

45. 集合 set

集合:

python
numbers = {1, 2, 3, 4}

集合中的元素不会重复。

例如:

python
numbers = {1, 1, 2, 2, 3}

print(numbers)

结果类似:

text
{1, 2, 3}

集合经常用于:

text
去重
成员判断
集合运算

46. in

使用:

python
in

判断某个元素是否存在。

例如:

python
names = ["Tom", "Jack"]

print("Tom" in names)

输出:

text
True

字符串也可以:

python
print("Py" in "Python")

输出:

text
True

47. 函数

使用:

python
def

定义函数。

例如:

python
def hello():
    print("Hello")

调用:

python
hello()

输出:

text
Hello

48. 函数参数

例如:

python
def hello(name):
    print(f"Hello, {name}")

调用:

python
hello("Tom")

输出:

text
Hello, Tom

49. return

函数可以使用:

python
return

返回结果。

例如:

python
def add(a, b):
    return a + b

调用:

python
result = add(10, 20)

print(result)

输出:

text
30

50. 默认参数

例如:

python
def hello(name="Python"):
    print(f"Hello, {name}")

调用:

python
hello()

输出:

text
Hello, Python

也可以:

python
hello("Tom")

51. 导入模块

Python 使用:

python
import

导入模块。

例如:

python
import math

print(math.sqrt(16))

输出:

text
4.0

52. from ... import ...

也可以只导入某个功能:

python
from math import sqrt

print(sqrt(16))

这样就不需要写:

text
math.sqrt()

53. as

可以给模块设置别名。

例如:

python
import math as m

print(m.sqrt(16))

54. 异常处理

程序运行时可能出现错误。

例如:

python
number = int(input("请输入数字:"))

如果用户输入:

text
hello

会出现异常。

可以使用:

python
try:
    number = int(input("请输入数字:"))
    print(number)
except ValueError:
    print("输入的不是有效数字")

55. pass

pass 表示暂时什么都不做。

例如:

python
if True:
    pass

常用于先搭好代码结构。

例如:

python
def hello():
    pass

56. 常见内置函数

函数作用
print()输出
input()输入
type()查看类型
len()获取长度
int()转整数
float()转浮点数
str()转字符串
bool()转布尔值
range()生成数字序列
sum()求和
max()最大值
min()最小值
sorted()排序

例如:

python
numbers = [10, 20, 30]

print(sum(numbers))
print(max(numbers))
print(min(numbers))

57. 一个完整示例

python
name = input("请输入你的名字:")
score = int(input("请输入你的成绩:"))

if score >= 90:
    level = "优秀"
elif score >= 80:
    level = "良好"
elif score >= 60:
    level = "及格"
else:
    level = "不及格"

print(f"{name} 的成绩是 {score},等级为 {level}")

如果输入:

text
Tom
85

输出:

text
Tom 的成绩是 85,等级为 良好

这个简单程序已经包含:

text
变量
input
int
if
elif
else
f-string
print

58. Python 基础语法速查

变量

python
name = "Tom"
age = 18

输出

python
print("Hello")

输入

python
name = input("请输入名字:")

条件判断

python
if age >= 18:
    print("成年人")
else:
    print("未成年人")

for 循环

python
for i in range(5):
    print(i)

while 循环

python
while condition:
    pass

列表

python
numbers = [1, 2, 3]

字典

python
user = {
    "name": "Tom",
    "age": 18
}

函数

python
def add(a, b):
    return a + b

导入模块

python
import math

小结

Python 入门阶段最重要的内容可以概括为:

text
变量
数据类型
输入输出
运算符
条件判断
循环
列表
元组
字典
集合
函数
模块
异常处理

最基础的代码结构:

python
name = input("请输入名字:")

if name == "Tom":
    print("Hello Tom")
else:
    print(f"Hello {name}")

学习 Python 时,不建议只背语法。

更重要的是自己多写:

text
判断题
循环题
列表操作
字符串处理
简单函数
小型脚本

把这些基础语法真正写熟以后,再继续学习:

text
文件操作
模块与包
虚拟环境
面向对象
第三方库
项目结构

会更加顺畅。