基础数据类型演示

Python基础代码大全:从入门到实战的必备代码合集

在Python编程学习之路上,掌握基础代码是构建复杂应用的地基,本文整理了Python开发中最常用的基础代码模块,涵盖变量、控制结构、数据结构、函数、文件操作等核心场景,每个模块均附有可直接运行的代码示例与详细注释,助您快速搭建编程知识体系。

变量与数据类型 Python的动态类型特性让变量声明无需显式指定类型,但理解基础数据类型至关重要:

age = 30                # 整数类型
height = 1.75           # 浮点类型
is_active = True        # 布尔类型
complex_num = 3+4j      # 复数类型
# 类型检查与转换
print(type(name))       # <class 'str'>
num_str = "123"
num_int = int(num_str)  # 字符串转整数

运算符与表达式 掌握运算符优先级和类型转换规则能避免逻辑错误:

# 算术运算符
a, b = 10, 3
print(a + b, a - b, a * b, a // b)  # 13 7 30 3
# 比较与逻辑运算符
print(a > b and b != 0)  # True
print(not (a < b or b == 0))  # True
# 成员与身份运算符
list_data = [1, 2, 3]
print(2 in list_data)   # True
print([1,2] is [1,2])  # False(内存地址不同)

控制结构 条件判断与循环是程序逻辑的核心:

# if-elif-else结构
score = 85
if score >= 90:
    print("优秀")
elif score >= 75:
    print("良好")  # 此分支将被执行
else:
    print("待提高")
# for循环遍历多种数据结构
for i in range(5):          # 数字序列遍历
    print(i, end=" ")       # 输出0-4
fruits = ["apple", "banana"]
for fruit in fruits:        # 列表遍历
    print(fruit.upper())
# while循环与break/continue
count = 0
while count < 5:
    count += 1
    if count == 3:
        continue           # 跳过当前迭代剩余代码
    print(count)

函数与模块 函数封装可复用逻辑,模块化提升代码可维护性:

# 定义带参数和返回值的函数
def calculate_area(length, width=2):
    """计算矩形面积,支持默认参数"""
    return length * width
print(calculate_area(5))       # 10(使用默认宽度)
# 变量作用域演示
total = 0
def add_num(value):
    global total             # 声明全局变量
    total += value
add_num(10)
print(total)                 # 10
# 模块导入与使用
import math
print(math.sqrt(16))        # 4.0
from datetime import datetime
print(datetime.now().strftime("%Y-%m-%d"))

数据结构操作 列表、字典、集合等数据结构的常用操作:

# 列表操作
my_list = [4, 2, 3, 1]
my_list.sort()             # 升序排序
print(my_list[1:3])        # [2, 3](切片操作)
# 字典操作
student = {"name": "Tom", "age": 18}
student["class"] = "CS101" # 添加新键值对
for key, value in student.items():
    print(f"{key}: {value}")
# 集合操作
set_a = {1, 2, 3}
set_b = {3, 4, 5}
print(set_a & set_b)       # 交集 {3}
print(set_a | set_b)       # 并集 {1,2,3,4,5}
# 元组不可变性示例
tuple_data = (10, 20)
# tuple_data[0] = 30 会引发TypeError

文件操作 文件读写是数据处理的基础技能:

# 写入文件
with open("demo.txt", "w") as file:
    file.write("第一行数据\n第二行数据")
# 读取文件
with open("demo.txt", "r") as file:
    for line in file:
        print(line.strip())  # 去除换行符
# CSV文件处理
import csv
with open("data.csv", "w", newline="") as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(["ID", "Name"])
    writer.writerows([[1, "Alice"], [2, "Bob"]])

异常处理 优雅处理运行时错误保障程序健壮性:

try:
    result = 10 / 0
except ZeroDivisionError as e:
    print(f"除零错误: {e}")
finally:
    print("无论是否出错都会执行")
# 自定义异常
class CustomError(Exception):
    pass
def check_value(value):
    if value < 0:
        raise CustomError("值不能为负数")
    return value

这些基础代码模块构成了Python编程的基石,通过实际编写和修改这些示例代码,您将深入理解Python的语法特性和编程思想,建议将每个模块的代码亲自运行测试,观察不同输入下的输出结果,从而真正掌握这些基础代码的精髓,随着实践的深入,您会发现这些基础代码片段可以组合出强大的应用程序,为后续学习数据分析、Web开发、机器学习等高级应用奠定坚实基础。

(7)

猜你喜欢

发表回复

本站作者才能评论

评论列表(3条)

  • 初夏兰的头像
    初夏兰 2026年02月19日

    我是照明号的签约作者“初夏兰”

  • 初夏兰
    初夏兰 2026年02月19日

    本文概览:Python基础代码大全:从入门到实战的必备代码合集在Python编程学习之路上,掌握基础代码是构建复杂应用的地基,本文整理了Python开发中最常用的基础代码模块,涵盖变量、...

  • 初夏兰
    用户021901 2026年02月19日

    文章不错《基础数据类型演示》内容很有帮助

联系我们:

邮件:照明号@gmail.com

工作时间:周一至周五,9:30-17:30,节假日休息

关注微信