以下是一些 Python 知识点的示例代码:
- **基本语法**:
```python
这是一个注释
age = 25
if age < 18:
print("未成年")
else:
print("成年人")
```
- **数据类型**:
```python
num = 42
name = "John"
my_list = [1, 2, 3]
my_dict = {"name": "Alice", "age": 30}
```
- **变量与赋值**:
```python
x = 10
y = 5
z = x + y
```
- **条件与循环**:
```python
for i in range(5):
print(i)
while x > 0:
print(x)
x -= 1
```
- **函数**:
```python
def greet(name):
return "Hello, " + name
result = greet("Alice")
print(result)
```
- **模块与包**:
```python
import math
print(math.sqrt(16))
```
- **文件操作**:
```python
with open("example.txt", "r") as file:
content = file.read()
print(content)
```
- **异常处理**:
```python
try:
result = 10 / 0
except ZeroDivisionError:
print("除以零错误")
```
- **面向对象编程**:
```python
class Dog:
def init(self, name):
self.name = name
def bark(self):
print(self.name + "在叫")
my_dog = Dog("旺财")
my_dog.bark()
```
- **列表推导式**:
```python
numbers = [1, 2, 3, 4, 5]
squares = [x**2 for x in numbers if x % 2 == 0]
print(squares)
```
- **生成器与迭代器**:
```python
def simple_generator():
yield 1
yield 2
yield 3
gen = simple_generator()
for value in gen:
print(value)
```
- **装饰器**:
```python
def my_decorator(func):
def wrapper():
print("在函数之前执行")
func()
print("在函数之后执行")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
```
- **虚拟环境**:创建和激活虚拟环境
```bash
python -m venv myenv
source myenv/bin/activate # 在 Linux/macOS 上
```
- **包管理器**:使用 pip 安装第三方库
```bash
pip install pandas
```
这些示例可以帮助你更好地理解 Python 的各种概念和功能。你可以根据自己的需求和兴趣深入学习这些主题,并创建自己的 Python 程序。