Python 变量与数据类型核心指南
概述
变量和数据类型是编程的基石。在 Python 中,变量就像是一个个容器,用来存储数据;而数据类型则决定了这个容器能装什么、以及能对里面的数据做什么操作。
数据类型概览
Python 的数据类型主要分为基本类型和复合类型两大类:
数据类型 ├── 基本数据类型 │ ├── 数字类型 (Numbers) │ ├── 字符串类型 (String) │ ├── 布尔类型 (Boolean) │ └── None 类型 └── 复合数据类型 ├── 列表类型 (List) ├── 元组类型 (Tuple) ├── 字典类型 (Dictionary) └── 集合类型 (Set)
实战代码示例
下面我们通过一段完整的代码来演示这些类型的声明、使用及特性。注意观察 type() 函数的输出,它能帮你确认变量的实际类型。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 1. 数字类型 (Numbers)
print("=== 数字类型 ===")
# 整数 (Integer)
age = 25
print(f"整数示例 - 年龄:{age} (类型:{type(age)})")
# 浮点数 (Float)
height = 175.5
print(f"浮点数示例 - 身高:{height}cm (类型:{type(height)})")
# 复数 (Complex)
complex_num = 3 + 4j
print(f"复数示例:{complex_num} (类型:{type(complex_num)})")
# 布尔值 (Boolean) - 实际上是 int 的子类
is_student = True
is_employed = False
print(f"布尔值示例 - 是学生:{is_student} (类型:{type(is_student)})")
print(f"布尔值示例 - 已就业: (类型:)")
()
()
name =
()
message =
()
multiline_text =
()
formatted_str =
()
()
()
fruits = [, , ]
()
()
fruits[] =
()
fruits.append()
()
()
()
coordinates = (, )
()
x, y = coordinates
()
()
()
person = {: , : , : }
()
()
person[] =
()
()
()
unique_numbers = {, , , , , , }
()
set_a = {, , }
set_b = {, , }
union_result = set_a | set_b
()
intersection_result = set_a & set_b
()
()
()
str_num =
int_num = (str_num)
()
num =
str_from_num = (num)
()
my_list = [, , ]
my_tuple = (my_list)
()
original_tuple = (, , )
new_list = (original_tuple)
()
()
()
result =
()
()
()
variations = [age, height, name, is_student, fruits, coordinates, person, unique_numbers]
i, var (variations, ):
()


