Python 基础语法和核心概念
以下是 Python 基础语法和核心概念的演练内容,涵盖变量、数据类型、控制结构、函数等关键知识点,适合新手巩固基础:
1. 变量与数据类型
(1) 基本类型操作
# 整数与浮点数
a = 10
b = 3.14
print(a + b) # 13.14 (自动类型转换)
# 字符串处理
name = "Alice"
print(name.upper()) # "ALICE"
print(f"Hello, {name}!") # 格式化输出
# 布尔类型
is_valid = True
print(not is_valid) # False
(2) 类型转换
num_str = "123"
num_int = int(num_str) # 字符串转整数
num_float = float("45.67") # 转浮点数
print(str(100) + "元") # "100元"
2. 列表(List)操作
(1) 增删改查
fruits = ["apple", "banana"]
fruits.append("orange") # 添加元素
fruits.insert(1, "grape") # 插入到索引1
fruits.remove("banana") # 删除元素
print(fruits[0]) # "apple"
print(fruits[-1]) # "orange" (倒数第一个)
(2) 切片与遍历
numbers = [1, 2, 3, 4, 5]
print(numbers[1:4]) # [2, 3, 4]
print(numbers[::2]) # [1, 3, 5] (步长2)
# 列表推导式
squares = [x**2 for x in numbers if x % 2 == 0]
print(squares) # [4, 16]
3. 字典(Dict)操作
(1) 基本使用
student = {"name": "Bob", "age": 20}
student["grade"] = 90 # 添加键值对
print(student.get("age", "未知")) # 20 (避免KeyError)
# 遍历字典
for key, value in student.items():
print(f"{key}: {value}")
(2) 字典合并
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
merged = {**dict1, **dict2} # {'a':1, 'b':3, 'c':4}
4. 条件与循环
(1) 条件判断
score = 85
if score >= 90:
print("优秀")
elif 60 <= score < 90:
print("及格")
else:
print("不及格")
(2) 循环控制
# for循环
for i in range(5): # 0到4
if i == 3:
continue # 跳过3
print(i)
# while循环
count = 0
while count < 3:
print("Hello")
count += 1
5. 函数定义与使用
(1) 基本函数
def add(x, y=0): # 默认参数
return x + y
print(add(3, 5)) # 8
print(add(3)) # 3
(2) Lambda表达式
multiply = lambda a, b: a * b
print(multiply(4, 5)) # 20
# 结合列表排序
students = [("Bob", 20), ("Alice", 18)]
students.sort(key=lambda x: x[1]) # 按年龄排序
6. 文件操作
(1) 读写文件
# 写入文件
with open("test.txt", "w") as f:
f.write("Hello, Python!\nSecond line")
# 读取文件
with open("test.txt", "r") as f:
content = f.readlines() # ['Hello, Python!\n', 'Second line']
(2) CSV文件处理
import csv
# 写入CSV
with open("data.csv", "w", newline='') as f:
writer = csv.writer(f)
writer.writerow(["Name", "Age"])
writer.writerow(["Alice", 25])
# 读取CSV
with open("data.csv", "r") as f:
reader = csv.reader(f)
for row in reader:
print(row) # ["Name", "Age"], ["Alice", 25]
7. 异常处理
try:
num = int(input("请输入数字: "))
result = 10 / num
except ValueError:
print("输入的不是数字!")
except ZeroDivisionError:
print("不能除以零!")
else:
print(f"结果是: {result}")
finally:
print("程序结束")
8. 综合练习
(1) 计算斐波那契数列
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
print(a, end=' ')
a, b = b, a + b
fibonacci(10) # 0 1 1 2 3 5 8 13 21 34
(2) 统计文本词频
text = "apple banana apple orange banana apple"
words = text.split()
word_count = {}
for word in words:
word_count[word] = word_count.get(word, 0) + 1
print(word_count) # {'apple':3, 'banana':2, 'orange':1}
关键知识点总结
| 主题 | 核心要点 |
|---|---|
| 数据类型 | 列表切片、字典操作、类型转换 |
| 控制结构 | 条件判断、循环控制(break/continue) |
| 函数 | 参数传递、lambda表达式 |
| 文件处理 | 上下文管理器(with)、CSV读写 |
| 异常处理 | try-except-finally 结构 |
通过以上练习,可以快速掌握 Python 基础语法,建议配合实际项目(如简单计算器、待办事项管理)巩固技能!
前事不忘,后事之师
浙公网安备 33010602011771号