下面是一份 超完整的 Python 语法与入门指南。内容从零开始,到能写小程序为止,适合系统学习。
一、Python简介
Python 是一种 高级、解释型、面向对象的编程语言。
特点:
- 语法简单
- 可读性强
- 开源生态丰富
- 跨平台
主要应用:
- 数据分析
- 人工智能
- Web开发
- 自动化脚本
常见开发工具:
- Visual Studio Code
- PyCharm
- Jupyter Notebook
二、安装与运行
安装 **Python 后,可以运行:
print("Hello Python")
输出:
Hello Python
三、Python基本语法规则
1 缩进
Python 使用 缩进表示代码块:
if True:
print("Hello")
通常使用 4个空格缩进。
2 注释
单行注释:
# 这是注释
print("hello")
多行注释:
"""
这是多行注释
"""
四、变量
变量用于 存储数据。
name = "Alice"
age = 20
height = 1.75
Python 是 动态类型语言:
x = 10
x = "hello"
五、基本数据类型
1 整数
a = 10
2 浮点数
b = 3.14
3 字符串
c = "Python"
4 布尔值
d = True
查看类型:
print(type(a))
六、运算符
算术运算
a = 10
b = 3
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a % b)
比较运算
print(a > b)
print(a < b)
print(a == b)
逻辑运算
True and False
True or False
not True
七、输入与输出
输出
print("Hello")
多个输出:
name = "Tom"
age = 18
print(name, age)
输入
name = input("请输入名字:")
print(name)
转换为数字:
age = int(input("年龄:"))
八、条件语句
age = 18
if age >= 18:
print("成年")
else:
print("未成年")
多个条件:
score = 85
if score >= 90:
print("优秀")
elif score >= 60:
print("及格")
else:
print("不及格")
九、循环结构
1 for循环
for i in range(5):
print(i)
输出:
0 1 2 3 4
2 while循环
i = 0
while i < 5:
print(i)
i += 1
十、数据结构
Python 有四大核心数据结构。
1 列表 list
nums = [1,2,3,4]
访问:
print(nums[0])
添加:
nums.append(5)
遍历:
for n in nums:
print(n)
2 元组 tuple
元组 不可修改。
t = (1,2,3)
3 字典 dict
键值对结构:
student = {
"name":"Tom",
"age":20
}
访问:
print(student["name"])
4 集合 set
集合 不重复:
s = {1,2,3,3}
print(s)
输出:
{1,2,3}
十一、字符串操作
s = "Python"
长度:
len(s)
切片:
print(s[0:3])
拼接:
a = "Hello"
b = "World"
print(a + b)
十二、函数
函数用于 封装代码。
def add(a,b):
return a + b
调用:
print(add(3,5))
默认参数:
def greet(name="Tom"):
print("Hello", name)
十三、模块
Python 可以导入模块。
import math
使用:
print(math.sqrt(16))
十四、异常处理
try:
x = 10 / 0
except:
print("发生错误")
十五、文件操作
写入文件:
f = open("test.txt","w")
f.write("Hello")
f.close()
读取文件:
f = open("test.txt","r")
print(f.read())
f.close()
推荐写法:
with open("test.txt","r") as f:
print(f.read())
十六、面向对象基础
定义类:
class Dog:
def __init__(self,name):
self.name = name
def bark(self):
print("汪")
创建对象:
d = Dog("Buddy")
d.bark()
十七、常见标准库
常见模块:
math数学random随机数datetime时间
示例:
import random
print(random.randint(1,10))
十八、Python常用第三方库
数据分析常用:
- NumPy
- pandas
- Matplotlib
十九、完整小项目示例
一个简单 成绩管理程序:
students = {
"Tom":80,
"Lucy":90,
"Jack":70
}
for name,score in students.items():
if score >= 60:
print(name,"及格")
else:
print(name,"不及格")
二十、Python学习路线
建议顺序:
Python基础语法
↓
数据结构
↓
函数与模块
↓
面向对象
↓
文件操作
↓
第三方库
进阶方向:
- 数据分析
- Web开发
- 自动化
- 人工智能
如果你需要,我可以再给你一份 《Python从入门到精通完整知识树(300+知识点)》,很多计算机专业课程都按这个体系学习,会更系统。