1. 首页 > IT综合教程 > 正文

it教程FG176-Python开发基础

1. Python语言概述

Python是一种高级编程语言,以其简洁、易读的语法而闻名。它支持多种编程范式,包括面向对象、命令式、函数式和过程式编程。Python广泛应用于Web开发、数据分析、人工智能、科学计算等领域。更多学习教程www.fgedu.net.cn

生产环境风哥建议:选择合适的Python版本,Python 3.8+是推荐的版本,因为Python 2已经停止支持。

2. Python环境搭建

搭建Python开发环境需要安装Python解释器和相关工具。

# 检查系统是否已安装Python
# python3 –version
Python 3.9.13

# 安装Python 3.9
# Ubuntu/Debian
# apt update && apt install -y python3 python3-pip python3-venv

# CentOS/RHEL
# yum install -y python3 python3-pip python3-venv

# 安装pip
# python3 -m pip install –upgrade pip

# 验证pip
# pip3 –version
pip 23.0.1 from /usr/local/lib/python3.9/site-packages/pip (python 3.9)

3. Python基础语法

Python基础语法包括变量、数据类型、运算符、控制语句等基本元素。学习交流加群风哥微信: itpux-com

# 第一个Python程序
print(“Hello, World!”)

# 变量和数据类型
name = “John”
age = 30
height = 1.75
is_student = False

# 列表
fruits = [“apple”, “banana”, “orange”]

# 字典
person = {“name”: “John”, “age”: 30, “city”: “New York”}

# 控制语句
if age >= 18:
print(“Adult”)
else:
print(“Minor”)

# 循环
for fruit in fruits:
print(fruit)

# 函数
def greet(name):
return f”Hello, {name}!”

print(greet(“Alice”))

风哥风哥提示:Python使用缩进来表示代码块,这是Python的一个重要特性,需要注意保持一致的缩进。

4. Python面向对象编程

Python支持面向对象编程,包括类、对象、继承、多态等特性。

# 类和对象
class Person:
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

# 创建对象
person = Person(“John”, 30)
print(person.greet())
print(person.get_age())

# 继承
class Student(Person):
def __init__(self, name, age, student_id):
super().__init__(name, age)
self.student_id = student_id

def get_student_id(self):
return self.student_id

# 创建学生对象
student = Student(“Alice”, 20, “12345”)
print(student.greet())
print(student.get_student_id())

5. Python模块和包

Python模块是一个包含Python定义和语句的文件,包是一个包含多个模块的目录。学习交流加群风哥QQ113257174

# 创建模块 (mymodule.py)
# def greet(name):
# return f”Hello, {name}!”

# 导入模块
import mymodule
print(mymodule.greet(“John”))

# 从模块导入特定函数
from mymodule import greet
print(greet(“Alice”))

# 导入所有函数
from mymodule import *

# 创建包
# 创建一个目录,包含__init__.py文件
# mypackage/
# __init__.py
# module1.py
# module2.py

# 导入包
import mypackage.module1
print(mypackage.module1.function1())

6. Python文件操作

Python提供了丰富的文件操作功能,用于读写文件。更多学习教程公众号风哥教程itpux_com

# 写入文件
with open(“example.txt”, “w”) as f:
f.write(“Hello, Python!\n”)
f.write(“This is a test file.\n”)

# 读取文件
with open(“example.txt”, “r”) as f:
content = f.read()
print(content)

# 逐行读取
with open(“example.txt”, “r”) as f:
for line in f:
print(line.strip())

# 追加文件
with open(“example.txt”, “a”) as f:
f.write(“This is an appended line.\n”)

7. Python异常处理

Python使用try-except语句处理异常,提高程序的健壮性。

try:
# 可能抛出异常的代码
result = 10 / 0
except ZeroDivisionError:
# 捕获特定异常
print(“Error: Division by zero”)
except Exception as e:
# 捕获所有异常
print(f”Error: {e}”)
finally:
# 无论是否发生异常都会执行的代码
print(“Execution completed”)

# 自定义异常
class CustomError(Exception):
pass

try:
raise CustomError(“This is a custom error”)
except CustomError as e:
print(f”Custom error: {e}”)

8. Python高级特性

Python提供了多种高级特性,如列表推导式、生成器、装饰器等。

# 列表推导式
numbers = [1, 2, 3, 4, 5]
squares = [x**2 for x in numbers]
print(squares) # [1, 4, 9, 16, 25]

# 生成器
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)

# 装饰器
def log_function(func):
def wrapper(*args, **kwargs):
print(f”Calling function: {func.__name__}”)
result = func(*args, **kwargs)
print(f”Function {func.__name__} completed”)
return result
return wrapper

@log_function
def add(a, b):
return a + b

print(add(1, 2))

9. Python常用库

Python拥有丰富的第三方库,用于各种应用场景。

# 安装第三方库
# pip3 install requests numpy pandas matplotlib

# 使用requests库
import requests
response = requests.get(“https://api.github.com”)
print(response.status_code)
print(response.json())

# 使用numpy库
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr.mean())
print(arr.max())

# 使用pandas库
import pandas as pd
df = pd.DataFrame({
“name”: [“John”, “Alice”, “Bob”],
“age”: [30, 20, 25]
})
print(df)

# 使用matplotlib库
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.plot(x, y)
plt.xlabel(“X-axis”)
plt.ylabel(“Y-axis”)
plt.title(“Line Plot”)
plt.savefig(“plot.png”)

10. Python开发最佳实践

Python开发的最佳实践包括代码风格、性能优化、错误处理等方面。author:www.itpux.com

# 代码风格示例(PEP 8)
# 使用4个空格缩进
# 每行不超过79个字符
# 函数和类之间空两行
# 方法之间空一行

# 性能优化
# 使用生成器节省内存
def generate_numbers(n):
for i in range(n):
yield i

# 使用字典或集合进行快速查找
names = set([“John”, “Alice”, “Bob”])
if “John” in names: # O(1)操作
print(“John is in the set”)

# 错误处理最佳实践
def divide(a, b):
if b == 0:
raise ValueError(“Division by zero”)
return a / b

try:
result = divide(10, 0)
except ValueError as e:
print(f”Error: {e}”)

生产环境风哥建议:使用虚拟环境隔离项目依赖,使用pytest进行测试,使用flake8检查代码风格,使用black自动格式化代码。

风哥风哥提示:使用虚拟环境可以避免依赖冲突,是Python项目的最佳实践。

# 创建虚拟环境
# python3 -m venv venv

# 激活虚拟环境
# Linux/Mac
# source venv/bin/activate

# Windows
# venv\Scripts\activate

# 安装依赖
# pip install -r requirements.txt

# 冻结依赖
# pip freeze > requirements.txt

本文由风哥教程整理发布,仅用于学习测试使用,转载注明出处:http://www.fgedu.net.cn/10327.html

联系我们

在线咨询:点击这里给我发消息

微信号:itpux-com

工作日:9:30-18:30,节假日休息