第 2 章 变量、基本数据类型与运算符

2.1 变量与赋值

Python 的变量是指向对象的标签,不需要声明类型:

x = 10              # int
name = "Alice"      # str
pi = 3.14159        # float
is_ok = True        # bool

x = "now a string"  # 同一变量可重新绑定不同类型(动态类型)

支持多重赋值与交换:

a, b = 1, 2
a, b = b, a         # 交换,无需临时变量
x = y = z = 0       # 链式赋值

命名规则:字母/下划线开头,只能含字母、数字、下划线;区分大小写;不能用关键字(if、for、class…,可用 keyword.kwlist 查看)。约定 snake_case,常量全大写。

2.2 数字类型

int(整数,无限精度)

n = 1_000_000_000   # 下划线提高可读性
big = 2 ** 100      # 任意精度,不会溢出
hex_n = 0xFF        # 十六进制 → 255
oct_n = 0o17        # 八进制 → 15
bin_n = 0b1010      # 二进制 → 10

float(浮点数)

f = 3.14159
sci = 1.5e3         # 科学计数法 → 1500.0

注意浮点精度:二进制无法精确表示某些十进制小数。

0.1 + 0.2           # 0.30000000000000004 !
round(0.1 + 0.2, 2) # 0.3
# 需要精确计算(如金额)用 decimal.Decimal:
from decimal import Decimal
Decimal("0.1") + Decimal("0.2")   # Decimal('0.3')

complex(复数)

c = 3 + 4j
c.real, c.imag      # (3.0, 4.0)
abs(c)              # 5.0(模)

类型转换

int("42")       # 42
int(3.99)       # 3(向零截断,不是四舍五入!)
float(7)        # 7.0
str(3.14)       # '3.14'
bool(0)         # False;bool("")、bool([]) 也是 False

2.3 字符串 str(不可变)

创建与转义

s1 = 'single'
s2 = "double"
s3 = '''多行
字符串'''
path = r"C:\new\raw"   # r 前缀:原始字符串,\ 不转义

常用转义:\n 换行、\t 制表、\\` 反斜杠、"` 引号。

索引与切片

s = "Python"
s[0]        # 'P'
s[-1]       # 'n'(负索引从尾部数)
s[0:2]      # 'Py'(左闭右开)
s[:3]       # 'Pyt'
s[3:]       # 'hon'
s[::-1]     # 'nohtyP'(反转)
s[::2]      # 'Pto'(步长 2)
s[10]       # IndexError!索引越界报错
s[5:100]    # 'n'(切片越界不报错,截断处理)

常用方法

"hello world".upper()          # 'HELLO WORLD'
"HELLO".lower()                # 'hello'
"hello".capitalize()           # 'Hello'
"  hi  ".strip()               # 'hi'(去两端空白)
"hello".replace("l", "L")      # 'heLLo'
"a,b,c".split(",")             # ['a', 'b', 'c']
"-".join(["a", "b", "c"])      # 'a-b-c'
"hello".startswith("he")       # True
"hello".find("l")              # 2(找不到返回 -1)
"hello".count("l")             # 2
"42".isdigit()                 # True
"abc".isalpha()                # True

字符串不可变:s[0] = "X" 会报 TypeError;所有"修改"方法都返回新字符串。

f-string 格式化(推荐,Python 3.6+)

name, score = "Alice", 92.567
f"{name} 得分 {score}"          # 'Alice 得分 92.567'
f"{score:.1f}"                  # '92.6'(保留 1 位小数)
f"{42:05d}"                     # '00042'
f"{0.856:.1%}"                  # '85.6%'
f"{1234567:,}"                  # '1,234,567'
f"{name=}"                      # "name='Alice'"(调试利器,3.8+)

旧写法供识别:"{}".format(x)、"%s" % x。

2.4 布尔类型与真值测试

bool 只有 True / False,是 int 的子类(True == 1)。

以下值在条件判断中均为 假:None、False、0、0.0、""、[]、{}、set()、()。其余为真。

items = []
if not items:          # 惯用写法,比 len(items) == 0 更 Pythonic
    print("empty")

2.5 运算符

算术运算符

7 + 2    # 9
7 - 2    # 5
7 * 2    # 14
7 / 2    # 3.5   真除法(Python 3)
7 // 2   # 3     整除(向下取整:-7 // 2 == -4)
7 % 2    # 1     取模(结果的符号跟除数)
2 ** 10  # 1024  幂
divmod(7, 2)  # (3, 1) 商和余数一起返回

比较运算符

==(值相等)、!=、<、>、<=、>=。支持链式比较:

0 < x < 10        # 等价于 0 < x and x < 10

== 比较值,is 比较身份(同一对象):

a = [1, 2]; b = [1, 2]
a == b   # True
a is b   # False(不同对象)
# is 仅用于与 None 比较:if x is None:

逻辑运算符

True and False   # False(and:短路,返回第一个假值或最后一个值)
True or False    # True  (or:短路,返回第一个真值)
not True         # False
name = user_input or "匿名"   # 常见惯用法

其他运算符

3 in [1, 2, 3]          # True(成员运算)
"a" not in "abc"        # False
x = None
x is None               # True(身份运算)
i += 1                  # 增量赋值:+= -= *= /= //= %= **=

注意:Python 没有 i++ / i--,用 i += 1。

运算符优先级(从高到低速记)

** → 一元 +- → * / // % → + - → 比较 → not → and → or。拿不准时加括号,可读性更好。

2.6 输入与输出

name = input("你的名字:")     # 返回的永远是字符串!
age = int(input("年龄:"))     # 数字需手动转换,转换失败抛 ValueError
print("a", "b", sep=", ", end="\n")   # a, b

2.7 类型检查与本章小结

type(3)                 # <class 'int'>
isinstance(3, int)      # True(推荐:兼容子类)
isinstance(True, int)   # True!bool 是 int 的子类

小结:变量是标签不是盒子;记住浮点精度陷阱;== 与 is 的区别是高频面试题;字符串不可变;input() 永远返回字符串。

下一章:列表、元组、字典、集合四大容器。

Python3 基础知识 / 第 2 章 变量、基本数据类型与运算符 0 字 0 行 cosolar
2026-09-17T11:10:47.658705830Z 2026-09-17T11:25:53.618884395Z