Python 基础知识超详细讲解(新手友好版)
一、Python 是什么?
Python 是一门简单易学、功能强大的编程语言,语法接近自然语言,适合零基础入门,可用于数据分析、爬虫、Web开发、人工智能、自动化办公等几乎所有领域。
二、环境准备
- 下载安装 Python(官网:python.org,安装时勾选Add Python to PATH)
- 编写工具:系统自带记事本、VS Code、PyCharm 均可
- 运行方式:
- 命令行输入
python 进入交互式环境
- 编写
.py 文件,命令行执行 python 文件名.py
三、基础语法
1. 注释
注释不执行,用于解释代码
2. 变量与数据类型
变量不用声明类型,直接赋值
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 | # 数字
a = 10 # 整数 int
b = 3.14 # 浮点数 float
c = 2 + 3j # 复数
# 字符串
s = "hello"
s2 = 'world'
# 布尔值
is_ok = True
is_no = False
# 空值
n = None
|
常用类型判断:type(变量)
3. 输入输出
| # 输出
print("Hello Python")
print(10 + 20)
# 输入(默认字符串类型)
name = input("请输入名字:")
age = int(input("请输入年龄:")) # 转整数
|
4. 运算符
- 算术:
+ - * / % // **(加、减、乘、除、取余、整除、次方)
- 比较:
> < >= <= == !=
- 逻辑:
and or not
- 赋值:
= += -= *= /=
四、流程控制
1. 条件语句 if-elif-else
| score = 85
if score >= 90:
print("优秀")
elif score >= 60:
print("及格")
else:
print("不及格")
|
⚠️ Python 用缩进表示代码块,不用大括号
2. 循环语句
for 循环
| # 遍历
for i in range(5): # 0~4
print(i)
# 遍历列表
for s in ["a", "b", "c"]:
print(s)
|
while 循环
| i = 0
while i < 5:
print(i)
i += 1
|
3. 跳出循环
break:结束整个循环
continue:跳过本次循环
五、常用数据结构
1. 列表 list(有序可修改)
| lst = [1, 2, "a", True]
lst.append(5) # 添加
lst[0] = 100 # 修改
print(lst[1]) # 取值
|
2. 元组 tuple(有序不可修改)
3. 字典 dict(键值对)
| d = {"name": "张三", "age": 20}
print(d["name"])
d["age"] = 21
|
4. 集合 set(无序不重复)
| s = {1, 2, 2, 3} # 自动去重 → {1,2,3}
|
六、函数
定义与调用
| def add(x, y):
return x + y
result = add(3, 5)
print(result)
|
默认参数
| def say_hello(name="小明"):
print("你好", name)
say_hello()
say_hello("小红")
|
七、字符串常用操作
| s = "hello"
print(s.upper()) # 转大写
print(s.lower()) # 转小写
print(s[0]) # 取字符
print(s[1:3]) # 切片
print(len(s)) # 长度
|
八、文件操作
| # 写入
with open("test.txt", "w", encoding="utf-8") as f:
f.write("Hello Python")
# 读取
with open("test.txt", "r", encoding="utf-8") as f:
content = f.read()
print(content)
|
九、异常处理
| try:
num = int(input("输入数字:"))
except:
print("输入不是数字")
|