引言:为什么选择Python作为你的第一门编程语言?

Python是一门高级、解释型、通用的编程语言,以其简洁易读的语法和强大的生态系统而闻名。对于零基础学习者来说,Python是极佳的入门选择,原因如下:

  1. 语法接近自然语言:Python的代码读起来像英语句子,降低了学习门槛。
  2. 应用领域广泛:从Web开发、数据分析、人工智能到自动化脚本,Python几乎无处不在。
  3. 庞大的社区支持:遇到问题时,你可以在Stack Overflow、GitHub等平台找到海量解决方案。
  4. 跨平台运行:Windows、macOS、Linux都能无缝运行Python代码。

第一部分:环境搭建与基础准备

1.1 安装Python解释器

步骤详解

  1. 访问Python官网(https://www.python.org/downloads/)
  2. 下载最新稳定版本(推荐Python 3.10或3.11)
  3. 安装时务必勾选”Add Python to PATH”选项
  4. 验证安装:打开命令行(Windows: cmd;macOS/Linux: Terminal),输入:
    
    python --version
    
    应显示类似 Python 3.11.0 的信息

1.2 选择开发环境

推荐方案对比

工具 适用人群 优点 缺点
IDLE 绝对初学者 随Python自带,简单易用 功能有限,不适合大型项目
VS Code 所有学习者 免费、强大、插件丰富 需要简单配置
PyCharm Community 专业开发者 功能全面,调试强大 占用资源较多

VS Code配置步骤

  1. 下载安装VS Code(https://code.visualstudio.com/)
  2. 安装Python扩展(搜索”Python”并安装)
  3. 创建第一个文件:hello.py
  4. 输入代码:
    
    print("Hello, World!")
    
  5. 运行:右键选择”Run Python File in Terminal”

1.3 第一个Python程序

让我们从经典的”Hello, World!“开始:

# 这是一个注释,解释代码的作用
print("Hello, World!")  # 打印问候语
print("欢迎来到Python世界!")

代码解析

  • print() 是Python内置函数,用于输出内容到屏幕
  • 字符串需要用引号(单引号或双引号)包裹
  • 注释以 # 开头,Python会忽略注释内容

第二部分:Python基础语法详解

2.1 变量与数据类型

变量:存储数据的容器,命名规则:

  • 以字母或下划线开头
  • 只能包含字母、数字、下划线
  • 区分大小写
  • 不能使用Python关键字
# 合法的变量名
name = "Alice"
age = 25
is_student = True
_height = 175.5

# 非法的变量名(会报错)
# 1name = "Bob"  # 以数字开头
# class = "Math"  # 使用了关键字

Python基本数据类型

类型 示例 说明
整数 42, -100 整数,无大小限制
浮点数 3.14, -0.5 带小数点的数字
字符串 "Hello", 'Python' 文本,用引号包裹
布尔值 True, False 逻辑值,只有两个
None None 表示空值或无值
# 数据类型示例
number = 42          # 整数
price = 19.99        # 浮点数
message = "Python"   # 字符串
is_active = True     # 布尔值
empty = None         # None值

# 查看数据类型
print(type(number))    # <class 'int'>
print(type(price))     # <class 'float'>
print(type(message))   # <class 'str'>
print(type(is_active)) # <class 'bool'>

2.2 运算符

算术运算符

a = 10
b = 3

print(a + b)   # 13  加法
print(a - b)   # 7   减法
print(a * b)   # 30  乘法
print(a / b)   # 3.333...  除法(浮点数)
print(a // b)  # 3   整除(取整)
print(a % b)   # 1   取余
print(a ** b)  # 1000  幂运算

比较运算符

x = 5
y = 10

print(x == y)  # False  等于
print(x != y)  # True   不等于
print(x > y)   # False  大于
print(x < y)   # True   小于
print(x >= y)  # False  大于等于
print(x <= y)  # True   小于等于

逻辑运算符

a = True
b = False

print(a and b)  # False  与
print(a or b)   # True   或
print(not a)    # False  非

2.3 字符串操作

字符串基础

# 创建字符串
s1 = "Python"
s2 = '编程'
s3 = """多行
字符串"""

# 字符串拼接
greeting = "Hello" + " " + "World"  # "Hello World"
name = "Alice"
age = 25
info = f"{name} is {age} years old."  # f-string格式化,Python 3.6+
print(info)  # Alice is 25 years old.

# 字符串方法
text = "  Python Programming  "
print(text.strip())      # "Python Programming"  去除两端空格
print(text.lower())      # "  python programming  "  转小写
print(text.upper())      # "  PYTHON PROGRAMMING  "  转大写
print(text.split())      # ['', 'Python', 'Programming', '']  按空格分割
print(text.find("Pro"))  # 10  查找子串位置
print(text.count("o"))   # 2  统计字符出现次数

2.4 列表(List)

列表是Python中最常用的数据结构之一,可变且有序。

# 创建列表
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]

# 访问元素(索引从0开始)
print(fruits[0])   # "apple"
print(fruits[-1])  # "cherry"  负数索引从末尾开始

# 修改元素
fruits[1] = "orange"
print(fruits)  # ["apple", "orange", "cherry"]

# 添加元素
fruits.append("grape")      # 在末尾添加
fruits.insert(1, "mango")   # 在指定位置插入
print(fruits)  # ["apple", "mango", "orange", "cherry", "grape"]

# 删除元素
fruits.remove("orange")     # 删除指定元素
popped = fruits.pop()       # 删除并返回最后一个元素
print(fruits)  # ["apple", "mango", "cherry"]
print(popped)  # "grape"

# 列表切片
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(numbers[2:5])    # [2, 3, 4]  从索引2到4(不包括5)
print(numbers[:3])     # [0, 1, 2]  从开头到索引2
print(numbers[6:])     # [6, 7, 8, 9]  从索引6到末尾
print(numbers[::2])    # [0, 2, 4, 6, 8]  步长为2
print(numbers[::-1])   # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]  反转

# 列表推导式(简洁的创建方式)
squares = [x**2 for x in range(10)]
print(squares)  # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares)  # [0, 4, 16, 36, 64]

2.5 元组(Tuple)

元组是不可变的序列,适用于存储不应被修改的数据。

# 创建元组
point = (3, 4)          # 坐标点
colors = ("red", "green", "blue")
single = (42,)          # 单元素元组需要逗号

# 访问元素
print(point[0])  # 3
print(point[1])  # 4

# 元组解包
x, y = point
print(f"坐标: ({x}, {y})")  # 坐标: (3, 4)

# 元组不可变,以下操作会报错
# point[0] = 5  # TypeError: 'tuple' object does not support item assignment

2.6 字典(Dictionary)

字典是键值对的集合,通过键来访问值。

# 创建字典
person = {
    "name": "Alice",
    "age": 25,
    "city": "Beijing"
}

# 访问值
print(person["name"])  # "Alice"
print(person.get("email", "N/A"))  # "N/A"  如果键不存在返回默认值

# 添加/修改键值对
person["email"] = "alice@example.com"  # 添加
person["age"] = 26  # 修改

# 删除键值对
del person["city"]
print(person)  # {'name': 'Alice', 'age': 26, 'email': 'alice@example.com'}

# 字典方法
keys = person.keys()      # dict_keys(['name', 'age', 'email'])
values = person.values()  # dict_values(['Alice', 26, 'alice@example.com'])
items = person.items()    # dict_items([('name', 'Alice'), ('age', 26), ('email', 'alice@example.com')])

# 字典推导式
squares_dict = {x: x**2 for x in range(5)}
print(squares_dict)  # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

2.7 集合(Set)

集合是无序且不重复的元素集合。

# 创建集合
fruits_set = {"apple", "banana", "cherry"}
numbers_set = {1, 2, 3, 3, 2, 1}  # 重复元素会被自动去重
print(numbers_set)  # {1, 2, 3}

# 集合操作
set_a = {1, 2, 3, 4}
set_b = {3, 4, 5, 6}

print(set_a | set_b)  # {1, 2, 3, 4, 5, 6}  并集
print(set_a & set_b)  # {3, 4}  交集
print(set_a - set_b)  # {1, 2}  差集
print(set_a ^ set_b)  # {1, 2, 5, 6}  对称差集

# 集合推导式
even_numbers = {x for x in range(10) if x % 2 == 0}
print(even_numbers)  # {0, 2, 4, 6, 8}

第三部分:控制流与函数

3.1 条件语句(if-elif-else)

# 基本结构
score = 85

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif score >= 60:
    grade = "D"
else:
    grade = "F"

print(f"成绩: {score}, 等级: {grade}")

# 多条件判断
temperature = 25
is_raining = False

if temperature > 30 and not is_raining:
    print("天气炎热,适合游泳")
elif temperature < 10:
    print("天气寒冷,注意保暖")
else:
    print("天气适中,适合户外活动")

# 嵌套条件
age = 20
has_license = True

if age >= 18:
    if has_license:
        print("你可以合法驾驶")
    else:
        print("你需要先考取驾照")
else:
    print("你未满18岁,不能驾驶")

3.2 循环结构

for循环

# 遍历列表
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(f"I like {fruit}")

# 使用range函数
for i in range(5):  # 0, 1, 2, 3, 4
    print(i)

# 带索引的遍历
for index, fruit in enumerate(fruits):
    print(f"{index}: {fruit}")

# 字典遍历
person = {"name": "Alice", "age": 25, "city": "Beijing"}
for key, value in person.items():
    print(f"{key}: {value}")

# 列表推导式(另一种循环方式)
squares = [x**2 for x in range(10)]
print(squares)  # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

while循环

# 基本while循环
count = 0
while count < 5:
    print(f"Count: {count}")
    count += 1

# 无限循环与break
import random

while True:
    num = random.randint(1, 10)
    print(f"随机数: {num}")
    if num == 7:
        print("找到了数字7!")
        break

# continue语句
for i in range(10):
    if i % 2 == 0:
        continue  # 跳过偶数
    print(i)  # 只打印奇数: 1, 3, 5, 7, 9

3.3 函数

定义和调用函数

# 无参数函数
def greet():
    print("Hello, World!")

greet()  # 调用函数

# 带参数的函数
def greet_person(name):
    print(f"Hello, {name}!")

greet_person("Alice")  # Hello, Alice!

# 带返回值的函数
def add(a, b):
    return a + b

result = add(5, 3)
print(result)  # 8

# 默认参数
def greet(name="Guest"):
    print(f"Hello, {name}!")

greet()        # Hello, Guest!
greet("Alice") # Hello, Alice!

# 可变参数(*args)
def sum_numbers(*args):
    total = 0
    for num in args:
        total += num
    return total

print(sum_numbers(1, 2, 3, 4, 5))  # 15

# 关键字参数(**kwargs)
def print_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print_info(name="Alice", age=25, city="Beijing")
# name: Alice
# age: 25
# city: Beijing

函数作用域

# 全局变量与局部变量
global_var = "I am global"

def my_function():
    local_var = "I am local"
    print(global_var)  # 可以访问全局变量
    print(local_var)   # 可以访问局部变量

my_function()
# print(local_var)  # 错误!local_var在函数外部不可见

# 使用global关键字修改全局变量
counter = 0

def increment():
    global counter
    counter += 1

increment()
print(counter)  # 1

第四部分:文件操作与异常处理

4.1 文件读写

文本文件操作

# 写入文件
with open("example.txt", "w", encoding="utf-8") as file:
    file.write("第一行:Python编程\n")
    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()去除换行符

# 追加模式
with open("example.txt", "a", encoding="utf-8") as file:
    file.write("第四行:新内容\n")

CSV文件操作

import csv

# 写入CSV
data = [
    ["姓名", "年龄", "城市"],
    ["Alice", 25, "Beijing"],
    ["Bob", 30, "Shanghai"],
    ["Charlie", 28, "Guangzhou"]
]

with open("people.csv", "w", newline="", encoding="utf-8") as file:
    writer = csv.writer(file)
    writer.writerows(data)

# 读取CSV
with open("people.csv", "r", encoding="utf-8") as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)  # 每行是一个列表

# 使用字典方式读写CSV
with open("people.csv", "r", encoding="utf-8") as file:
    reader = csv.DictReader(file)
    for row in reader:
        print(f"{row['姓名']}住在{row['城市']}")

4.2 异常处理

基本异常处理

# try-except结构
try:
    num = int(input("请输入一个整数: "))
    result = 10 / num
    print(f"10除以{num}等于{result}")
except ValueError:
    print("错误:请输入有效的整数!")
except ZeroDivisionError:
    print("错误:除数不能为零!")
except Exception as e:
    print(f"发生未知错误: {e}")

# 多个except块
try:
    file = open("nonexistent.txt", "r")
    content = file.read()
    file.close()
except FileNotFoundError:
    print("文件不存在!")
except PermissionError:
    print("没有读取权限!")
except Exception as e:
    print(f"其他错误: {e}")

# finally块(无论是否异常都会执行)
try:
    file = open("example.txt", "r")
    content = file.read()
    print(content)
except FileNotFoundError:
    print("文件不存在!")
finally:
    print("操作完成!")  # 总是会执行

自定义异常

# 定义自定义异常类
class AgeError(Exception):
    """自定义年龄异常"""
    pass

def check_age(age):
    if age < 0 or age > 150:
        raise AgeError(f"年龄{age}超出合理范围(0-150)")
    return True

# 使用自定义异常
try:
    age = int(input("请输入年龄: "))
    check_age(age)
    print(f"年龄{age}有效")
except AgeError as e:
    print(f"错误: {e}")
except ValueError:
    print("请输入有效的整数!")

第五部分:面向对象编程(OOP)

5.1 类与对象

# 定义类
class Dog:
    # 类属性(所有实例共享)
    species = "Canis familiaris"
    
    # 初始化方法(构造函数)
    def __init__(self, name, age):
        self.name = name  # 实例属性
        self.age = age
    
    # 实例方法
    def bark(self):
        return f"{self.name} says: Woof!"
    
    def describe(self):
        return f"{self.name} is {self.age} years old"
    
    # 静态方法(不需要self参数)
    @staticmethod
    def is_dog(obj):
        return isinstance(obj, Dog)

# 创建对象(实例化)
dog1 = Dog("Buddy", 3)
dog2 = Dog("Max", 5)

# 访问属性和方法
print(dog1.name)      # Buddy
print(dog1.age)       # 3
print(dog1.bark())    # Buddy says: Woof!
print(dog1.describe()) # Buddy is 3 years old

# 类属性访问
print(Dog.species)    # Canis familiaris
print(dog1.species)   # Canis familiaris

# 静态方法调用
print(Dog.is_dog(dog1))  # True
print(Dog.is_dog("Not a dog"))  # False

5.2 继承与多态

# 父类
class Animal:
    def __init__(self, name):
        self.name = name
    
    def speak(self):
        raise NotImplementedError("子类必须实现speak方法")
    
    def describe(self):
        return f"{self.name} is an animal"

# 子类1:Dog
class Dog(Animal):
    def __init__(self, name, breed):
        super().__init__(name)  # 调用父类构造函数
        self.breed = breed
    
    def speak(self):  # 重写父类方法
        return f"{self.name} says: Woof!"
    
    def describe(self):  # 重写父类方法
        return f"{self.name} is a {self.breed} dog"

# 子类2:Cat
class Cat(Animal):
    def __init__(self, name, color):
        super().__init__(name)
        self.color = color
    
    def speak(self):
        return f"{self.name} says: Meow!"
    
    def describe(self):
        return f"{self.name} is a {self.color} cat"

# 创建对象
dog = Dog("Buddy", "Golden Retriever")
cat = Cat("Whiskers", "orange")

# 多态:不同对象调用相同方法,行为不同
animals = [dog, cat]
for animal in animals:
    print(animal.speak())  # Buddy says: Woof!  Whiskers says: Meow!
    print(animal.describe())  # Buddy is a Golden Retriever dog  Whiskers is a orange cat

5.3 封装与属性装饰器

class BankAccount:
    def __init__(self, owner, initial_balance=0):
        self.owner = owner
        self._balance = initial_balance  # 约定:单下划线表示"受保护"属性
    
    # 使用@property装饰器创建只读属性
    @property
    def balance(self):
        return self._balance
    
    # 使用setter装饰器创建可写属性
    @balance.setter
    def balance(self, value):
        if value < 0:
            raise ValueError("余额不能为负数!")
        self._balance = value
    
    # 使用deleter装饰器
    @balance.deleter
    def balance(self):
        print("余额已被删除")
        self._balance = 0
    
    def deposit(self, amount):
        if amount <= 0:
            raise ValueError("存款金额必须为正数!")
        self._balance += amount
        return self._balance
    
    def withdraw(self, amount):
        if amount <= 0:
            raise ValueError("取款金额必须为正数!")
        if amount > self._balance:
            raise ValueError("余额不足!")
        self._balance -= amount
        return self._balance

# 使用BankAccount类
account = BankAccount("Alice", 1000)
print(account.balance)  # 1000

# 通过setter修改余额
account.balance = 1500
print(account.balance)  # 1500

# 尝试设置负余额(会抛出异常)
try:
    account.balance = -100
except ValueError as e:
    print(e)  # 余额不能为负数!

# 使用方法操作
account.deposit(500)
print(account.balance)  # 2000

account.withdraw(300)
print(account.balance)  # 1700

# 删除余额
del account.balance
print(account.balance)  # 0

第六部分:模块与包

6.1 导入模块

# 导入整个模块
import math
print(math.sqrt(16))  # 4.0
print(math.pi)        # 3.141592653589793

# 导入特定函数/类
from math import sqrt, pi
print(sqrt(16))  # 4.0
print(pi)        # 3.141592653589793

# 导入并重命名
import math as m
print(m.sqrt(16))  # 4.0

# 导入模块中的所有内容(不推荐)
from math import *
print(sqrt(16))  # 4.0
print(pi)        # 3.141592653589793

6.2 创建自己的模块

创建模块文件my_utils.py

# my_utils.py
def greet(name):
    """问候函数"""
    return f"Hello, {name}!"

def calculate_area(radius):
    """计算圆面积"""
    import math
    return math.pi * radius ** 2

class Calculator:
    """简单计算器类"""
    def __init__(self):
        self.history = []
    
    def add(self, a, b):
        result = a + b
        self.history.append(f"{a} + {b} = {result}")
        return result
    
    def multiply(self, a, b):
        result = a * b
        self.history.append(f"{a} * {b} = {result}")
        return result
    
    def show_history(self):
        for item in self.history:
            print(item)

# 测试代码(仅在直接运行此文件时执行)
if __name__ == "__main__":
    print("测试模块功能...")
    print(greet("Alice"))
    print(f"圆面积: {calculate_area(5)}")
    
    calc = Calculator()
    print(calc.add(2, 3))
    print(calc.multiply(4, 5))
    calc.show_history()

使用模块

# main.py
import my_utils

# 使用函数
print(my_utils.greet("Bob"))  # Hello, Bob!

# 使用类
calc = my_utils.Calculator()
print(calc.add(10, 20))  # 30
print(calc.multiply(3, 4))  # 12
calc.show_history()

6.3 包的创建与使用

包结构

my_package/
├── __init__.py
├── module1.py
├── module2.py
└── subpackage/
    ├── __init__.py
    └── module3.py

创建包

# my_package/__init__.py
print("正在导入my_package包")
from . import module1, module2
from .subpackage import module3

# my_package/module1.py
def func1():
    return "这是module1的函数"

# my_package/module2.py
def func2():
    return "这是module2的函数"

# my_package/subpackage/__init__.py
from . import module3

# my_package/subpackage/module3.py
def func3():
    return "这是module3的函数"

使用包

# 使用包
import my_package

print(my_package.module1.func1())  # 这是module1的函数
print(my_package.module2.func2())  # 这是module2的函数
print(my_package.subpackage.module3.func3())  # 这是module3的函数

第七部分:常用标准库介绍

7.1 datetime - 日期时间处理

from datetime import datetime, date, timedelta

# 获取当前时间
now = datetime.now()
print(f"当前时间: {now}")  # 2024-01-15 10:30:45.123456

# 创建特定日期时间
specific_date = datetime(2024, 12, 25, 18, 0, 0)
print(f"圣诞节: {specific_date}")  # 2024-12-25 18:00:00

# 格式化日期时间
formatted = now.strftime("%Y-%m-%d %H:%M:%S")
print(f"格式化时间: {formatted}")  # 2024-01-15 10:30:45

# 解析字符串为日期时间
parsed = datetime.strptime("2024-12-25 18:00:00", "%Y-%m-%d %H:%M:%S")
print(f"解析结果: {parsed}")  # 2024-12-25 18:00:00

# 日期计算
tomorrow = now + timedelta(days=1)
print(f"明天: {tomorrow}")

# 日期差
diff = timedelta(days=10) - timedelta(days=3)
print(f"日期差: {diff}")  # 7 days, 0:00:00

# 日期比较
date1 = date(2024, 1, 1)
date2 = date(2024, 12, 31)
print(date1 < date2)  # True

7.2 random - 随机数生成

import random

# 生成随机整数
random_int = random.randint(1, 100)  # 1到100之间的整数
print(f"随机整数: {random_int}")

# 生成随机浮点数
random_float = random.uniform(0.0, 1.0)  # 0.0到1.0之间的浮点数
print(f"随机浮点数: {random_float}")

# 从序列中随机选择
fruits = ["apple", "banana", "cherry", "date"]
random_fruit = random.choice(fruits)
print(f"随机水果: {random_fruit}")

# 随机打乱列表
numbers = [1, 2, 3, 4, 5]
random.shuffle(numbers)
print(f"打乱后的列表: {numbers}")

# 随机抽样
sample = random.sample(range(100), 5)  # 从0-99中随机抽取5个不重复的数
print(f"随机抽样: {sample}")

# 生成随机密码
import string
def generate_password(length=12):
    chars = string.ascii_letters + string.digits + string.punctuation
    return ''.join(random.choice(chars) for _ in range(length))

print(f"随机密码: {generate_password(16)}")

7.3 os - 操作系统交互

import os

# 获取当前工作目录
current_dir = os.getcwd()
print(f"当前目录: {current_dir}")

# 创建目录
os.makedirs("new_folder", exist_ok=True)  # exist_ok=True避免重复创建报错
print("目录创建成功")

# 列出目录内容
files = os.listdir(".")
print(f"当前目录文件: {files}")

# 检查路径是否存在
path_exists = os.path.exists("example.txt")
print(f"文件是否存在: {path_exists}")

# 获取文件大小
if path_exists:
    file_size = os.path.getsize("example.txt")
    print(f"文件大小: {file_size} 字节")

# 分割路径
path = "/home/user/documents/file.txt"
dir_name, file_name = os.path.split(path)
print(f"目录: {dir_name}, 文件: {file_name}")

# 连接路径(推荐使用os.path.join)
full_path = os.path.join("folder", "subfolder", "file.txt")
print(f"完整路径: {full_path}")

7.4 sys - 系统相关

import sys

# 获取Python版本
print(f"Python版本: {sys.version}")

# 获取命令行参数
print(f"命令行参数: {sys.argv}")

# 获取Python路径
print(f"Python路径: {sys.path}")

# 退出程序
# sys.exit(0)  # 正常退出
# sys.exit(1)  # 错误退出

# 获取标准输入/输出/错误
print("标准输出:", sys.stdout)
print("标准错误:", sys.stderr)

第八部分:实践项目:简易计算器

8.1 项目需求分析

功能需求

  1. 支持基本运算:加、减、乘、除
  2. 支持连续运算
  3. 支持历史记录查看
  4. 支持清除历史
  5. 支持退出程序

技术需求

  • 使用函数封装各个功能
  • 使用列表存储历史记录
  • 使用循环实现主程序
  • 使用异常处理处理错误输入

8.2 完整代码实现

# calculator.py
import os

class Calculator:
    """简易计算器类"""
    
    def __init__(self):
        self.history = []
        self.current_result = 0
    
    def add(self, a, b):
        """加法"""
        result = a + b
        self.history.append(f"{a} + {b} = {result}")
        self.current_result = result
        return result
    
    def subtract(self, a, b):
        """减法"""
        result = a - b
        self.history.append(f"{a} - {b} = {result}")
        self.current_result = result
        return result
    
    def multiply(self, a, b):
        """乘法"""
        result = a * b
        self.history.append(f"{a} * {b} = {result}")
        self.current_result = result
        return result
    
    def divide(self, a, b):
        """除法"""
        if b == 0:
            raise ValueError("除数不能为零!")
        result = a / b
        self.history.append(f"{a} / {b} = {result}")
        self.current_result = result
        return result
    
    def show_history(self):
        """显示历史记录"""
        if not self.history:
            print("历史记录为空")
            return
        
        print("\n=== 计算历史 ===")
        for i, record in enumerate(self.history, 1):
            print(f"{i}. {record}")
        print(f"当前结果: {self.current_result}")
    
    def clear_history(self):
        """清除历史记录"""
        self.history.clear()
        self.current_result = 0
        print("历史记录已清除")

def get_number_input(prompt):
    """获取数字输入"""
    while True:
        try:
            value = input(prompt)
            return float(value)
        except ValueError:
            print("错误:请输入有效的数字!")

def main():
    """主程序"""
    calc = Calculator()
    
    while True:
        print("\n" + "="*40)
        print("简易计算器")
        print("="*40)
        print("1. 加法")
        print("2. 减法")
        print("3. 乘法")
        print("4. 除法")
        print("5. 查看历史记录")
        print("6. 清除历史记录")
        print("7. 退出")
        print("="*40)
        
        choice = input("请选择操作 (1-7): ").strip()
        
        if choice == '1':
            a = get_number_input("输入第一个数: ")
            b = get_number_input("输入第二个数: ")
            result = calc.add(a, b)
            print(f"结果: {result}")
        
        elif choice == '2':
            a = get_number_input("输入第一个数: ")
            b = get_number_input("输入第二个数: ")
            result = calc.subtract(a, b)
            print(f"结果: {result}")
        
        elif choice == '3':
            a = get_number_input("输入第一个数: ")
            b = get_number_input("输入第二个数: ")
            result = calc.multiply(a, b)
            print(f"结果: {result}")
        
        elif choice == '4':
            try:
                a = get_number_input("输入第一个数: ")
                b = get_number_input("输入第二个数: ")
                result = calc.divide(a, b)
                print(f"结果: {result}")
            except ValueError as e:
                print(f"错误: {e}")
        
        elif choice == '5':
            calc.show_history()
        
        elif choice == '6':
            calc.clear_history()
        
        elif choice == '7':
            print("感谢使用计算器!")
            break
        
        else:
            print("无效选择,请重新输入!")
        
        input("\n按回车键继续...")

if __name__ == "__main__":
    main()

8.3 项目运行与测试

运行方式

python calculator.py

测试示例

========================================
简易计算器
========================================
1. 加法
2. 减法
3. 乘法
4. 除法
5. 查看历史记录
6. 清除历史记录
7. 退出
========================================
请选择操作 (1-7): 1
输入第一个数: 10
输入第二个数: 5
结果: 15.0

按回车键继续...

========================================
简易计算器
========================================
1. 加法
2. 减法
3. 乘法
4. 除法
5. 查看历史记录
6. 清除历史记录
7. 退出
========================================
请选择操作 (1-7): 5

=== 计算历史 ===
1. 10 + 5 = 15.0
当前结果: 15.0

按回车键继续...

第九部分:学习路径与资源推荐

9.1 学习路线图

阶段一:基础语法(1-2周)

  • 变量、数据类型、运算符
  • 字符串、列表、元组、字典、集合
  • 条件语句、循环结构
  • 函数定义与调用

阶段二:进阶概念(2-3周)

  • 文件操作
  • 异常处理
  • 模块与包
  • 面向对象编程基础

阶段三:实践项目(2-3周)

  • 小型项目:计算器、待办事项列表
  • 中型项目:简易通讯录、文本处理工具
  • 大型项目:Web应用、数据分析项目

阶段四:专业方向(持续学习)

  • Web开发(Flask/Django)
  • 数据分析(Pandas/NumPy/Matplotlib)
  • 机器学习(Scikit-learn/TensorFlow)
  • 自动化脚本(Selenium/BeautifulSoup)

9.2 推荐学习资源

在线教程

  1. Python官方文档https://docs.python.org/3/tutorial/
  2. 菜鸟教程https://www.runoob.com/python3/python3-tutorial.html
  3. 廖雪峰的Python教程https://www.liaoxuefeng.com/wiki/1016959663602400

书籍推荐

  1. 《Python编程:从入门到实践》 - Eric Matthes
  2. 《流畅的Python》 - Luciano Ramalho(进阶)
  3. 《Python Cookbook》 - David Beazley(实用技巧)

视频课程

  1. Coursera:Python for Everybody(密歇根大学)
  2. Udemy:Complete Python Bootcamp
  3. B站:Python教程(众多免费优质课程)

练习平台

  1. LeetCode:算法与数据结构练习
  2. HackerRank:Python专项练习
  3. Codewars:趣味编程挑战

9.3 常见问题与解决方案

问题1:安装包失败

# 解决方案:使用国内镜像源
pip install package_name -i https://pypi.tuna.tsinghua.edu.cn/simple

问题2:编码问题

# 解决方案:指定文件编码
# 在文件开头添加
# -*- coding: utf-8 -*-

# 或者使用Python 3默认的UTF-8编码

问题3:缩进错误

# 错误示例
def my_function():
print("Hello")  # 缩进错误!

# 正确示例
def my_function():
    print("Hello")  # 正确缩进(4个空格)

问题4:变量未定义

# 错误示例
print(x)  # NameError: name 'x' is not defined

# 正确示例
x = 10
print(x)

第十部分:总结与下一步行动

10.1 本指南回顾

通过本指南,你已经学习了:

  1. 环境搭建:Python安装、开发环境配置
  2. 基础语法:变量、数据类型、运算符、字符串操作
  3. 数据结构:列表、元组、字典、集合
  4. 控制流:条件语句、循环结构
  5. 函数:定义、参数、作用域
  6. 文件操作:读写文本文件、CSV文件
  7. 异常处理:try-except、自定义异常
  8. 面向对象:类、对象、继承、封装
  9. 模块与包:导入、创建、使用
  10. 标准库:datetime、random、os、sys
  11. 实践项目:简易计算器开发

10.2 下一步行动建议

立即行动

  1. 完成所有代码练习:确保每个示例都能运行
  2. 修改计算器项目:添加新功能(如幂运算、取余)
  3. 创建个人项目:选择感兴趣的方向开始实践

长期规划

  1. 选择专业方向:根据兴趣选择Web开发、数据分析等
  2. 参与开源项目:在GitHub上寻找适合初学者的项目
  3. 建立学习习惯:每天至少30分钟编码练习
  4. 加入社区:参与Python相关论坛、微信群、Discord

10.3 鼓励与寄语

编程是一门实践的艺术,理论知识需要通过大量编码来巩固。不要害怕犯错,每个错误都是学习的机会。Python社区非常友好,遇到问题时积极寻求帮助。

记住:最好的学习方式是边做边学。从今天开始,每天写一点代码,哪怕只是一个简单的”Hello, World!“。坚持一个月,你会惊讶于自己的进步。

祝你Python学习之旅愉快!