Python 快速入门
什么是 Python?
Python 是一种简洁、易学、功能强大的编程语言。它具有简单的语法、丰富的库和强大的社区支持,是初学者和专业开发者的理想选择。
Python 的特点
- 简洁易学 - 代码可读性强,学习曲线平缓
- 功能强大 - 支持多种编程范式(面向对象、函数式、过程式)
- 跨平台 - 可在 Windows、Linux、Mac 等多个平台运行
- 丰富的库 - 拥有海量第三方库,涵盖各个领域
- 社区活跃 - 拥有全球最大的编程社区之一
- 开源免费 - 完全开源,免费使用和修改
Python 在 LeBot 中的应用
在 LeBot 开发中,Python 主要用于:
- 编写机器人控制脚本
- 数据处理和分析
- 机器学习模型开发
- 图像处理和计算机视觉
- 网络通信和远程控制
- 快速原型开发
环境搭建
安装 Python
Linux(Debian/Ubuntu)
bash
# 查看已安装的 Python 版本
python3 --version
# 如果未安装,进行安装
sudo apt update
sudo apt install python3 python3-pip python3-venv
# 验证安装
python3 --version
pip3 --versionWindows
- 从 python.org 下载安装程序
- 运行安装程序,勾选 "Add Python to PATH"
- 完成安装
macOS
bash
# 使用 Homebrew
brew install python3
# 或下载安装程序设置虚拟环境
虚拟环境可以隔离项目依赖,避免版本冲突。
bash
# 创建虚拟环境
python3 -m venv lebot_env
# 激活虚拟环境
# Linux/Mac
source lebot_env/bin/activate
# Windows
lebot_env\Scripts\activate
# 退出虚拟环境
deactivate安装常用库
bash
# 在虚拟环境中安装
pip install numpy pandas matplotlib scipy scikit-learn opencv-python
# 查看已安装的包
pip list
# 导出依赖列表
pip freeze > requirements.txt
# 从依赖列表安装
pip install -r requirements.txtPython 基础语法
变量和数据类型
Python 是动态类型语言,变量类型在运行时确定。
python
# 整数
age = 18
print(type(age)) # <class 'int'>
# 浮点数
height = 1.75
print(type(height)) # <class 'float'>
# 字符串
name = "LeBot"
print(type(name)) # <class 'str'>
# 布尔值
is_active = True
print(type(is_active)) # <class 'bool'>
# 列表
colors = ["red", "green", "blue"]
print(type(colors)) # <class 'list'>
# 字典
robot = {"name": "LeBot", "year": 2024}
print(type(robot)) # <class 'dict'>
# 元组
coordinates = (10, 20, 30)
print(type(coordinates)) # <class 'tuple'>字符串操作
python
# 字符串定义
s1 = "Hello"
s2 = 'World'
s3 = """多行
字符串"""
# 字符串连接
greeting = s1 + " " + s2 # "Hello World"
# 字符串格式化
temperature = 45.5
message = f"温度是 {temperature}°C" # f-string(推荐)
# 或使用 format 方法
message = "温度是 {}°C".format(temperature)
# 字符串方法
text = "lebot is awesome"
print(text.upper()) # LEBOT IS AWESOME
print(text.capitalize()) # Lebot is awesome
print(text.replace("lebot", "robot")) # robot is awesome
print(text.split(" ")) # ['lebot', 'is', 'awesome']
# 字符串切片
s = "Python"
print(s[0]) # P
print(s[1:4]) # yth
print(s[-1]) # n
print(s[::-1]) # nohtyP列表和元组
python
# 创建列表
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]
# 列表操作
numbers.append(6) # [1, 2, 3, 4, 5, 6]
numbers.extend([7, 8]) # [1, 2, 3, 4, 5, 6, 7, 8]
numbers.insert(0, 0) # 在位置 0 插入
numbers.remove(3) # 删除值为 3 的元素
numbers.pop() # 删除最后一个元素
numbers.pop(0) # 删除第一个元素
# 列表索引和切片
print(numbers[0]) # 第一个元素
print(numbers[-1]) # 最后一个元素
print(numbers[1:4]) # 切片
# 列表长度
print(len(numbers))
# 元组(不可修改)
point = (10, 20)
print(point[0]) # 10
# point[0] = 15 # 会报错!
# 列表推导式(强大的列表创建方式)
squares = [x**2 for x in range(1, 6)] # [1, 4, 9, 16, 25]
even_numbers = [x for x in range(10) if x % 2 == 0] # [0, 2, 4, 6, 8]字典
python
# 创建字典
robot_config = {
"name": "LeBot",
"year": 2024,
"type": "wheeled-legged",
"sensors": ["IMU", "Camera", "Lidar"]
}
# 访问字典值
print(robot_config["name"]) # LeBot
print(robot_config.get("age", "Unknown")) # Unknown(使用默认值)
# 修改和添加
robot_config["battery"] = 85
robot_config["name"] = "LeBot v2"
# 删除
del robot_config["battery"]
robot_config.pop("year")
# 遍历字典
for key, value in robot_config.items():
print(f"{key}: {value}")
# 字典的 keys 和 values
print(robot_config.keys())
print(robot_config.values())
# 字典推导式
squares_dict = {x: x**2 for x in range(1, 6)} # {1: 1, 2: 4, 3: 9, ...}条件语句
python
# if-else 基本结构
age = 18
if age < 13:
print("儿童")
elif age < 18:
print("青少年")
else:
print("成年人")
# 三元表达式
status = "adult" if age >= 18 else "minor"
# 逻辑运算符
temperature = 45
humidity = 65
if temperature > 40 and humidity > 60:
print("环境恶劣!")
if temperature < 0 or humidity > 80:
print("需要调节环境")
# in 和 not in
colors = ["red", "green", "blue"]
if "red" in colors:
print("红色已在列表中")
if "yellow" not in colors:
print("黄色不在列表中")循环
python
# for 循环
for i in range(5):
print(i) # 0, 1, 2, 3, 4
# 遍历列表
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# 遍历字典
robot = {"name": "LeBot", "speed": 2.5}
for key, value in robot.items():
print(f"{key}: {value}")
# enumerate - 获取索引和值
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# while 循环
count = 0
while count < 5:
print(count)
count += 1
# 循环控制
for i in range(10):
if i == 3:
continue # 跳过当前迭代
if i == 7:
break # 退出循环
print(i)
# 循环中的 else 子句
for i in range(5):
print(i)
else:
print("循环完成!")函数
python
# 函数定义
def greet(name):
"""问候函数"""
return f"你好,{name}!"
print(greet("LeBot")) # 你好,LeBot!
# 函数参数
def move_robot(speed, direction="forward"):
"""移动机器人"""
print(f"机器人以 {speed} m/s 向 {direction} 移动")
move_robot(1.0) # 使用默认参数
move_robot(2.0, "backward") # 提供所有参数
# 可变长参数
def sum_numbers(*args):
"""求和任意数量的数字"""
total = 0
for num in args:
total += num
return total
print(sum_numbers(1, 2, 3, 4, 5)) # 15
# 关键字参数
def configure_robot(**kwargs):
"""配置机器人"""
for key, value in kwargs.items():
print(f"配置 {key} = {value}")
configure_robot(speed=2.0, battery=85, mode="autonomous")
# 函数返回多个值
def get_position():
"""获取机器人位置"""
x, y, z = 1.5, 2.0, 0.5
return x, y, z
x, y, z = get_position()
print(f"位置: ({x}, {y}, {z})")
# 默认参数注意事项
# ⚠️ 不要使用可变对象作为默认参数
# def bad_function(items=[]): # 危险!
# items.append(1)
# return items
# 正确做法
def good_function(items=None):
if items is None:
items = []
items.append(1)
return items文件操作
python
# 打开和读取文件
with open("data.txt", "r") as file:
content = file.read() # 读取整个文件
# 或逐行读取
# for line in file:
# print(line.strip())
# 写入文件
with open("output.txt", "w") as file:
file.write("Hello, LeBot!\n")
file.write("This is line 2\n")
# 追加到文件
with open("log.txt", "a") as file:
file.write("新的日志信息\n")
# JSON 操作
import json
# 保存为 JSON
data = {
"robot_name": "LeBot",
"version": 1.0,
"sensors": ["IMU", "Camera"]
}
with open("config.json", "w") as f:
json.dump(data, f, indent=2)
# 读取 JSON
with open("config.json", "r") as f:
loaded_data = json.load(f)
print(loaded_data["robot_name"])
# CSV 操作
import csv
# 写入 CSV
with open("sensor_data.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["时间", "温度", "湿度"])
writer.writerow([1, 45.5, 65])
writer.writerow([2, 46.0, 64])
# 读取 CSV
with open("sensor_data.csv", "r") as f:
reader = csv.reader(f)
for row in reader:
print(row)面向对象编程
python
# 类定义
class Robot:
"""机器人类"""
# 类变量(所有实例共享)
species = "Legged Wheeled Robot"
# 构造函数
def __init__(self, name, speed):
# 实例变量
self.name = name
self.speed = speed
self.is_moving = False
# 实例方法
def move_forward(self):
"""向前移动"""
self.is_moving = True
print(f"{self.name} 以 {self.speed} m/s 向前移动")
def stop(self):
"""停止"""
self.is_moving = False
print(f"{self.name} 已停止")
def __str__(self):
"""字符串表示"""
return f"{self.name} (速度: {self.speed} m/s)"
# 创建对象
robot1 = Robot("LeBot-1", 2.0)
robot2 = Robot("LeBot-2", 1.5)
# 调用方法
robot1.move_forward() # LeBot-1 以 2.0 m/s 向前移动
robot1.stop() # LeBot-1 已停止
# 访问属性
print(robot1.name) # LeBot-1
print(Robot.species) # Legged Wheeled Robot
# 继承
class AutonomousRobot(Robot):
"""自主机器人"""
def __init__(self, name, speed, ai_level):
super().__init__(name, speed)
self.ai_level = ai_level
def navigate(self, destination):
"""自主导航"""
print(f"{self.name} 正在用 AI 等级 {self.ai_level} 导航到 {destination}")
autonomous = AutonomousRobot("LeBot-AI", 2.5, "advanced")
autonomous.navigate("目标地点")
# 多态
def command_robot(robot):
"""命令机器人"""
robot.move_forward()
robot.stop()
command_robot(robot1)
command_robot(autonomous)异常处理
python
# 基本异常处理
try:
result = 10 / 0
except ZeroDivisionError:
print("错误:不能除以零!")
# 多个异常
try:
numbers = [1, 2, 3]
print(numbers[10])
except IndexError:
print("索引超出范围")
except KeyError:
print("键不存在")
# 捕获所有异常(不推荐)
try:
# 某些操作
pass
except Exception as e:
print(f"发生错误:{e}")
# finally 子句(无论如何都执行)
try:
file = open("data.txt", "r")
# 读取文件
except FileNotFoundError:
print("文件不存在")
finally:
# 总是执行这里
if 'file' in locals():
file.close()
# 自定义异常
class RobotError(Exception):
"""机器人错误"""
pass
def check_battery(level):
if level < 10:
raise RobotError("电池电量过低!")
print(f"电池电量良好:{level}%")
try:
check_battery(5)
except RobotError as e:
print(f"错误:{e}")模块和包
python
# 导入模块
import math
print(math.pi)
print(math.sqrt(16))
# 导入特定函数
from math import sin, cos, pi
angle = pi / 4
print(sin(angle))
# 给导入的内容取别名
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
# 导入包中的模块
from collections import Counter
data = [1, 2, 2, 3, 3, 3]
counter = Counter(data)
print(counter) # Counter({3: 3, 2: 2, 1: 1})
# 查看模块中的所有可用项
import os
# print(dir(os))
# 获取模块的帮助文档
# help(math)常用内置函数
python
# 数据类型转换
x = int("123") # 123
y = float("3.14") # 3.14
s = str(42) # "42"
b = bool(1) # True
# 数学函数
print(abs(-5)) # 5
print(max([1, 5, 3])) # 5
print(min([1, 5, 3])) # 1
print(sum([1, 2, 3, 4, 5])) # 15
print(round(3.7)) # 4
print(pow(2, 3)) # 8
# 序列函数
print(len([1, 2, 3])) # 3
print(sorted([3, 1, 2])) # [1, 2, 3]
print(reversed([1, 2, 3])) # <list_reverseiterator>
print(list(reversed([1, 2, 3]))) # [3, 2, 1]
# 映射和过滤
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
evens = list(filter(lambda x: x % 2 == 0, numbers))
# zip - 组合序列
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f"{name}: {age}")
# all 和 any
print(all([True, True, True])) # True
print(all([True, False, True])) # False
print(any([False, False, True])) # True
# enumerate
for i, value in enumerate(["a", "b", "c"]):
print(f"{i}: {value}")LeBot 控制示例
python
#!/usr/bin/env python3
import time
import math
from typing import Tuple
class LeBotController:
"""LeBot 机器人控制类"""
def __init__(self, port="/dev/ttyUSB0", baudrate=115200):
"""初始化 LeBot 控制器"""
self.port = port
self.baudrate = baudrate
self.connected = False
self.position: Tuple[float, float] = (0.0, 0.0)
self.orientation = 0.0 # 弧度
def connect(self) -> bool:
"""连接到 LeBot"""
try:
# 实际连接代码
print(f"连接到 {self.port}...")
time.sleep(0.5)
self.connected = True
print("连接成功!")
return True
except Exception as e:
print(f"连接失败:{e}")
return False
def disconnect(self) -> None:
"""断开连接"""
self.connected = False
print("已断开连接")
def move(self, speed: float, duration: float) -> None:
"""移动机器人"""
if not self.connected:
raise RuntimeError("未连接到机器人")
print(f"以 {speed} m/s 移动 {duration} 秒")
# 更新位置(简化计算)
distance = speed * duration
self.position = (
self.position[0] + distance * math.cos(self.orientation),
self.position[1] + distance * math.sin(self.orientation)
)
time.sleep(duration)
def rotate(self, angle: float) -> None:
"""旋转机器人"""
if not self.connected:
raise RuntimeError("未连接到机器人")
print(f"旋转 {math.degrees(angle)} 度")
self.orientation = (self.orientation + angle) % (2 * math.pi)
def get_status(self) -> dict:
"""获取机器人状态"""
return {
"connected": self.connected,
"position": self.position,
"orientation": math.degrees(self.orientation)
}
def __enter__(self):
"""上下文管理器支持"""
self.connect()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""上下文管理器退出"""
self.disconnect()
# 使用 LeBot 控制器
if __name__ == "__main__":
# 方法 1:手动管理连接
robot = LeBotController()
robot.connect()
robot.move(1.0, 2.0) # 以 1 m/s 移动 2 秒
robot.rotate(math.pi / 2) # 旋转 90 度
robot.move(0.5, 1.0) # 以 0.5 m/s 移动 1 秒
status = robot.get_status()
print(f"机器人状态:{status}")
robot.disconnect()
# 方法 2:使用上下文管理器(推荐)
with LeBotController() as robot2:
robot2.move(2.0, 1.0)
robot2.rotate(math.pi / 4)Python 最佳实践
- 遵循 PEP 8 代码风格 - 使用统一的代码格式
python
# ✓ 好的做法
def calculate_distance(point1, point2):
x_diff = point2[0] - point1[0]
y_diff = point2[1] - point1[1]
return (x_diff**2 + y_diff**2)**0.5
# ✗ 不好的做法
def calc_dist(p1,p2):
return ((p2[0]-p1[0])**2+(p2[1]-p1[1])**2)**0.5- 添加文档字符串和注释 - 解释代码意图
python
def move_robot(speed: float, duration: float) -> None:
"""
移动机器人。
参数:
speed: 移动速度(m/s)
duration: 移动时长(秒)
抛出异常:
ValueError: 如果速度为负数
"""
if speed < 0:
raise ValueError("速度不能为负数")
# 实现移动逻辑- 使用类型提示 - 明确指定参数和返回类型
python
from typing import List, Dict, Optional
def process_sensor_data(data: List[float]) -> Dict[str, float]:
"""处理传感器数据"""
return {
"mean": sum(data) / len(data),
"max": max(data),
"min": min(data)
}- 异常处理 - 恰当地处理可能出现的错误
python
def read_config(filename: str) -> dict:
"""读取配置文件"""
try:
with open(filename, "r") as f:
import json
return json.load(f)
except FileNotFoundError:
print(f"配置文件 {filename} 不存在")
return {}
except json.JSONDecodeError:
print(f"配置文件 {filename} 格式错误")
return {}- 使用列表推导式 - 简洁而高效
python
# ✓ 好的做法
squares = [x**2 for x in range(10)]
# ✗ 不好的做法
squares = []
for x in range(10):
squares.append(x**2)调试技巧
python
# 使用 print 调试
def move(speed, duration):
print(f"DEBUG: move called with speed={speed}, duration={duration}")
# 实现代码
print(f"DEBUG: move completed")
# 使用 pdb 调试器
import pdb
def complex_calculation():
x = 10
pdb.set_trace() # 在这里停止执行
y = x * 2
return y
# 常用 pdb 命令:
# n - 下一行
# s - 进入函数
# c - 继续执行
# l - 查看代码
# p 变量名 - 打印变量值
# w - 查看调用栈
# 使用日志模块(推荐)
import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
def robot_control():
logger.debug("机器人开始工作")
logger.info("机器人移动中")
logger.warning("电池电量低")
logger.error("连接失败")总结
Python 基础知识涵盖:
- 变量、数据类型和操作
- 控制流(条件语句和循环)
- 函数定义和调用
- 面向对象编程
- 文件 I/O 和异常处理
- 模块和包的使用
- 代码风格和最佳实践
掌握这些基础后,你可以开始用 Python 编写 LeBot 控制程序。在接下来的章节中,我们将深入学习 Python 的高级特性和在机器人开发中的应用。