Python 基础核心概念与实战代码示例(含数据类型、变量、流程控制、数据结构、函数与文件操作)
Python 基础核心概念与实战代码示例(含数据类型、变量、流程控制、数据结构、函数与文件操作)
- 环境
- 介绍
- 基本数据类型
- 变量与运算符
- 流程控制
- 条件语句
- 循环语句
- 核心数据结构
- 函数
- 基本文件操作
环境
Python 3.12.2
介绍
下面这些内容涵盖了 Python 编程的基础知识,包括数据的存储形式(基本数据类型)、数据的操作方式(变量与运算符)、程序的执行逻辑(流程控制)、高效组织数据的方式(核心数据结构)、代码复用机制(函数)以及与外部存储交互的方法(文件操作),是构建 Python 程序的基础要素。
基本数据类型
# 整数 (int)
age = 25
print("整数:", age, type(age))# 浮点数 (float)
height = 1.75
print("浮点数:", height, type(height))# 字符串 (str)
name = "Alice"
print("字符串:", name, type(name))# 布尔值 (bool)
is_student = True
print("布尔值:", is_student, type(is_student))
变量与运算符
# 变量
a = 10
b = 3# 算术运算
print("加法:", a + b)
print("减法:", a - b)
print("乘法:", a * b)
print("除法:", a / b)
print("整除:", a // b)
print("取余:", a % b)
print("幂运算:", a **b)# 比较运算
print("等于:", a == b)
print("不等于:", a != b)
print("大于:", a > b)
print("小于等于:", a <= b)# 逻辑运算
x = True
y = False
print("与运算:", x and y)
print("或运算:", x or y)
print("非运算:", not x)
流程控制
条件语句
score = 85if score >= 90:print("优秀")
elif score >= 80:print("良好")
elif score >= 60:print("及格")
else:print("不及格")
循环语句
# for循环
print("for循环:")
for i in range(5):print(i)# while循环
print("\n while循环:")
count = 0
while count < 5:print(count)count += 1# 循环中的break和continue
print("\n 带break的循环:")
for i in range(10):if i == 5:breakprint(i)
核心数据结构
# 列表 (List)
a_tree = ["大树", "小树", "小树苗"]
print("列表:", a_tree)
print("列表第一个元素:", a_tree[0])
a_tree.append("大树苗") # 添加元素
print("添加元素后的列表:", a_tree)# 元组 (Tuple) - 不可变
b_tree = ("大树", 250, "小树")
print("\n 元组:", b_tree)
print("元组第二个元素:", b_tree[1])# 字典 (Dictionary)
o_tree = {"name": "小树","age": 200
}
print("\n 字典:", o_tree)
print("树的姓名:", o_tree["name"])
o_tree["height"] = "99米"
print("添加键值对后的字典:", o_tree)# 集合 (Set) - 无序且不重复
numbers = {1, 2, 3, 4, 4, 5, "魔丸", "魔丸"}
print("\n 集合:", numbers) # 自动去重
numbers.add(6) # 添加元素
print("添加元素后的集合:", numbers)
函数
# 定义函数
def print_tree_name(name):"""打印输出树的名字"""return f"树的名字是:{name}!"# 调用函数
message = print_tree_name("大大树")
print(message)# 带默认参数的函数
def calculate_area(length, width=1):"""计算矩形面积,默认宽度为1"""return length * widthprint("面积1:", calculate_area(5)) # 使用默认宽度
print("面积2:", calculate_area(5, 3)) # 指定宽度# 带返回多个值的函数
def get_name_and_age():return "小树", 200name, age = get_name_and_age()
print(f"姓名: {name}, 年龄: {age}")
基本文件操作
# 写入文件
with open("example.txt", "w", encoding="utf-8") as file:file.write("Hello!\n")file.write("我是测试文件。我是测试文件!\n")# 读取文件
with open("example.txt", "r", encoding="utf-8") as file:content = file.read()print("文件内容:")print(content)# 追加内容到文件
with open("example.txt", "a", encoding="utf-8") as file:file.write("我是追加的内容。\n")