Python 入门指南
安装 Python
前往 Python 官网 下载最新版本,并按照安装向导完成配置。推荐安装时勾选“Add Python to PATH”选项,以便在命令行直接运行 Python。
运行 Python
Python 代码可以通过交互式解释器或脚本文件运行。
- 交互式解释器:在终端输入
python
或python3
进入交互模式,直接输入代码执行。 - 脚本文件:将代码保存为
.py
文件,例如hello.py
,然后在终端执行python hello.py
。
基本语法
Python 以缩进区分代码块,无需使用大括号。
# 示例:打印语句
print("Hello, World!")
# 条件语句
if 5 > 2:
print("Five is greater than two!")
else:
print("Condition not met.")
变量与数据类型
Python 是动态类型语言,变量无需声明类型。
# 变量赋值
x = 10
name = "Alice"
# 常见数据类型
integer_num = 42
float_num = 3.14
text = "Python"
boolean = True
my_list = [1, 2, 3]
my_dict = {"key": "value"}
函数定义
使用 def
关键字定义函数。
def greet(name):
return f"Hello, {name}!"
print(greet("Bob")) # 输出:Hello, Bob!
循环结构
Python 支持 for
和 while
循环。
# for 循环
for i in range(5):
print(i) # 输出 0 到 4
# while 循环
count = 0
while count < 3:
print(count)
count += 1
文件操作
使用 open
函数读写文件。
# 写入文件
with open("example.txt", "w") as file:
file.write("This is a test.")
# 读取文件
with open("example.txt", "r") as file:
content = file.read()
print(content) # 输出:This is a test.
模块与包
Python 通过模块组织代码,使用 import
导入。
# 导入标准库模块
import math
print(math.sqrt(16)) # 输出:4.0
# 导入自定义模块(假设存在 my_module.py)
import my_module
my_module.my_function()
常用工具与资源
- IDE 推荐:VS Code、PyCharm、Jupyter Notebook。
- 学习资源:
- 官方文档:docs.python.org
- 教程网站:Real Python、W3Schools Python
- 练习平台:LeetCode、Codewars
下一步学习方向
- 掌握面向对象编程(类与对象)。
- 学习常用库(如
requests
、pandas
、numpy
)。 - 探索 Web 开发(Django、Flask)或数据分析(Matplotlib、Seaborn)。