Files
chunyu_project/media/learn/courses/12/chapters/47.md
T
2026-08-05 23:59:15 +08:00

109 lines
1.7 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 第2章 变量与数据类型
## 2.1 变量
在 Python 中,变量不需要声明类型,直接赋值即可创建。
```python
name = "张三"
age = 20
height = 1.75
is_student = True
```
### 变量命名规则
1. **只能包含**:字母、数字、下划线
2. **不能以数字开头**
3. **区分大小写**:`Name` 和 `name` 是不同的变量
4. **不能使用关键字**:如 `if`、`for`、`class` 等
### 推荐命名风格
| 类型 | 示例 | 说明 |
|------|------|------|
| 普通变量 | `user_name` | 蛇形命名法 |
| 常量 | `MAX_SIZE` | 全大写 |
---
## 2.2 数字
### 整数(int)
```python
a = 100
b = -50
print(type(a)) # <class 'int'>
```
### 浮点数(float)
```python
pi = 3.14159
price = 9.9
```
### 数字运算
```python
print(10 + 3) # 加法
print(10 - 3) # 减法
print(10 * 3) # 乘法
print(10 / 3) # 除法
print(10 // 3) # 整除
print(10 % 3) # 取余
print(10 ** 3) # 幂运算
```
---
## 2.3 字符串
```python
name = "Python"
print(len(name)) # 字符串长度
print(name[0]) # 索引从0开始
print(name[0:3]) # 切片操作
print(name.upper()) # 转大写
```
### 字符串格式化
```python
name = "小明"
age = 18
print(f"我叫{name},今年{age}岁")
```
---
## 2.4 列表
```python
fruits = ["苹果", "香蕉", "橙子"]
fruits.append("西瓜")
fruits.insert(0, "梨")
fruits.pop()
```
---
## 2.5 字典
```python
student = {
"name": "张三",
"age": 20,
"major": "计算机科学"
}
print(student["name"])
```
---
## 本章练习
1. 创建一个包含5个元素的列表,并进行增删改操作
2. 创建一个学生字典,包含姓名、年龄、成绩等信息
3. 编写程序,输入圆的半径,计算圆的面积