Python作为一门易学易用的编程语言,受到了众多初学者的喜爱。本文介绍30个Python基础知识点和实用技巧,帮助你快速掌握Python编程的核心概念。
一、基本数据类型
1. 数字与运算
# 整数和浮点数
x = 10 # 整数
y = 3.14 # 浮点数
# 基本运算
print(x + y) # 加法: 13.14
print(x - y) # 减法: 6.86
print(x * y) # 乘法: 31.4
print(x / y) # 除法: 3.184713375796178
print(x // y) # 整除: 3.0
print(x % y) # 取余: 0.5800000000000001
print(x ** 2) # 幂运算: 100
2. 字符串基础
# 创建字符串
name = "Python编程"
message = '学习Python很有趣'
# 字符串连接
greeting = "你好," + name + "!"
print(greeting) # 你好,Python编程!
# 字符串格式化
age = 30
info = f"{name}已经{age}岁了"
print(info) # Python编程已经30岁了
3. 布尔值与比较
# 布尔值
is_valid = True
is_complete = False
# 比较运算符
x = 10
y = 20
print(x > y) # False
print(x < y) # True
print(x == y) # False
print(x != y) # True
print(x >= 10) # True
4. 类型转换
# 字符串转数字
num_str = "123"
num_int = int(num_str) # 123 (整数)
num_float = float(num_str) # 123.0 (浮点数)
# 数字转字符串
price = 19.99
price_str = str(price) # "19.99"
# 转换为布尔值
print(bool(0)) # False
print(bool(1)) # True
print(bool("")) # False
print(bool("text")) # True
5. 变量与常量
# 变量命名
user_name = "admin" # 推荐使用下划线命名法
count = 0
# 多变量赋值
x, y, z = 1, 2, 3
print(x, y, z) # 1 2 3
# 交换变量值
a, b = 5, 10
a, b = b, a
print(a, b) # 10 5
# 常量约定(Python没有真正的常量)
MAX_USERS = 100 # 全大写表示常量,不应被修改
二、数据结构
6. 列表基础
# 创建列表
fruits = ["苹果", "香蕉", "橙子"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "文本", True, 3.14]
# 访问元素
first_fruit = fruits[0] # "苹果"
last_number = numbers[-1] # 5
# 修改元素
fruits[1] = "梨"
print(fruits) # ["苹果", "梨", "橙子"]
# 添加和删除元素
fruits.append("葡萄") # 添加到末尾
fruits.insert(1, "香蕉") # 在指定位置插入
removed = fruits.pop(0) # 移除并返回指定位置元素
fruits.remove("橙子") # 移除特定值的元素
7. 列表切片
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# 基本切片 [开始:结束:步长]
first_three = numbers[0:3] # [0, 1, 2]
middle = numbers[3:7] # [3, 4, 5, 6]
last_three = numbers[-3:] # [7, 8, 9]
every_second = numbers[::2] # [0, 2, 4, 6, 8]
reversed_list = numbers[::-1] # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
8. 字典使用
# 创建字典
user = {"name": "张三","age": 25,"is_active": True
}
# 访问值
print(user["name"]) # 张三
# 使用get安全访问(避免键不存在时出错)
email = user.get("email", "未设置") # "未设置"
# 添加和修改
user["email"] = "zhangsan@example.com"
user["age"] = 26
# 删除键值对
del user["is_active"]
9. 元组
# 创建元组(不可修改的列表)
coordinates = (10, 20)
rgb = (255, 0, 0)# 访问元素
x = coordinates[0] # 10
y = coordinates[1] # 20# 元组解包
r, g, b = rgb
print(r, g, b) # 255 0 0# 单元素元组需要逗号
single_item = (42,) # 这是一个元组
not_tuple = (42) # 这是一个整数
10. 集合
# 创建集合(无序且元素唯一)
fruits = {"苹果", "香蕉", "橙子"}
numbers = {1, 2, 3, 3, 4, 4, 5} # 重复元素会被删除
print(numbers) # {1, 2, 3, 4, 5}# 添加和删除元素
fruits.add("葡萄")
fruits.remove("香蕉") # 如果元素不存在会报错
fruits.discard("梨") # 如果元素不存在不会报错# 集合操作
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
print(set1 & set2) # 交集: {3, 4}
print(set1 | set2) # 并集: {1, 2, 3, 4, 5, 6}
print(set1 - set2) # 差集: {1, 2}
三、控制流
11. 条件语句
# if语句
age = 18
if age < 18:print("未成年")
elif age == 18:print("刚好成年")
else:print("成年人")# 条件表达式(三元运算符)
status = "成年" if age >= 18 else "未成年"
print(status) # "成年"# 逻辑运算符
if age >= 18 and age <= 65:print("工作年龄")# 真值判断
name = ""
if name: # 空字符串视为Falseprint("名字已设置")
12. 循环
# for循环遍历列表
fruits = ["苹果", "香蕉", "橙子"]
for fruit in fruits:print(f"我喜欢吃{fruit}")# for循环遍历字典
user = {"name": "张三", "age": 25}
for key in user:print(f"{key}: {user[key]}")# for循环更多方式
for key, value in user.items():print(f"{key}: {value}")# range函数生成数字序列
for i in range(5): # 0到4print(i)# while循环
count = 0
while count < 5:print(count)count += 1
13. 循环控制
# break语句提前结束循环
for i in range(10):if i == 5:breakprint(i) # 打印0到4# continue语句跳过当前迭代
for i in range(10):if i % 2 == 0: # 如果是偶数continueprint(i) # 只打印奇数# else子句(循环正常完成时执行)
for i in range(3):print(i)
else:print("循环正常完成")
14. 列表推导式
# 基本列表推导式
numbers = [1, 2, 3, 4, 5]
squares = [n**2 for n in numbers] # [1, 4, 9, 16, 25]# 带条件的列表推导式
even_squares = [n**2 for n in numbers if n % 2 == 0] # [4, 16]# 嵌套列表转为平面列表
matrix = [[1, 2], [3, 4], [5, 6]]
flattened = [num for row in matrix for num in row] # [1, 2, 3, 4, 5, 6]
15. 字典推导式
# 创建字典
names = ["apple", "banana", "cherry"]
fruit_dict = {name: len(name) for name in names}
# {"apple": 5, "banana": 6, "cherry": 6}# 条件字典推导式
numbers = [1, 2, 3, 4, 5]
square_dict = {n: n**2 for n in numbers if n % 2 == 0}
# {2: 4, 4: 16}
四、函数
16. 函数定义与调用
# 定义简单函数
def greet(name):"""向指定的人问好""" # 文档字符串return f"你好,{name}!"# 调用函数
message = greet("张三")
print(message) # 你好,张三!# 多返回值
def get_dimensions(width, height):area = width * heightperimeter = 2 * (width + height)return area, perimeterarea, perimeter = get_dimensions(5, 3)
print(f"面积: {area}, 周长: {perimeter}") # 面积: 15, 周长: 16
17. 函数参数
# 位置参数
def greet(first_name, last_name):return f"你好,{first_name} {last_name}!"print(greet("张", "三")) # 你好,张 三!# 关键字参数
print(greet(last_name="三", first_name="张")) # 你好,张 三!# 默认参数值
def greet_with_title(name, title="先生"):return f"你好,{name}{title}!"print(greet_with_title("张三")) # 你好,张三先生!
print(greet_with_title("李四", "女士")) # 你好,李四女士!
18. 可变参数
# *args(收集位置参数)
def sum_numbers(*numbers):return sum(numbers)print(sum_numbers(1, 2, 3, 4)) # 10# **kwargs(收集关键字参数)
def create_profile(**user_info):return user_infoprofile = create_profile(name="张三", age=25, city="北京")
print(profile) # {'name': '张三', 'age': 25, 'city': '北京'}
19. 作用域
# 局部作用域和全局作用域
x = 10 # 全局变量def test_scope():y = 20 # 局部变量print(x) # 可以访问全局变量print(y)test_scope()
# print(y) # 错误!不能访问局部变量# 使用global关键字
def modify_global():global xx = 50 # 修改全局变量modify_global()
print(x) # 50
20. 匿名函数
# lambda函数(一行匿名函数)
add = lambda a, b: a + b
print(add(5, 3)) # 8# 结合函数式编程
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared) # [1, 4, 9, 16, 25]# 使用lambda排序
users = [{"name": "张三", "age": 30},{"name": "李四", "age": 25},{"name": "王五", "age": 40}
]
sorted_users = sorted(users, key=lambda user: user["age"])
print([user["name"] for user in sorted_users]) # ['李四', '张三', '王五']
五、文件处理
21. 读写文本文件
# 写入文件
with open("example.txt", "w", encoding="utf-8") as file:file.write("第一行内容\n")file.write("第二行内容\n")# 读取整个文件
with open("example.txt", "r", encoding="utf-8") as file:content = file.read()print(content)# 逐行读取
with open("example.txt", "r", encoding="utf-8") as file:for line in file:print(line.strip()) # strip()移除行尾的换行符
22. 文件路径处理
from pathlib import Path# 创建路径对象
path = Path("data") / "users.txt"
print(path) # data/users.txt (Windows上是data\users.txt)# 检查路径
data_dir = Path("data")
if not data_dir.exists():data_dir.mkdir()print("data目录已创建")# 获取文件信息
if path.exists():print(f"文件大小: {path.stat().st_size} 字节")print(f"修改时间: {path.stat().st_mtime}")
23. CSV文件处理
import csv# 写入CSV文件
with open("users.csv", "w", newline="", encoding="utf-8") as file:writer = csv.writer(file)writer.writerow(["姓名", "年龄", "城市"]) # 写入标题行writer.writerow(["张三", 25, "北京"])writer.writerow(["李四", 30, "上海"])# 读取CSV文件
with open("users.csv", "r", encoding="utf-8") as file:reader = csv.reader(file)for row in reader:print(row) # 每行是一个列表# 使用DictReader/DictWriter处理CSV
with open("users.csv", "r", encoding="utf-8") as file:reader = csv.DictReader(file)for row in reader:print(f"{row['姓名']}来自{row['城市']}")
六、错误和异常处理
24. 基本异常处理
# try-except语句
try:number = int(input("请输入一个数字: "))result = 10 / numberprint(f"结果是: {result}")
except ValueError:print("输入不是有效的数字")
except ZeroDivisionError:print("不能除以零")
except:print("发生了其他错误")
finally:print("无论是否发生异常,都会执行这里的代码")
25. 抛出异常
# 使用raise抛出异常
def validate_age(age):if age < 0:raise ValueError("年龄不能为负数")if age > 150:raise ValueError("年龄值不现实")return age# 处理自定义异常
try:user_age = validate_age(-5)
except ValueError as error:print(f"错误: {error}")
七、模块和包
26. 导入模块
# 导入标准库模块
import math
print(math.sqrt(16)) # 4.0# 导入特定函数
from random import randint
print(randint(1, 10)) # 1到10之间的随机整数# 使用别名
import datetime as dt
now = dt.datetime.now()
print(now)# 导入多个函数
from math import sin, cos, tan
27. 创建自定义模块
# 假设我们有文件 mymodule.py
"""
这是一个示例模块
"""
def greet(name):return f"你好,{name}!"PI = 3.14159# 在另一个文件中使用
import mymodule
print(mymodule.greet("张三"))
print(mymodule.PI)
28. 常用标准库
# 日期时间处理
from datetime import datetime, timedelta
now = datetime.now()
yesterday = now - timedelta(days=1)
print(now.strftime("%Y-%m-%d %H:%M:%S"))# 随机数
import random
print(random.choice(["苹果", "香蕉", "橙子"])) # 随机选择一个元素
print(random.sample(range(1, 50), 6)) # 随机选择6个不重复的数字# 系统操作
import os
current_dir = os.getcwd() # 获取当前工作目录
files = os.listdir(".") # 列出当前目录的文件
八、面向对象编程基础
29. 类和对象
# 定义类
class Person:def __init__(self, name, age):self.name = nameself.age = agedef greet(self):return f"你好,我是{self.name},今年{self.age}岁"def have_birthday(self):self.age += 1return f"{self.name}现在{self.age}岁了"# 创建对象
person1 = Person("张三", 25)
person2 = Person("李四", 30)# 调用方法
print(person1.greet())
print(person2.have_birthday())
30. 继承
# 基类
class Animal:def __init__(self, name):self.name = namedef make_sound(self):return "某种声音"# 子类
class Dog(Animal):def make_sound(self):return "汪汪!"class Cat(Animal):def make_sound(self):return "喵喵~"# 使用继承
dog = Dog("旺财")
cat = Cat("咪咪")
print(f"{dog.name}说:{dog.make_sound()}")
print(f"{cat.name}说:{cat.make_sound()}")# 检查类型
print(isinstance(dog, Dog)) # True
print(isinstance(dog, Animal)) # True
print(isinstance(dog, Cat)) # False
以上30个基础知识点涵盖了Python的核心概念,包括数据类型、控制流、函数、文件处理、错误处理、模块使用和面向对象编程。掌握这些基础知识,将使你能够编写出功能完善的Python程序。
作为初学者,建议你先专注于理解这些基础概念,然后通过实际项目来巩固学习成果。Python的学习曲线相对平缓,只要持续练习,你很快就能熟练掌握这门语言。
祝你学习愉快!