Python入门基础(二)

Python入门基础(二)

1. 列表和元组

1.1 列表

列表是Python中最常用的数据结构之一,它可以存储多个元素,并且元素可以是不同的数据类型。列表是可变的,这意味着你可以添加、删除或修改列表中的元素。

# 创建一个列表
fruits = ["apple", "banana", "cherry"]

# 访问列表元素
print(fruits[0])  # 输出: apple

# 修改列表元素
fruits[1] = "blueberry"
print(fruits)  # 输出: ['apple', 'blueberry', 'cherry']

# 添加元素
fruits.append("orange")
print(fruits)  # 输出: ['apple', 'blueberry', 'cherry', 'orange']

# 删除元素
fruits.remove("cherry")
print(fruits)  # 输出: ['apple', 'blueberry', 'orange']

1.2 元组

元组与列表类似,但元组是不可变的,这意味着一旦创建了元组,就不能修改它的元素。元组通常用于存储不应更改的数据。

# 创建一个元组
colors = ("red", "green", "blue")

# 访问元组元素
print(colors[1])  # 输出: green

# 尝试修改元组元素(会报错)
# colors[1] = "yellow"  # TypeError: 'tuple' object does not support item assignment

2. 字典

字典是Python中的另一种重要数据结构,它存储键值对。字典中的键必须是唯一的,而值可以是任何数据类型。字典是可变的,允许你添加、删除或修改键值对。

# 创建一个字典
person = {
    "name": "Alice",
    "age": 25,
    "city": "New York"
}

# 访问字典元素
print(person["name"])  # 输出: Alice

# 修改字典元素
person["age"] = 26
print(person)  # 输出: {'name': 'Alice', 'age': 26, 'city': 'New York'}

# 添加新的键值对
person["email"] = "[email protected]"
print(person)  # 输出: {'name': 'Alice', 'age': 26, 'city': 'New York', 'email': '[email protected]'}

# 删除键值对
del person["city"]
print(person)  # 输出: {'name': 'Alice', 'age': 26, 'email': '[email protected]'}

3. 集合

集合是一个无序且不重复的元素集。集合通常用于成员测试和消除重复元素。

# 创建一个集合
numbers = {1, 2, 3, 4, 5}

# 添加元素
numbers.add(6)
print(numbers)  # 输出: {1, 2, 3, 4, 5, 6}

# 删除元素
numbers.remove(3)
print(numbers)  # 输出: {1, 2, 4, 5, 6}

# 集合操作
set1 = {1, 2, 3}
set2 = {3, 4, 5}

# 并集
print(set1 | set2)  # 输出: {1, 2, 3, 4, 5}

# 交集
print(set1 & set2)  # 输出: {3}

# 差集
print(set1 - set2)  # 输出: {1, 2}

4. 文件操作

4.1 读取文件

# 打开文件并读取内容
with open("example.txt", "r") as file:
    content = file.read()
    print(content)

4.2 写入文件

# 打开文件并写入内容
with open("example.txt", "w") as file:
    file.write("Hello, Python!")

5. 异常处理

在编写程序时,可能会遇到各种错误和异常。Python提供了异常处理机制,允许你捕获并处理这些异常。

try:
    # 尝试执行可能出错的代码
    result = 10 / 0
except ZeroDivisionError:
    # 处理异常
    print("不能除以零")
finally:
    # 无论是否发生异常,都会执行的代码
    print("执行完毕")

6. 总结

本文介绍了Python中的列表、元组、字典、集合、文件操作和异常处理。这些内容是Python编程的基础,掌握它们将帮助你编写更复杂和功能强大的程序。在接下来的文章中,我们将继续探讨Python的更多高级特性。

你可能感兴趣的:(Python,Python,入门,基础)