想系统提升编程能力、查看更完整的学习路线,欢迎访问 AI Compass:https://github.com/tingaicompass/AI-Compass
仓库持续更新刷题题解、Python 基础和 AI 实战内容,适合想高效进阶的你。
02 - 变量与数据类型
学习目标: 掌握Python的基本数据类型和变量使用
📖 知识点讲解
Python是动态类型语言,变量不需要声明类型,直接赋值即可。
Python的基本数据类型
| 类型 | 英文名 | 示例 | 说明 |
|---|---|---|---|
| 整数 | int | 42, -10, 0 |
没有大小限制 |
| 浮点数 | float | 3.14, -0.5 |
小数 |
| 字符串 | str | "hello", 'world' |
文本 |
| 布尔值 | bool | True, False |
真/假 |
| 空值 | None | None |
表示"没有值" |
💻 代码示例
示例1:变量赋值
python
# 不需要声明类型,直接赋值
x = 10 # 整数
y = 3.14 # 浮点数
name = "Alice" # 字符串
is_valid = True # 布尔值
result = None # 空值
# 查看类型
print(type(x)) # <class 'int'>
print(type(name)) # <class 'str'>
示例2:整数(int)
python
a = 10
b = -5
c = 0
# 基本运算
print(a + b) # 5
print(a - b) # 15
print(a * b) # -50
print(a / b) # -2.0 (除法结果是浮点数)
print(a // b) # -2 (整除)
print(a % 3) # 1 (取余)
print(a ** 2) # 100 (幂运算)
# Python的整数没有大小限制!
big = 12345678901234567890
print(big * 2) # 不会溢出
示例3:浮点数(float)
python
x = 3.14
y = -0.5
print(x + y) # 2.64
print(x * 2) # 6.28
# ⚠️ 浮点数精度问题
print(0.1 + 0.2) # 0.30000000000000004 (不是0.3!)
示例4:字符串(str)
python
# 单引号或双引号都可以
s1 = "hello"
s2 = 'world'
# 字符串拼接
print(s1 + " " + s2) # hello world
# 字符串重复
print("ha" * 3) # hahaha
# 访问字符
print(s1[0]) # h (第一个字符)
print(s1[-1]) # o (最后一个字符)
# 字符串是不可变的
# s1[0] = 'H' # ❌ 报错!
示例5:布尔值(bool)
python
is_adult = True
is_student = False
# 逻辑运算
print(True and False) # False
print(True or False) # True
print(not True) # False
# 比较运算返回布尔值
print(5 > 3) # True
print(5 == 5) # True
print(5 != 3) # True
# 在条件判断中使用
if is_adult:
print("成年人")
示例6:None - 空值
python
x = None
# 检查是否为None
if x is None:
print("x是空值")
# 函数没有返回值时返回None
def do_nothing():
pass
result = do_nothing()
print(result) # None
# 默认参数常用None
def greet(name=None):
if name is None:
print("Hello, Guest!")
else:
print(f"Hello, {name}!")
greet() # Hello, Guest!
greet("Alice") # Hello, Alice!
🎯 在算法题中的应用
python
# 第1课:两数之和
def twoSum(nums, target): # nums: list, target: int
seen = {} # dict
for i, num in enumerate(nums): # i: int, num: int
complement = target - num # int
if complement in seen: # bool
return [seen[complement], i] # list
seen[num] = i
return [] # 空列表
# 第26课:环形链表
def hasCycle(head): # head: ListNode or None
if not head: # head is None
return False # bool
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
🏋️ 快速练习
练习1:类型转换
python
# 字符串转整数
s = "123"
x = int(s)
print(x + 1) # 124
# 整数转字符串
num = 456
s = str(num)
print(s + "789") # "456789"
# 注意:不能直接转换非数字字符串
# int("hello") # ❌ ValueError
练习2:交换两个变量
python
a = 10
b = 20
# Python特有的简洁写法
a, b = b, a
print(a) # 20
print(b) # 10
🎓 小结
✅ Python是动态类型,变量不需要声明类型
✅ 五种基本类型:int, float, str, bool, None
✅ 使用type()查看类型
✅ 整数没有大小限制
✅ 字符串不可变
✅ 用None表示空值
下一步 : 03-运算符.md
如果这篇内容对你有帮助,推荐收藏 AI Compass:https://github.com/tingaicompass/AI-Compass
更多系统化题解、编程基础和 AI 学习资料都在这里,后续复习和拓展会更省时间。