Python 基础篇(四):变量、输出与运算符


第四章. 变量、输出与运算符

4.1. 第一个程序:print 的基础用法

4.1.1. Hello World(2 分钟)

  • 运行第一行代码
  • 解释 print() 的作用

4.1.2. print 的多个参数

1
2
print("Hello")
print("Hello", "World") # 多个参数,默认用空格分隔

4.1.3. sep 参数:自定义分隔符

1
2
print("Python", "Java", "C++", sep=", ")  # 输出:Python, Java, C++
print("2026", "02", "07", sep="-") # 输出:2026-02-07

4.1.4. end 参数:控制结尾字符

1
2
3
4
5
print("Hello", end=" ")
print("World") # 输出:Hello World(不换行)

print("加载中", end="...")
print("完成") # 输出:加载中...完成

4.2. 变量:给数据贴标签

4.2.1. 什么是变量?

  • 变量是"标签",不是"盒子"
  • Python 不需要声明类型
1
2
3
4
name = "张三"
age = 25
print(name)
print(age)

4.2.2. 变量的命名规范

  • 只能包含字母、数字、下划线
  • 不能以数字开头
  • 不能使用保留字(ifforclass 等)
1
2
3
4
5
6
7
8
9
# ✅ 合法
user_name = "张三"
age_2024 = 25
_private = "私有变量"

# ❌ 非法
2024_age = 25 # 不能以数字开头
user-name = "张三" # 不能用连字符
class = "Python" # 不能用保留字

4.2.3. 命名风格:蛇形 vs 驼峰

1
2
3
4
5
6
7
# 蛇形命名法(Python 推荐)
user_name = "张三"
total_price = 100

# 驼峰命名法(JavaScript 风格,不推荐)
userName = "张三"
totalPrice = 100

4.2.4. 多重赋值

1
2
3
4
5
6
7
# 一行给多个变量赋值
a, b, c = 10, 20, 30

# 交换变量(Python 的优雅写法)
x, y = 5, 10
x, y = y, x # 交换后,x=10, y=5
print(x, y)

4.3. 数据类型:Python 的四大基础类型

4.3.1. 整数 int

1
2
3
4
5
6
age = 25
year = 2026
negative = -100

print(age)
print(type(age)) # 输出:<class 'int'>

4.3.2. 浮点数 float

1
2
3
4
5
6
price = 19.99
pi = 3.14159
temperature = -5.5

print(price)
print(type(price)) # 输出:<class 'float'>

浮点数精度陷阱

1
print(0.1 + 0.2)  # 输出:0.30000000000000004(不是 0.3)

原因:浮点数在计算机中用二进制表示,某些十进制小数无法精确表示。

4.3.3. 字符串 str

1
2
3
4
5
6
7
8
name = "张三"
message = '你好,Python!'
multiline = """这是
多行
字符串"""

print(name)
print(type(name)) # 输出:<class 'str'>

字符串拼接

1
2
3
4
5
6
7
first_name = "张"
last_name = "三"
full_name = first_name + last_name
print(full_name) # 输出:张三

# 字符串重复
print("=" * 20) # 输出:====================

字符串与数字不能直接拼接

1
2
3
4
5
6
# ❌ 错误
age = 25
print("年龄:" + age) # TypeError

# ✅ 正确:先转换类型
print("年龄:" + str(age))

4.3.4. 布尔值 bool

1
2
3
4
5
is_student = True
is_adult = False

print(is_student)
print(type(is_student)) # 输出:<class 'bool'>

4.3.5. 类型转换

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 转换为整数
print(int("123")) # 字符串 → 整数:123
print(int(3.14)) # 浮点数 → 整数:3(截断小数)

# 转换为浮点数
print(float("3.14")) # 字符串 → 浮点数:3.14
print(float(10)) # 整数 → 浮点数:10.0

# 转换为字符串
print(str(123)) # 整数 → 字符串:"123"
print(str(3.14)) # 浮点数 → 字符串:"3.14"

# 转换为布尔值
print(bool(1)) # True
print(bool(0)) # False
print(bool("")) # False(空字符串)
print(bool("Python")) # True(非空字符串)

4.4. 运算符:让数据动起来

4.4.1. 算术运算符

1
2
3
4
5
6
7
8
9
a, b = 10, 3

print(a + b) # 加法:13
print(a - b) # 减法:7
print(a * b) # 乘法:30
print(a / b) # 除法:3.3333...
print(a // b) # 整除:3(向下取整)
print(a % b) # 取余:1
print(a ** b) # 幂运算:1000(10 的 3 次方)

整除 vs 除法

1
2
3
4
5
print(10 / 3)   # 3.3333...(浮点数)
print(10 // 3) # 3(整数)

# 负数的整除(向下取整)
print(-10 // 3) # -4(不是 -3)

取余的实际应用

1
2
3
4
5
6
# 判断奇偶数
number = 7
print(number % 2) # 1(奇数)

number = 8
print(number % 2) # 0(偶数)

4.4.2. 比较运算符

1
2
3
4
5
6
7
8
x, y = 5, 10

print(x == y) # 相等:False
print(x != y) # 不等:True
print(x < y) # 小于:True
print(x > y) # 大于:False
print(x <= y) # 小于等于:True
print(x >= y) # 大于等于:False

比较运算符返回布尔值

1
2
3
result = 5 > 3
print(result) # True
print(type(result)) # <class 'bool'>

4.4.3. 逻辑运算符

1
2
3
4
5
6
7
8
9
10
11
12
# and:与(两个都为 True 才返回 True)
print(True and True) # True
print(True and False) # False
print(False and False) # False

# or:或(至少一个为 True 就返回 True)
print(True or False) # True
print(False or False) # False

# not:非(取反)
print(not True) # False
print(not False) # True

逻辑运算符的实际应用

1
2
3
4
5
6
age = 20
has_id = True

# 判断是否可以进入网吧(年满 18 岁且有身份证)
can_enter = age >= 18 and has_id
print(can_enter) # True

短路求值

1
2
3
4
5
6
7
8
# and 的短路:如果第一个是 False,不会计算第二个
x = 0
result = x != 0 and 10 / x # 不会报错,因为 x != 0 是 False
print(result) # False

# or 的短路:如果第一个是 True,不会计算第二个
result = True or print("这不会执行")
print(result) # True

3.4.4. 赋值运算符

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
x = 10

x += 5 # 等价于 x = x + 5
print(x) # 15

x -= 3 # 等价于 x = x - 3
print(x) # 12

x *= 2 # 等价于 x = x * 2
print(x) # 24

x /= 4 # 等价于 x = x / 4
print(x) # 6.0

x //= 2 # 等价于 x = x // 2
print(x) # 3.0

x %= 2 # 等价于 x = x % 2
print(x) # 1.0

x **= 3 # 等价于 x = x ** 3
print(x) # 1.0

4.4.5. 运算符优先级

1
2
3
4
5
6
7
8
9
10
# 优先级:** > * / // % > + - > 比较运算符 > not > and > or

result = 2 + 3 * 4
print(result) # 14(先乘后加)

result = (2 + 3) * 4
print(result) # 20(括号优先)

result = 5 + 3 > 2 * 4
print(result) # False(先算术,后比较:8 > 8 是 False)

4.5. 字符串格式化:让输出更优雅

4.5.1. 字符串拼接(不推荐)

1
2
3
name = "张三"
age = 25
print("姓名:" + name + ",年龄:" + str(age))

4.5.2. f-string(推荐,Python 3.6+)

1
2
3
name = "张三"
age = 25
print(f"姓名:{name},年龄:{age}")

f-string 中可以写表达式

1
2
3
4
5
a, b = 10, 20
print(f"{a} + {b} = {a + b}") # 输出:10 + 20 = 30

price = 19.99
print(f"价格:{price * 2}") # 输出:价格:39.98

格式化数字

1
2
3
4
5
6
7
pi = 3.14159

print(f"{pi:.2f}") # 保留 2 位小数:3.14
print(f"{pi:.4f}") # 保留 4 位小数:3.1416

price = 1234.5678
print(f"{price:,.2f}") # 千分位分隔:1,234.57

对齐与填充

1
2
3
4
5
6
name = "Python"

print(f"{name:>10}") # 右对齐,总宽度 10: Python
print(f"{name:<10}") # 左对齐,总宽度 10:Python
print(f"{name:^10}") # 居中对齐,总宽度 10: Python
print(f"{name:*^10}") # 用 * 填充:**Python**

4.6. 转义字符:特殊字符的表示

4.6.1. 常用转义字符

1
2
3
4
print("第一行\n第二行")  # \n:换行
print("姓名\t年龄") # \t:制表符(Tab)
print("他说:\"你好!\"") # \":双引号
print("路径:C:\\Users") # \\:反斜杠

4.6.2. 原始字符串(不转义)

1
2
3
4
5
# 普通字符串:\n 会被转义
print("C:\new_folder") # 输出乱码

# 原始字符串:\n 不会被转义
print(r"C:\new_folder") # 输出:C:\new_folder

4.7. 实战练习:个人信息卡片生成器

需求:输入姓名、年龄、城市,生成格式化的信息卡片。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 输入信息(暂时用赋值代替 input,下一章会讲 input)
name = "张三"
age = 25
city = "北京"
salary = 15000.50

# 计算年薪
annual_salary = salary * 12

# 生成信息卡片
print("=" * 40)
print(f"{'个人信息卡片':^40}")
print("=" * 40)
print(f"姓名:{name}")
print(f"年龄:{age} 岁")
print(f"城市:{city}")
print(f"月薪:¥{salary:,.2f}")
print(f"年薪:¥{annual_salary:,.2f}")
print("=" * 40)

输出效果

1
2
3
4
5
6
7
8
9
========================================
个人信息卡片
========================================
姓名:张三
年龄:25 岁
城市:北京
月薪:¥15,000.50
年薪:¥180,006.00
========================================

4.8. 本章小结

本章学习了 Python 的基础语法,掌握了变量、数据类型、运算符和字符串格式化。

知识点使用场景关键动作
print 的 sep/end 参数自定义输出格式print(..., sep=", ", end="")
变量的多重赋值交换变量、批量赋值a, b = b, a
类型转换字符串与数字拼接str(123), int("123")
f-string 格式化优雅地输出变量f"{name},{age} 岁"

下一章,我们将学习用户输入(input)和条件判断(if),让程序能够根据不同情况做出不同反应。