变量与数据类型
Python 是动态类型语言:变量不需要声明类型,直接赋值即可,类型随值自动确定。
基本数据类型
- int:整数;
- float:浮点数;
- str:字符串;
- bool:布尔值 True / False;
- NoneType:空值 None。
复合类型(后续章节详解)
list(列表)、tuple(元组)、dict(字典)、set(集合)。用 type() 查看类型,isinstance() 判断类型。
变量命名:字母/下划线开头,建议小写加下划线(snake_case)。常量用全大写。
代码示例
# 变量赋值(动态类型)
name = "小王" # str
age = 25 # int
height = 1.75 # float
is_student = True # bool
hobby = None # None
print(type(name)) # <class "str">
print(type(height)) # <class "float">
# 类型转换
age_str = str(age) # "25"
score = int("90") # 90
print(age_str, score)
# 多变量赋值
x, y, z = 1, 2, 3
print(x, y, z)
# 交换变量
x, y = y, x
print(x, y) # 2 1
# 命名规范
user_name = "admin"
MAX_COUNT = 100 # 常量习惯全大写
📚 Python 语法速查
常用条目速查,完整版见对应教程章节。可复制代码到在线运行中测试。
| 写法 / 语法 | 作用 |
|---|---|
print("hello") | 输出到控制台 |
name = "张三" | 变量赋值(无需声明类型) |
if x > 0: ... | 条件判断(注意冒号和缩进) |
for i in range(10): ... | 循环(缩进是语法的一部分) |
while x < 10: ... | 条件循环 |
def fn(a, b): return a + b | 定义函数 |
class Person: ... | 定义类 |
list = [1, 2, 3] | 列表(可改) |
tuple = (1, 2) | 元组(不可改) |
dict = {"key": "value"} | 字典(键值对) |
set = {1, 2, 3} | 集合(去重) |
len(obj) | 取长度 |
str(x) / int(x) / float(x) | 类型转换 |
s.split(",") | 字符串按分隔符拆分 |
" ".join(list) | 列表拼接成字符串 |
import os | 导入模块 |
from math import sqrt | 从模块导入指定函数 |
try: ... except Exception as e: ... | 异常捕获 |
with open("a.txt", "r") as f: ... | 文件读取(自动关闭) |
f"你好 {name}" | f-string 格式化 |
lambda x: x * 2 | 匿名函数 |
list(map(fn, arr)) | 函数式处理列表 |
range(start, stop, step) | 生成数字序列 |
if __name__ == "__main__": | 主入口判断 |
pip install 包名 | 安装第三方包(命令行) |