Python 基础:变量与数据类型

5 阅读3分钟

一、什么是变量?

变量是存储数据的容器。在 Python 中,你不需要声明变量类型,Python 会自动推断。

# 变量赋值
name = "Alice"
age = 25
height = 1.68
is_student = True

print(f"姓名:{name}")
print(f"年龄:{age}")
print(f"身高:{height}米")
print(f"是否学生:{is_student}")

输出:

姓名:Alice
年龄:25
身高:1.68 米
是否学生:True

二、Python 的核心数据类型

1. 数值类型

# 整数 (int)
count = 100
negative = -50

# 浮点数 (float)
price = 19.99
pi = 3.14159

# 复数 (complex)
complex_num = 3 + 4j

print(f"整数:{count}, 类型:{type(count)}")
print(f"浮点数:{price}, 类型:{type(price)}")
print(f"复数:{complex_num}, 类型:{type(complex_num)}")

2. 字符串 (str)

# 字符串定义
single_quote = 'Hello'
double_quote = "World"
multi_line = """这是
多行
字符串"""

# 字符串操作
greeting = "Hello, Python!"
print(f"长度:{len(greeting)}")
print(f"大写:{greeting.upper()}")
print(f"截取:{greeting[0:5]}")
print(f"替换:{greeting.replace('Python', 'World')}")

3. 布尔类型 (bool)

# 布尔值
is_true = True
is_false = False

# 布尔运算
print(f"True and False: {True and False}")
print(f"True or False: {True or False}")
print(f"not True: {not True}")

# 比较运算产生布尔值
print(f"5 > 3: {5 > 3}")
print(f"5 == 5: {5 == 5}")

4. 序列类型

列表 (list) - 可变序列

# 创建列表
fruits = ["apple", "banana", "orange"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]

# 列表操作
fruits.append("grape")      # 添加元素
fruits[0] = "Apple"         # 修改元素
removed = fruits.pop()      # 移除最后一个

print(f"列表:{fruits}")
print(f"长度:{len(fruits)}")
print(f"切片:{fruits[1:3]}")

元组 (tuple) - 不可变序列

# 创建元组
coordinates = (10, 20)
colors = ("red", "green", "blue")
single = (42,)  # 单元素元组需要逗号

print(f"坐标:{coordinates}")
print(f"颜色:{colors}")
print(f"第一个颜色:{colors[0]}")

# 元组不可修改(以下会报错)
# colors[0] = "yellow"  # TypeError!

5. 字典 (dict) - 键值对

# 创建字典
person = {
    "name": "Alice",
    "age": 25,
    "city": "Beijing"
}

# 字典操作
print(f"姓名:{person['name']}")
person["email"] = "alice@example.com"  # 添加
person["age"] = 26                      # 修改
del person["city"]                      # 删除

print(f"更新后:{person}")
print(f"所有键:{list(person.keys())}")
print(f"所有值:{list(person.values())}")

6. 集合 (set) - 无序不重复

# 创建集合
numbers = {1, 2, 3, 3, 4, 4, 5}
print(f"集合(自动去重):{numbers}")

# 集合运算
set_a = {1, 2, 3, 4}
set_b = {3, 4, 5, 6}

print(f"并集:{set_a | set_b}")
print(f"交集:{set_a & set_b}")
print(f"差集:{set_a - set_b}")

三、类型转换

# 显式类型转换
num_str = "123"
num_int = int(num_str)
num_float = float(num_str)

print(f"字符串转整数:{num_int + 10}")
print(f"字符串转浮点:{num_float * 2}")

# 其他类型转字符串
value = 42
text = str(value)
print(f"整数转字符串:'{text}'")

# 列表转元组
my_list = [1, 2, 3]
my_tuple = tuple(my_list)
print(f"列表转元组:{my_tuple}")

四、实战练习:学生信息管理系统

# 简易学生信息管理系统
def create_student(name, age, grade):
    """创建学生记录"""
    return {
        "name": name,
        "age": age,
        "grade": grade,
        "courses": []
    }

def add_course(student, course_name):
    """添加课程"""
    student["courses"].append(course_name)
    return student

def display_student(student):
    """显示学生信息"""
    print(f"\n{'='*30}")
    print(f"姓名:{student['name']}")
    print(f"年龄:{student['age']}")
    print(f"年级:{student['grade']}")
    print(f"课程:{', '.join(student['courses']) or '暂无'}")
    print(f"{'='*30}")

# 使用示例
if __name__ == "__main__":
    # 创建学生
    student1 = create_student("张三", 18, "高一")
    student2 = create_student("李四", 19, "高二")
    
    # 添加课程
    add_course(student1, "数学")
    add_course(student1, "英语")
    add_course(student2, "物理")
    
    # 显示信息
    display_student(student1)
    display_student(student2)
    
    # 统计
    students = [student1, student2]
    print(f"\n总学生数:{len(students)}")
    print(f"平均年龄:{sum(s['age'] for s in students) / len(students)}")

运行结果:

==============================
姓名:张三
年龄:18
年级:高一
课程:数学,英语
==============================

==============================
姓名:李四
年龄:19
年级:高二
课程:物理
==============================

总学生数:2
平均年龄:18.5

五、今日要点总结

数据类型可变性示例
int不可变42
float不可变3.14
str不可变"hello"
bool不可变True
list可变[1, 2, 3]
tuple不可变(1, 2, 3)
dict可变{"key": "value"}
set可变{1, 2, 3}

关键记忆点:

  1. Python 是动态类型语言,无需声明变量类型
  2. 使用 type() 查看变量类型
  3. 列表可变,元组不可变
  4. 字典是键值对,集合自动去重
  5. 使用 int(), str(), float() 等进行类型转换