Python从入门到实战:全面学习指南2
第一部分:Python基础入门
1.1 Python简介与环境搭建
Python是一种高级、解释型的编程语言,以简洁易读的语法著称。它由Guido van Rossum于1991年创建,如今已成为最受欢迎的编程语言之一。
安装Python
python
# 检查Python是否安装成功 import sys print("Python版本:", sys.version) print("安装路径:", sys.executable)
开发环境配置
推荐使用VS Code作为开发环境,安装Python扩展后即可开始编程。
python
# 第一个Python程序 print("Hello, World!") print("欢迎学习Python编程!")# 简单的数学运算 a = 10 b = 5 print(f"{a} + {b} = {a + b}") print(f"{a} - {b} = {a - b}") print(f"{a} × {b} = {a * b}") print(f"{a} ÷ {b} = {a / b}")
1.2 变量与数据类型
python
# 变量定义与使用 name = "张三" age = 25 height = 1.75 is_student = Trueprint(f"姓名: {name}") print(f"年龄: {age}岁") print(f"身高: {height}米") print(f"是否学生: {is_student}")# 数据类型检查 print(f"name的类型: {type(name)}") print(f"age的类型: {type(age)}") print(f"height的类型: {type(height)}") print(f"is_student的类型: {type(is_student)}")# 数据类型转换 number_str = "123" number_int = int(number_str) number_float = float(number_str) print(f"字符串转整数: {number_int}") print(f"字符串转浮点数: {number_float}")
1.3 基本运算符
python
# 算术运算符 x = 15 y = 4print(f"x + y = {x + y}") # 加法 print(f"x - y = {x - y}") # 减法 print(f"x * y = {x * y}") # 乘法 print(f"x / y = {x / y}") # 除法 print(f"x // y = {x // y}") # 整除 print(f"x % y = {x % y}") # 取模 print(f"x ** y = {x ** y}") # 幂运算# 比较运算符 print(f"x > y: {x > y}") print(f"x < y: {x < y}") print(f"x == y: {x == y}") print(f"x != y: {x != y}")# 逻辑运算符 a = True b = False print(f"a and b: {a and b}") print(f"a or b: {a or b}") print(f"not a: {not a}")
1.4 控制流程
条件语句
python
# if-elif-else语句 def check_grade(score):if score >= 90:return "优秀"elif score >= 80:return "良好"elif score >= 70:return "中等"elif score >= 60:return "及格"else:return "不及格"# 测试成绩判断 scores = [95, 85, 75, 65, 55] for score in scores:grade = check_grade(score)print(f"分数 {score}: {grade}")# 嵌套条件语句 def can_drive(age, has_license):if age >= 18:if has_license:return "可以驾驶"else:return "年龄达标但无驾照"else:return "年龄未达标"
循环语句
python
# for循环示例 print("=== for循环示例 ===")# 遍历列表 fruits = ["苹果", "香蕉", "橙子", "葡萄"] for fruit in fruits:print(f"我喜欢吃{fruit}")# 使用range函数 print("\n数字1-10:") for i in range(1, 11):print(i, end=" ")print("\n\n偶数0-20:") for i in range(0, 21, 2):print(i, end=" ")# while循环示例 print("\n\n=== while循环示例 ===")# 计数器循环 count = 1 while count <= 5:print(f"计数: {count}")count += 1# 用户输入验证 def get_positive_number():while True:try:num = float(input("请输入一个正数: "))if num > 0:return numelse:print("请输入正数!")except ValueError:print("请输入有效的数字!")# 测试输入函数 # positive_num = get_positive_number() # print(f"你输入的正数是: {positive_num}")
1.5 函数定义与使用
python
# 函数定义示例 def calculate_bmi(weight, height):"""计算BMI指数Args:weight: 体重(kg)height: 身高(m)Returns:BMI值和建议"""bmi = weight / (height ** 2)if bmi < 18.5:category = "偏瘦"elif bmi < 24:category = "正常"elif bmi < 28:category = "超重"else:category = "肥胖"return bmi, category# 使用函数 people = [{"name": "张三", "weight": 70, "height": 1.75},{"name": "李四", "weight": 55, "height": 1.65},{"name": "王五", "weight": 80, "height": 1.70} ]for person in people:bmi, category = calculate_bmi(person["weight"], person["height"])print(f"{person['name']}: BMI={bmi:.2f}, 体重{category}")# 默认参数函数 def greet(name, greeting="你好", punctuation="!"):"""带默认参数的问候函数"""return f"{greeting},{name}{punctuation}"print(greet("小明")) print(greet("小红", "Hello")) print(greet("小王", "Hi", "!!!"))
第二部分:Python数据结构
2.1 列表(List)
python
# 列表操作示例 print("=== 列表操作 ===")# 创建列表 numbers = [1, 2, 3, 4, 5] fruits = ["苹果", "香蕉", "橙子"] mixed = [1, "hello", 3.14, True]print(f"数字列表: {numbers}") print(f"水果列表: {fruits}") print(f"混合列表: {mixed}")# 列表索引和切片 print(f"\n第一个水果: {fruits[0]}") print(f"最后一个水果: {fruits[-1]}") print(f"前两个水果: {fruits[0:2]}") print(f"从第二个开始的所有水果: {fruits[1:]}")# 列表方法 fruits.append("葡萄") # 添加元素 print(f"添加后: {fruits}")fruits.insert(1, "梨") # 插入元素 print(f"插入后: {fruits}")fruits.remove("香蕉") # 删除元素 print(f"删除后: {fruits}")popped_fruit = fruits.pop() # 弹出最后一个元素 print(f"弹出的水果: {popped_fruit}") print(f"弹出后: {fruits}")# 列表推导式 squares = [x**2 for x in range(1, 6)] even_numbers = [x for x in range(1, 11) if x % 2 == 0] print(f"平方数: {squares}") print(f"偶数: {even_numbers}")
2.2 元组(Tuple)
python
# 元组示例 print("=== 元组操作 ===")# 创建元组 coordinates = (10, 20) colors = ("红色", "绿色", "蓝色") single_element = (42,) # 注意逗号print(f"坐标: {coordinates}") print(f"颜色: {colors}")# 元组解包 x, y = coordinates print(f"x坐标: {x}, y坐标: {y}")# 元组不可变性演示 try:coordinates[0] = 15 # 这会报错 except TypeError as e:print(f"错误: {e}")# 元组与列表转换 numbers_list = [1, 2, 3, 4, 5] numbers_tuple = tuple(numbers_list) print(f"列表转元组: {numbers_tuple}")new_list = list(numbers_tuple) print(f"元组转列表: {new_list}")
2.3 字典(Dictionary)
python
# 字典操作示例 print("=== 字典操作 ===")# 创建字典 student = {"name": "李小明","age": 20,"major": "计算机科学","grades": {"数学": 90, "英语": 85, "编程": 95} }print(f"学生信息: {student}")# 访问字典值 print(f"姓名: {student['name']}") print(f"年龄: {student.get('age')}") print(f"数学成绩: {student['grades']['数学']}")# 添加和修改元素 student["email"] = "lixiaoming@email.com" student["age"] = 21 print(f"更新后: {student}")# 字典方法 print(f"所有键: {list(student.keys())}") print(f"所有值: {list(student.values())}") print(f"所有键值对: {list(student.items())}")# 字典推导式 numbers = [1, 2, 3, 4, 5] squares_dict = {x: x**2 for x in numbers} print(f"数字平方字典: {