引言
Python 是一种高级编程语言,以其简洁的语法和强大的功能而闻名。它广泛应用于数据分析、人工智能、Web 开发、自动化脚本等领域。本文将带你从 Python 的基础语法开始,逐步深入,并通过实战项目帮助你掌握 Python 编程。
1. Python 基础语法
1.1 变量与数据类型
Python 是一种动态类型语言,变量的类型在运行时确定。常见的数据类型包括整数(int)、浮点数(float)、字符串(str)、布尔值(bool)等。
# 整数
a = 10
print(type(a)) # 输出: <class 'int'>
# 浮点数
b = 3.14
print(type(b)) # 输出: <class 'float'>
# 字符串
c = "Hello, Python!"
print(type(c)) # 输出: <class 'str'>
# 布尔值
d = True
print(type(d)) # 输出: <class 'bool'>
1.2 运算符
Python 支持多种运算符,包括算术运算符、比较运算符、逻辑运算符等。
# 算术运算符
x = 10
y = 3
print(x + y) # 加法, 输出: 13
print(x - y) # 减法, 输出: 7
print(x * y) # 乘法, 输出: 30
print(x / y) # 除法, 输出: 3.333...
print(x // y) # 整除, 输出: 3
print(x % y) # 取余, 输出: 1
print(x ** y) # 幂运算, 输出: 1000
# 比较运算符
print(x > y) # 大于, 输出: True
print(x < y) # 小于, 输出: False
print(x == y) # 等于, 输出: False
print(x != y) # 不等于, 输出: True
# 逻辑运算符
print(True and False) # 与, 输出: False
print(True or False) # 或, 输出: True
print(not True) # 非, 输出: False
1.3 控制结构
Python 支持条件语句和循环语句,用于控制程序的执行流程。
# 条件语句
age = 18
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
# 循环语句
# for 循环
for i in range(5):
print(i) # 输出: 0 1 2 3 4
# while 循环
count = 0
while count < 5:
print(count) # 输出: 0 1 2 3 4
count += 1
1.4 函数
函数是组织代码的基本单元,可以重复使用。Python 使用 def
关键字定义函数。
# 定义函数
def greet(name):
return f"Hello, {name}!"
# 调用函数
print(greet("Alice")) # 输出: Hello, Alice!
print(greet("Bob")) # 输出: Hello, Bob!
1.5 列表与字典
列表(list)和字典(dict)是 Python 中常用的数据结构。
# 列表
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # 输出: apple
fruits.append("orange") # 添加元素
print(fruits) # 输出: ['apple', 'banana', 'cherry', 'orange']
# 字典
person = {
"name": "Alice", "age": 25}
print(person["name"]) # 输出: Alice
person["age"] = 26 # 修改值
print(person) # 输出: {'name': 'Alice', 'age': 26}
2. Python 进阶语法
2.1 列表推导式
列表推导式是一种简洁的创建列表的方式。
# 生成 0 到 9 的平方列表
squares = [x**2 for x in range(10)]
print(squares) # 输出: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
2.2 生成器
生成器是一种特殊的迭代器,使用 yield
关键字定义。
# 生成器函数
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
# 使用生成器
for num in fibonacci(10):
print(num) # 输出: 0 1 1 2 3 5 8 13 21 34
2.3 装饰器
装饰器是一种用于修改函数行为的函数,使用 @
符号应用。
# 定义装饰器
def my_decorator(func):
def wrapper():
print("Before function call")
func()
print("After function call")
return wrapper
# 应用装饰器
@my_decorator
def say_hello():
print("Hello!")
# 调用函数
say_hello()
# 输出:
# Before function call
# Hello!
# After function call
2.4 类与对象
Python 支持面向对象编程,使用 class
关键字定义类。
# 定义类
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
return f"{self.name} says woof!"
# 创建对象
my_dog = Dog("Buddy")
print(my_dog.bark()) # 输出: Buddy says woof!
3. Python 标准库
Python 提供了丰富的标准库,涵盖了文件操作、正则表达式、日期时间处理等功能。
3.1 文件操作
使用 open
函数进行文件读写操作。
# 写入文件
with open("example.txt", "w") as file:
file.write("Hello, Python!")
# 读取文件
with open("example.txt", "r") as file:
content = file.read()
print(content) # 输出: Hello, Python!
3.2 正则表达式
使用 re
模块进行正则表达式匹配。
import re
# 匹配邮箱地址
pattern = r"[\w\.-]+@[\w\.-]+"
text = "Contact us at info@example.com"
match = re.search(pattern, text)
if match:
print("Email found:", match.group()) # 输出: Email found: info@example.com
3.3 日期时间处理
使用 datetime
模块处理日期和时间。
from datetime import datetime
# 获取当前时间
now = datetime.now()
print("Current time:", now) # 输出: Current time: 2023-10-01 12:34:56.789012
# 格式化时间
formatted_time = now.strftime("%Y-%m-%d %H:%M:%S")
print("Formatted time:", formatted_time) # 输出: Formatted time: 2023-10-01 12:34:56
4. Python 实战项目
4.1 简单的计算器
我们将实现一个简单的命令行计算器,支持加、减、乘、除运算。
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
if y == 0:
return "Error: Division by zero"
return x / y
def calculator():
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
choice = input("Enter choice (1/2/3/4): ")
if choice in ['1', '2', '3', '4']:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
print(f"Result: {add(num1, num2)}")
elif choice == '2':
print(f"Result: {subtract(num1, num2)}")
elif choice == '3':
print(f"Result: {multiply(num1, num2)}")
elif choice == '4':
print(f"Result: {divide(num1, num2)}")
else:
print("Invalid input")
# 运行计算器
calculator()
4.2 简单的 Web 爬虫
我们将使用 requests
和 BeautifulSoup
库实现一个简单的 Web 爬虫,抓取网页标题。
import requests
from bs4 import BeautifulSoup
def fetch_title(url):
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
return soup.title.string
# 抓取网页标题
url = "https://www.example.com"
title = fetch_title(url)
print(f"Title of {url}: {title}")
5. 总结
本文介绍了 Python 的基础语法、进阶语法、标准库以及两个实战项目。通过本文的学习,你应该能够掌握 Python 的基本编程技能,并能够应用这些技能解决实际问题。Python 的应用领域非常广泛,继续深入学习,你将能够开发出更加复杂和强大的应用。
6. 进一步学习资源
希望本文能够帮助你开启 Python 编程之旅,祝你在编程的世界中不断进步!