Python零基础入门教程:从环境搭建到基础语法
一、Python简介与环境搭建
Python是一种解释型、面向对象的高级编程语言,以简洁易读的语法著称。广泛应用于Web开发、数据分析、人工智能等领域。
环境搭建步骤:
- 官网下载Python安装包(推荐3.6+版本)
- 安装时勾选"Add Python to PATH"
- 验证安装:命令行输入
python --version
二、基础语法与数据类型
1. 第一个Python程序
print("Hello, 优快云!") # 输出语句
2. 变量与数据类型
# 基本数据类型
name = "Alice" # 字符串(str)
age = 25 # 整数(int)
price = 19.99 # 浮点数(float)
is_student = True # 布尔值(bool)
# 类型转换示例
num_str = "123"
num_int = int(num_str) # 字符串转整数
3. 列表与字典
# 列表(list)
fruits = ["apple", "banana", "cherry"]
fruits.append("orange") # 添加元素
print(fruits[0]) # 访问第一个元素
# 字典(dict)
person = {
"name": "Bob",
"age": 30,
"city": "Shanghai"
}
print(person["age"]) # 访问值
三、流程控制
1. 条件语句
score = 85
if score >= 90:
print("优秀")
elif score >= 60:
print("及格")
else:
print("不及格")
2. 循环结构
# for循环
for i in range(5): # 输出0-4
print(i)
# while循环
count = 0
while count < 3:
print("循环次数:", count)
count += 1
四、函数与模块
1. 定义函数
def add_numbers(a, b):
"""返回两个数的和"""
return a + b
result = add_numbers(3, 5)
print(result) # 输出8
2. 使用内置模块
import math
print(math.sqrt(16)) # 平方根 4.0
print(math.pi) # 圆周率 3.141592653589793
五、文件操作
读写文件示例
# 写入文件
with open("test.txt", "w") as f:
f.write("Hello 优快云\nPython教程")
# 读取文件
with open("test.txt", "r") as f:
content = f.read()
print(content)
六、常用数据结构操作
列表推导式
squares = [x**2 for x in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]
字典操作
student = {"name": "Tom", "age": 20, "major": "CS"}
# 遍历字典
for key, value in student.items():
print(f"{key}: {value}")
# 添加新键值对
student["grade"] = "A"
七、异常处理
try:
num = int(input("请输入数字: "))
print("输入的数字是:", num)
except ValueError:
print("输入的不是有效数字!")
学习要点总结
- Python使用缩进(4个空格)表示代码块
- 动态类型语言,变量无需声明类型
- 列表、字典、元组是常用的数据结构
with
语句可自动管理文件资源- 异常处理能增强程序健壮性
练习题目
- 编写计算1-100偶数和程序
- 实现字符串反转函数
- 读取文本文件并统计行数