当前位置: 首页 > news >正文

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"数字平方字典: {
http://www.dtcms.com/a/461268.html

相关文章:

  • 今天我们开始学习python3编程之python基础
  • jenkins更新了gitlab后出现报错
  • 【OS笔记06】:进程和线程4-进程调度的核心算法
  • 自助建网站工具网站建设与推广
  • 操作系统第二章(下)
  • UNIX下C语言编程与实践49-UNIX 信号量创建与控制:semget 与 semctl 函数的使用
  • 探索Playwright MCP和Claude的协作:智能网页操作新境界
  • Java-144 深入浅出 MongoDB BSON详解:MongoDB核心存储格式与JSON的区别与应用场景
  • 网站的流量是怎么算的双牌网站建设
  • TensorFlow2 Python深度学习 - TensorFlow2框架入门 - 神经网络基础原理
  • Flink State V2 实战从同步到异步的跃迁
  • xml网站地图在线生成工具杭州城西做网站的公司
  • 怎样搭建个人网站wordpress farmer
  • 10.9 lpf|求凸包|正反扫描
  • HashMap 与 Hashtable 深度对比分析
  • 网站开始开发阶段的主要流程辽宁建设工程信息网工程业绩怎么上传
  • 缓存雪崩、击穿、穿透是什么与解决方案
  • 桌面图标又乱了?这个小神器,让你的桌面布局“一键复位”
  • mongodb慢查询优化 速度欻欻滴~
  • 从零开始的C++学习生活 6:string的入门使用
  • 风景网站模板济南seo关键词排名工具
  • UE5 测量 -1,长度测量:P2制作定位球与定位线,P3制作射线检测节点,P4在鼠标位置生成定位球
  • UE5 GAS GameAbility源码解析 EndAbility
  • 潍坊网站建设 潍坊做网站外贸网站服务器推荐
  • 第7章 n步时序差分(3) n 步离轨策略学习
  • 【Leetcode hot 100】35.搜索插入位置
  • Django ORM 字段查询表达式(Field lookup expressions)
  • 设计模式--组合模式:统一处理树形结构的优雅设计
  • 推荐算法学习笔记(十九)阿里SIM 模型
  • 高级网站开发工程师证书现代网站建设