Python常用代码
时间: 2024-08-16 14:04:13 浏览: 39
web开发python常用代码,一步到位,新手必备
Python是一门简洁易读的高级编程语言,常用于数据分析、Web开发、科学计算等领域。下面是一些常见的Python代码片段:
1. **Hello World** 示例,这是大多数编程语言入门的第一个程序:
```python
print("Hello, World!")
```
2. **变量和数据类型**:
```python
name = "Alice" # 字符串
age = 25 # 整数
num_list = [1, 2, 3] # 列表
```
3. **条件语句(if-else)**:
```python
if condition:
print("Condition is True")
else:
print("Condition is False")
```
4. **循环(for和while)**:
```python
for item in ['a', 'b', 'c']:
print(item)
i = 0
while i < 5:
print(i)
i += 1
```
5. **函数定义**:
```python
def greet(name):
return f"Hello, {name}!"
```
6. **列表推导式(List Comprehension)**:
```python
squares = [x**2 for x in range(5)]
```
7. **模块导入(如NumPy)**:
```python
import numpy as np
array = np.array([1, 2, 3])
```
阅读全文