1. Python概述
Python是一种简单易学、功能强大的编程语言,广泛应用于Web开发、数据分析、人工智能、自动化脚本等领域。Python的设计哲学强调代码的可读性和简洁性,使得它成为初学者和专业开发者的首选语言之一。更多学习教程www.fgedu.net.cn
2. Python环境搭建
搭建Python开发环境需要安装Python解释器,并配置相关工具。
# 1. 更新包管理器
$ sudo apt update
# 2. 安装Python 3.9
$ sudo apt install python3.9 python3.9-dev python3.9-venv
# 3. 验证安装
$ python3.9 –version
Python 3.9.10
# 4. 安装pip
$ sudo apt install python3-pip
# 5. 验证pip
$ pip3 –version
pip 21.2.4 from /usr/lib/python3/dist-packages/pip (python 3.9)
# 6. 创建虚拟环境
$ python3.9 -m venv myenv
# 7. 激活虚拟环境
$ source myenv/bin/activate
# 8. 安装包示例
(myenv) $ pip install requests numpy pandas
# 9. 退出虚拟环境
(myenv) $ deactivate
3. Python基础知识
Python基础知识包括变量、数据类型、运算符、控制语句等。学习交流加群风哥微信: itpux-com
# 变量声明与赋值
name = “Python Developer”
age = 25
salary = 5000.0
is_employed = True
# 输出信息
print(f”Hello, {name}!”)
print(f”Age: {age}”)
print(f”Salary: {salary}”)
print(f”Employed: {is_employed}”)
# 控制语句
if age >= 18:
print(“Adult”)
else:
print(“Minor”)
# 循环语句
print(“Counting from 1 to 5:”)
for i in range(1, 6):
print(i)
# 函数定义与调用
def add(a, b):
return a + b
result = add(10, 20)
print(f”Sum: {result}”)
# 列表操作
fruits = [“Apple”, “Banana”, “Orange”]
print(f”Fruits: {fruits}”)
fruits.append(“Mango”)
print(f”Fruits after append: {fruits}”)
print(f”First fruit: {fruits[0]}”)
# 字典操作
person = {“name”: “John”, “age”: 30, “city”: “New York”}
print(f”Person: {person}”)
print(f”Name: {person[‘name’]}”)
person[“age”] = 31
print(f”Person after update: {person}”)
# 输出:
# Hello, Python Developer!
# Age: 25
# Salary: 5000.0
# Employed: True
# Adult
# Counting from 1 to 5:
# 1
# 2
# 3
# 4
# 5
# Sum: 30
# Fruits: [‘Apple’, ‘Banana’, ‘Orange’]
# Fruits after append: [‘Apple’, ‘Banana’, ‘Orange’, ‘Mango’]
# First fruit: Apple
# Person: {‘name’: ‘John’, ‘age’: 30, ‘city’: ‘New York’}
# Name: John
# Person after update: {‘name’: ‘John’, ‘age’: 31, ‘city’: ‘New York’}
4. 数据类型与操作
Python支持多种数据类型,包括数字、字符串、列表、元组、字典、集合等。
# 数字类型
integer = 42
float_num = 3.14
complex_num = 1 + 2j
print(f”Integer: {integer}, type: {type(integer)}”)
print(f”Float: {float_num}, type: {type(float_num)}”)
print(f”Complex: {complex_num}, type: {type(complex_num)}”)
# 字符串
string = “Hello, Python!”
multi_line_string = “””This is a
multi-line
string”””
print(f”String: {string}”)
print(f”Multi-line string: {multi_line_string}”)
print(f”First character: {string[0]}”)
print(f”Substring: {string[7:13]}”)
print(f”Uppercase: {string.upper()}”)
print(f”Lowercase: {string.lower()}”)
# 列表(可变)
list_example = [1, 2, 3, 4, 5]
print(f”List: {list_example}”)
list_example[0] = 10
print(f”List after update: {list_example}”)
list_example.append(6)
print(f”List after append: {list_example}”)
list_example.remove(3)
print(f”List after remove: {list_example}”)
# 元组(不可变)
tuple_example = (1, 2, 3, 4, 5)
print(f”Tuple: {tuple_example}”)
# tuple_example[0] = 10 # 会引发错误,元组不可变
# 字典
dict_example = {“name”: “Alice”, “age”: 28, “city”: “London”}
print(f”Dict: {dict_example}”)
dict_example[“age”] = 29
print(f”Dict after update: {dict_example}”)
dict_example[“country”] = “UK”
print(f”Dict after add: {dict_example}”)
# 集合(无序,不重复)
set_example = {1, 2, 3, 4, 5, 3, 2}
print(f”Set: {set_example}”)
set_example.add(6)
print(f”Set after add: {set_example}”)
set_example.remove(2)
print(f”Set after remove: {set_example}”)
# 输出:
# Integer: 42, type:
# Float: 3.14, type:
# Complex: (1+2j), type:
# String: Hello, Python!
# Multi-line string: This is a
# multi-line
# string
# First character: H
# Substring: Python
# Uppercase: HELLO, PYTHON!
# Lowercase: hello, python!
# List: [1, 2, 3, 4, 5]
# List after update: [10, 2, 3, 4, 5]
# List after append: [10, 2, 3, 4, 5, 6]
# List after remove: [10, 2, 4, 5, 6]
# Tuple: (1, 2, 3, 4, 5)
# Dict: {‘name’: ‘Alice’, ‘age’: 28, ‘city’: ‘London’}
# Dict after update: {‘name’: ‘Alice’, ‘age’: 29, ‘city’: ‘London’}
# Dict after add: {‘name’: ‘Alice’, ‘age’: 29, ‘city’: ‘London’, ‘country’: ‘UK’}
# Set: {1, 2, 3, 4, 5}
# Set after add: {1, 2, 3, 4, 5, 6}
# Set after remove: {1, 3, 4, 5, 6}
5. 控制流语句
Python的控制流语句包括条件语句、循环语句等。
# if-elif-else语句
score = 85
if score >= 90:
print(“Grade: A”)
elif score >= 80:
print(“Grade: B”)
elif score >= 70:
print(“Grade: C”)
elif score >= 60:
print(“Grade: D”)
else:
print(“Grade: F”)
# for循环
fruits = [“Apple”, “Banana”, “Orange”, “Mango”]
print(“Fruits:”)
for fruit in fruits:
print(f”- {fruit}”)
# for循环与range
print(“Counting from 1 to 5:”)
for i in range(1, 6):
print(i)
# while循环
count = 1
print(“While loop:”)
while count <= 5:
print(count)
count += 1
# break语句
print("Break example:")
for i in range(1, 10):
if i == 5:
break
print(i)
# continue语句
print("Continue example:")
for i in range(1, 6):
if i == 3:
continue
print(i)
# 输出:
# Grade: B
# Fruits:
# - Apple
# - Banana
# - Orange
# - Mango
# Counting from 1 to 5:
# 1
# 2
# 3
# 4
# 5
# While loop:
# 1
# 2
# 3
# 4
# 5
# Break example:
# 1
# 2
# 3
# 4
# Continue example:
# 1
# 2
# 4
# 5
6. 函数与模块
Python函数是可重用的代码块,模块是包含函数和变量的文件。学习交流加群风哥QQ113257174
# 基本函数
def greet(name):
“””问候函数”””
return f”Hello, {name}!”
print(greet(“Alice”))
# 带默认参数的函数
def calculate_area(length, width=1):
“””计算面积”””
return length * width
print(calculate_area(5, 3))
print(calculate_area(5)) # 使用默认参数
# 带可变参数的函数
def sum_numbers(*args):
“””计算多个数字的和”””
return sum(args)
print(sum_numbers(1, 2, 3, 4, 5))
# 带关键字参数的函数
def print_person(**kwargs):
“””打印个人信息”””
for key, value in kwargs.items():
print(f”{key}: {value}”)
print_person(name=”Bob”, age=30, city=”New York”)
# 模块示例
# 创建一个名为mymodule.py的文件,内容如下:
“””
def add(a, b):
return a + b
def subtract(a, b):
return a – b
“””
# 导入模块
# import mymodule
# print(mymodule.add(10, 5))
# print(mymodule.subtract(10, 5))
# 导入模块中的特定函数
# from mymodule import add, subtract
# print(add(10, 5))
# print(subtract(10, 5))
# 输出:
# Hello, Alice!
# 15
# 5
# 15
# name: Bob
# age: 30
# city: New York
7. 面向对象编程
Python支持面向对象编程,包括类、对象、继承、多态等特性。
# 定义类
class Person:
“””人员类”””
# 类变量
species = “Homo sapiens”
# 构造方法
def __init__(self, name, age):
self.name = name # 实例变量
self.age = age
# 实例方法
def greet(self):
return f”Hello, my name is {self.name}”
def get_age(self):
return self.age
# 创建对象
person1 = Person(“Alice”, 25)
person2 = Person(“Bob”, 30)
print(person1.greet())
print(person2.greet())
print(f”{person1.name}’s age: {person1.get_age()}”)
print(f”{person2.name}’s age: {person2.get_age()}”)
print(f”Species: {Person.species}”)
# 继承
class Student(Person):
“””学生类,继承自Person”””
def __init__(self, name, age, student_id):
super().__init__(name, age) # 调用父类构造方法
self.student_id = student_id
# 重写父类方法
def greet(self):
return f”Hello, my name is {self.name} and I’m a student”
# 子类特有方法
def get_student_id(self):
return self.student_id
# 创建学生对象
student = Student(“Charlie”, 20, “S12345″)
print(student.greet()) # 调用重写的方法
print(f”Student ID: {student.get_student_id()}”)
print(f”Student age: {student.get_age()}”) # 调用父类方法
# 多态
def introduce(person):
print(person.greet())
print(“\nPolymorphism example:”)
introduce(person1) # 传入Person对象
introduce(student) # 传入Student对象
# 输出:
# Hello, my name is Alice
# Hello, my name is Bob
# Alice’s age: 25
# Bob’s age: 30
# Species: Homo sapiens
# Hello, my name is Charlie and I’m a student
# Student ID: S12345
# Student age: 20
#
# Polymorphism example:
# Hello, my name is Alice
# Hello, my name is Charlie and I’m a student
8. 文件操作
Python提供了丰富的文件操作功能,用于读写文件。
# 写入文件
with open(“example.txt”, “w”) as f:
f.write(“Hello, Python!\n”)
f.write(“This is a test file.\n”)
f.write(“Python file operations are easy.\n”)
print(“File written successfully”)
# 读取文件
with open(“example.txt”, “r”) as f:
content = f.read()
print(“\nFile content:”)
print(content)
# 逐行读取
with open(“example.txt”, “r”) as f:
print(“\nReading line by line:”)
for line in f:
print(line.strip())
# 追加内容
with open(“example.txt”, “a”) as f:
f.write(“Appended line 1\n”)
f.write(“Appended line 2\n”)
print(“\nContent after append:”)
with open(“example.txt”, “r”) as f:
print(f.read())
# 输出:
# File written successfully
#
# File content:
# Hello, Python!
# This is a test file.
# Python file operations are easy.
#
# Reading line by line:
# Hello, Python!
# This is a test file.
# Python file operations are easy.
#
# Content after append:
# Hello, Python!
# This is a test file.
# Python file operations are easy.
# Appended line 1
# Appended line 2
9. 常用库与工具
Python拥有丰富的第三方库,用于各种用途。更多学习教程公众号风哥教程itpux_com
# 1. requests – HTTP请求
# pip install requests
import requests
# 发送GET请求
response = requests.get(“https://api.github.com/users/octocat”)
print(f”Status code: {response.status_code}”)
print(f”JSON response: {response.json()}”)
# 2. numpy – 科学计算
# pip install numpy
import numpy as np
# 创建数组
arr = np.array([1, 2, 3, 4, 5])
print(f”Array: {arr}”)
print(f”Array shape: {arr.shape}”)
# 数组运算
arr2 = arr * 2
print(f”Array multiplied by 2: {arr2}”)
# 3. pandas – 数据分析
# pip install pandas
import pandas as pd
# 创建DataFrame
data = {
“name”: [“Alice”, “Bob”, “Charlie”],
“age”: [25, 30, 35],
“city”: [“New York”, “London”, “Paris”]
}
df = pd.DataFrame(data)
print(“\nDataFrame:”)
print(df)
# 数据操作
print(“\nPeople over 25:”)
print(df[df[“age”] > 25])
# 4. matplotlib – 数据可视化
# pip install matplotlib
import matplotlib.pyplot as plt
# 生成数据
x = np.linspace(0, 10, 100)
y = np.sin(x)
# 绘制图表
plt.plot(x, y)
plt.title(“Sine Wave”)
plt.xlabel(“X”)
plt.ylabel(“Y”)
# plt.show() # 显示图表
plt.savefig(“sine_wave.png”) # 保存图表
print(“\nChart saved as sine_wave.png”)
# 5. os – 操作系统接口
import os
# 获取当前目录
print(f”Current directory: {os.getcwd()}”)
# 列出目录内容
print(“\nDirectory contents:”)
for item in os.listdir(“.”):
print(f”- {item}”)
# 6. datetime – 日期时间处理
from datetime import datetime, timedelta
# 获取当前时间
now = datetime.now()
print(f”\nCurrent time: {now}”)
# 日期运算
tomorrow = now + timedelta(days=1)
print(f”Tomorrow: {tomorrow}”)
# 格式化日期
formatted = now.strftime(“%Y-%m-%d %H:%M:%S”)
print(f”Formatted time: {formatted}”)
10. Python开发最佳实践
Python开发最佳实践包括代码规范、性能优化、安全性等多个方面。
# 1. 代码规范
– 遵循PEP 8代码风格指南
– 使用有意义的变量和函数命名
– 保持代码缩进一致(4个空格)
– 编写清晰的文档字符串
– 避免过长的函数和类
# 2. 性能优化
– 使用列表推导式代替循环
– 避免在循环中进行昂贵的操作
– 使用生成器节省内存
– 合理使用内置函数和库
– 避免过度使用全局变量
# 3. 安全性
– 防止SQL注入
– 防止XSS攻击
– 避免硬编码敏感信息
– 合理处理异常
– 使用HTTPS
# 4. 测试
– 编写单元测试
– 使用pytest或unittest框架
– 实现集成测试
– 进行性能测试
# 5. 工具和工作流
– 使用虚拟环境隔离依赖
– 使用pip管理包
– 使用版本控制工具(如Git)
– 考虑使用CI/CD流水线
– 使用IDE(如PyCharm、VS Code)提高开发效率
# 6. 代码示例
# 好的实践示例
def calculate_average(numbers):
“””计算平均值”””
if not numbers:
return 0
return sum(numbers) / len(numbers)
# 使用列表推导式
numbers = [1, 2, 3, 4, 5]
squared = [x**2 for x in numbers if x > 2]
print(f”Squared numbers: {squared}”)
# 使用上下文管理器处理文件
with open(“example.txt”, “r”) as f:
content = f.read()
# 使用生成器
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
print(“Fibonacci sequence:”)
for num in fibonacci(10):
print(num)
author:www.itpux.com
本文由风哥教程整理发布,仅用于学习测试使用,转载注明出处:http://www.fgedu.net.cn/10327.html
