Python学习路径
3/12 章节
25%
Python语法精讲
变量与数据类型
变量的定义
在Python中,变量是用来存储数据的容器,不需要声明类型,直接赋值即可使用。
# 变量赋值示例 name = "Python学习者" age = 18 height = 1.75 is_student = True
基本数据类型
Python支持多种数据类型,常见的包括:
- 整数 (int): 如 10, -5, 0
- 浮点数 (float): 如 3.14, -2.5
- 字符串 (str): 如 "Hello", 'Python'
- 布尔值 (bool): True 或 False
- 列表 (list): 可变序列,如 [1, 2, 3]
- 元组 (tuple): 不可变序列,如 (1, 2, 3)
- 字典 (dict): 键值对集合,如 {"name": "Python", "version": 3.8}
- 集合 (set): 无序不重复元素集合,如 {1, 2, 3}
# 不同数据类型示例 numbers_list = [1, 2, 3, 4, 5] coordinates = (10.5, 20.3) person = { "name": "张三", "age": 25, "city": "北京" } unique_numbers = {1, 2, 3, 3, 4} # 自动去重
类型转换
Python提供了多种内置函数来进行类型转换:
# 类型转换示例 num_str = "123" num_int = int(num_str) # 字符串转整数 num_float = float(num_int) # 整数转浮点数 result_str = str(num_float) # 浮点数转字符串 num_list = [1, 2, 3] num_tuple = tuple(num_list) # 列表转元组 num_set = set(num_list) # 列表转集合
控制流语句
条件语句 (if-elif-else)
条件语句用于根据不同的条件执行不同的代码块。
# 条件语句示例 score = 85 if score >= 90: print("优秀") elif score >= 80: print("良好") elif score >= 60: print("及格") else: print("不及格")
循环语句
Python提供了两种主要的循环结构:for循环和while循环。
for循环
# for循环示例 # 遍历列表 fruits = ["苹果", "香蕉", "橙子"] for fruit in fruits: print(fruit) # 使用range函数 for i in range(1, 6): print(i) # 输出1到5 # 遍历字典 person = { "name": "李四", "age": 30, "city": "上海" } for key, value in person.items(): print(key, ":", value)
while循环
# while循环示例 count = 1 while count <= 5: print("计数: ", count) count += 1 # 递增计数 # 使用break跳出循环 number = 0 while True: number += 1 if number > 10: break # 跳出循环 if number % 2 == 0: continue # 跳过本次循环 print(number)
函数定义与调用
函数的定义
函数是组织好的、可重复使用的代码块,用于执行特定的任务。在Python中,使用def关键字定义函数。
# 基本函数定义 def greet(): # 无参数函数 print("你好,欢迎学习Python!") def greet_person(name): # 带参数函数 print(f"你好,{name}!") def add_numbers(a, b): # 带返回值函数 return a + b
函数的调用
定义函数后,可以通过函数名()来调用函数,传递相应的参数。
# 调用函数 greet() # 调用无参数函数 greet_person("张三") # 调用带参数函数 result = add_numbers(5, 3) # 调用带返回值函数 print(result) # 输出: 8
函数参数类型
Python函数支持多种参数类型:
# 不同类型的参数 def describe_person(name, age=18, city="北京"): # 默认参数 print(f"姓名: {name}, 年龄: {age}, 城市: {city}") def sum_numbers(*args): # 不定长位置参数 return sum(args) def print_info(**kwargs): # 不定长关键字参数 for key, value in kwargs.items(): print(key, ":", value) # 调用示例 describe_person("李四") # 使用默认参数 describe_person("王五", 25, "上海") # 覆盖默认参数 describe_person("赵六", city="广州") # 使用关键字参数 total = sum_numbers(1, 2, 3, 4, 5) print(total) # 输出: 15 print_info(name="小明", age=20, major="计算机科学")
Lambda函数(匿名函数)
Lambda函数是一种小的匿名函数,可以接受任意数量的参数,但只能有一个表达式。
# Lambda函数示例 add = lambda x, y: x + y print(add(5, 3)) # 输出: 8 # 与内置函数一起使用 numbers = [1, 3, 5, 7, 9] doubled = list(map(lambda x: x * 2, numbers)) print(doubled) # 输出: [2, 6, 10, 14, 18] evens = list(filter(lambda x: x % 2 == 0, numbers)) print(evens) # 输出: [](因为没有偶数)
列表与字典
列表(List)操作
列表是Python中最常用的数据结构之一,是一个有序的可变序列。
# 列表基本操作 fruits = ["苹果", "香蕉", "橙子", "葡萄"] # 访问元素 print(fruits[0]) # 输出: 苹果 print(fruits[-1]) # 输出: 葡萄(倒数第一个元素) # 修改元素 fruits[1] = "梨" # 添加元素 fruits.append("草莓") # 添加到末尾 fruits.insert(0, "西瓜") # 插入到指定位置 # 删除元素 fruits.remove("橙子") # 按值删除 removed = fruits.pop(1) # 按索引删除并返回元素 # 列表切片 subset = fruits[1:3] # 获取索引1到2的元素(不包含索引3) # 列表方法 print(fruits.index("苹果")) # 查找元素索引 print(fruits.count("苹果")) # 计算元素出现次数 fruits.sort() # 排序 fruits.reverse() # 反转 # 列表推导式 squares = [x**2 for x in range(1, 6)] print(squares) # 输出: [1, 4, 9, 16, 25]
字典(Dictionary)操作
字典是一种可变的、无序的键值对集合。
# 字典基本操作 person = { "name": "张三", "age": 28, "city": "北京", "skills": ["Python", "Java", "C++"] } # 访问值 print(person["name"]) # 输出: 张三 print(person.get("occupation", "未知")) # 使用get方法,提供默认值 # 修改值 person["age"] = 29 # 添加键值对 person["occupation"] = "工程师" # 删除键值对 del person["city"] removed_value = person.pop("skills") # 删除并返回值 # 字典方法 print(person.keys()) # 获取所有键 print(person.values()) # 获取所有值 print(person.items()) # 获取所有键值对 # 字典推导式 squares_dict = {x: x**2 for x in range(1, 6)} print(squares_dict) # 输出: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} # 合并字典 person.update({"email": "zhangsan@example.com", "phone": "13800138000"})
模块与包
模块(Module)
模块是一个包含Python定义和语句的文件,可以被其他程序导入使用。
# 导入模块 import math # 导入整个模块 from math import pi, sqrt # 导入模块中的特定函数或变量 from math import * # 导入模块中的所有内容(不推荐) import math as m # 给模块起别名 # 使用模块 print(math.pi) # 输出: 3.141592653589793 print(sqrt(16)) # 输出: 4.0 print(m.factorial(5)) # 输出: 120
创建自己的模块
你可以创建自己的Python文件作为模块,然后在其他程序中导入使用。
# 假设有一个名为 mymodule.py 的文件,内容如下: # def greet(name): # return f"你好,{name}!" # # def add(a, b): # return a + b # # PI = 3.14159 # 在另一个文件中导入并使用 import mymodule print(mymodule.greet("Python学习者")) print(mymodule.add(5, 3)) print(mymodule.PI)
包(Package)
包是一种管理Python模块命名空间的方式,它是一个包含多个模块的目录。
# 包的结构示例: # mypackage/ # __init__.py # module1.py # module2.py # 导入包中的模块 from mypackage import module1 from mypackage.module2 import some_function # 使用导入的模块和函数 module1.some_function() some_function()
常用标准库模块
Python提供了丰富的标准库,以下是一些常用的模块:
- os: 提供与操作系统交互的功能
- sys: 提供与Python解释器交互的功能
- datetime: 处理日期和时间
- random: 生成随机数
- json: 处理JSON数据
- re: 正则表达式操作
- math: 数学函数
- collections: 提供额外的数据结构
# 常用标准库示例 import os import datetime import random import json # os模块示例 print(os.getcwd()) # 获取当前工作目录 print(os.listdir()) # 列出当前目录下的文件和文件夹 # datetime模块示例 now = datetime.datetime.now() print(now) # 输出当前日期和时间 print(now.strftime("%Y-%m-%d %H:%M:%S")) # 格式化输出 # random模块示例 print(random.random()) # 生成0-1之间的随机浮点数 print(random.randint(1, 100)) # 生成1-100之间的随机整数 fruits = ["苹果", "香蕉", "橙子"] print(random.choice(fruits)) # 从列表中随机选择一个元素 # json模块示例 data = {"name": "张三", "age": 25} json_str = json.dumps(data, ensure_ascii=False) # 字典转JSON字符串 print(json_str) new_data = json.loads(json_str) # JSON字符串转字典 print(new_data)