一、环境搭建
- 官网下载Python 3.11+
- 勾选 Add Python to PATH(关键步骤!)
- 验证安装
python --version # 显示版本即成功
- 编辑器:PyCharm
- 在线环境:Replit
二、核心语法速通
- 变量与数据类型
name = "Alice" # 字符串
age = 25 # 整数
price = 19.99 # 浮点数
is_student = True # 布尔值
2. 流程控制
# 条件判断
if age >= 18:
print("成年人")
elif age >= 13:
print("青少年")
else:
print("儿童")
# 循环结构
for i in range(3): # 输出0,1,2
print(i)
nums = [1, 2, 3]
while nums: # 列表不为空时循环
print(nums.pop()) # 3,2,1
3. 函数与模块
# 自定义函数
def greet(name):
return f"Hello, {name}!"
# 调用标准库
import math
print(math.sqrt(16)) # 4.0
三、必学四大核心库
库名称 | 用途 | 示例代码片段 |
NumPy | 科学计算 | arr = np.array([1,2,3]) |
Pandas | 数据分析 | df = pd.read_csv('data.csv') |
Requests | 网络请求 | r = requests.get(url) |
Matplotlib | 数据可视化 | plt.plot(x, y); plt.show() |
四、新手练习项目
- 计算器
while True:
try:
expr = input("输入算式 (如 3+5): ")
print(eval(expr))
except:
print("输入错误!")
2. 词频统计
text = "hello world hello python"
words = text.split()
count = {word: words.count(word) for word in set(words)}
print(count) # {'world':1, 'hello':2, 'python':1}