Python零基础入门
·
一、Python基础介绍
1.1 什么是Python
Python 是一种解释型、面向对象、动态数据类型的高级编程语言。
-
可读性强、简洁易学习
-
高效高级数据结构
-
支持面向对象编程
-
全场景适用:Web、AI、数据分析、爬虫、自动化
Python 官网:https://www.python.org
1.2 Python版本选择
-
Python 2:2020-01-01 停止官方维护,禁止使用
-
Python 3:当前主流,推荐 3.8 及以上版本
二、Python 基本语法(核心)
2.1 变量与数据类型
Python 无需声明类型,直接赋值即可。
age = 30 # 整数 Int
pi = 3.14159 # 浮点数 Float
name = 'niko' # 字符串 String
is_student = True # 布尔值 Boolean
# f-string 格式化输出(推荐)
print(f"姓名: {name}, 年龄: {age}")
类型转换
str_num = "123" int_num = int(str_num) # 字符串 → 整数 new_msg = "分数:" + str(123) # 数字 → 字符串才能拼接
2.2 常用数据集合
列表 list(可变、有序)
todo = ["买牛奶", "取快递", "写代码"]
todo.append("运动30分钟")
todo[1] = "取顺丰快递"
del todo[2]
print(todo)
元组 tuple(不可变、有序)
info = ("zs", "110101199001011234", "1990-01-01")
print(info[0])
# info[1] = "xxx" # 报错:元组不可修改
字典 dict(键值对、3.7+有序)
contact = {"zs": "13800138000"}
contact["lisi"] = "13700137000"
print(contact["zs"])
2.3 流程控制(缩进为王!)
Python 不用大括号 {},用 4 个空格缩进 划分代码块。
条件判断 if/elif/else
score = 85
if score >= 90:
print("优秀")
elif score >= 80:
print("良好")
else:
print("加油")
循环 while / for
# while 循环
count = 3
while count > 0:
print(f"倒计时:{count}")
count -= 1
# for 循环
for i in range(1,6):
print(i)
# 遍历列表
fruits = ["apple","banana"]
for f in fruits:
print(f)
三、Python 面向对象
3.1 函数 def
def add(a, b): return a + b res = add(10,20) print(res)
3.2 类与对象 Class
-
__init__:构造函数 -
self:代表当前对象 -
__str__:打印对象时自动调用
class Dog:
species = "犬科" # 类属性
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print(f"{self.name} 汪汪叫")
def __str__(self):
return f"{self.name} {self.age}岁"
dog1 = Dog("小黑", 3)
dog1.bark()
print(dog1)
四、PHP vs Python 核心对比
| 特性 | PHP | Python | 适用场景 |
|---|---|---|---|
| 语法块 | 大括号 {} | 缩进 | Python 更简洁 |
| 变量 | 必须带 $ | 直接命名 | 入门更简单 |
| 应用领域 | 专注 Web | 全领域(AI/数据分析/爬虫) | 简单网站用 PHP,复杂系统用 Python |
| 字符串连接 | . | + / f-string | Python 更直观 |
五、Python 模块与工具
5.1 模块分类
-
内置模块:math、os、sys、random
-
自定义模块:自己写的
.py -
第三方模块:pip 安装
# 内置模块使用 import math print(math.sqrt(4))
5.2 pip 常用命令
# 查看已安装 pip list # 安装(清华镜像) pip install 模块名 -i https://pypi.tuna.tsinghua.edu.cn/simple # 卸载 pip uninstall 模块名
5.3 requests 库(网络请求神器)
import requests url = "https://www.zhibangyang.cn" res = requests.get(url) print(res.status_code) print(res.text)
5.4 OneForAll 域名收集工具
# 安装依赖 pip install -r requirements.txt -i 阿里云镜像 # 使用 python oneforall.py --target 域名 run
六、总结
本文涵盖:
-
Python 基础介绍与版本选择
-
变量、数据类型、流程控制
-
函数、类与面向对象
-
PHP vs Python 对比
-
模块、pip、requests、OneForAll 实战
Python 语法简洁、生态强大,是入门编程的最佳选择。
更多推荐



所有评论(0)