当前位置:首页 > Python > 正文

Python脚本编写入门教程 - 从零开始学习Python脚本编程

Python脚本编写入门教程

Python是当今最流行的脚本语言之一,以其简洁语法和强大功能而闻名。本教程将带你从零开始学习如何编写实用的Python脚本,实现文件处理、数据分析和自动化任务。

教程目录

  • Python环境搭建
  • 第一个Python脚本
  • 变量与数据类型
  • 条件语句与循环
  • 文件操作
  • 函数使用
  • 常用模块介绍
  • 错误处理
  • 实战案例

1. Python环境搭建

要编写Python脚本,首先需要安装Python解释器:

  1. 访问 Python官网 下载最新版本
  2. 运行安装程序,勾选"Add Python to PATH"选项
  3. 安装完成后,打开命令行输入 python --version 验证安装

2. 第一个Python脚本

创建名为 hello.py 的文件,输入以下内容:

print("你好,Python世界!")
print("这是你的第一个Python脚本")

在命令行运行:python hello.py

3. 变量与数据类型

基本数据类型

  • 整数:age = 25
  • 浮点数:price = 19.99
  • 字符串:name = "张三"
  • 布尔值:is_active = True
  • 列表:colors = ["红", "绿", "蓝"]

类型转换

num_str = "123"
num_int = int(num_str)  # 字符串转整数

num_float = 3.14
num_str = str(num_float)  # 浮点数转字符串

4. 条件语句与循环

条件语句

score = 85

if score >= 90:
    print("优秀")
elif score >= 80:
    print("良好")
elif score >= 60:
    print("及格")
else:
    print("不及格")

循环语句

# for循环
for i in range(5):
    print(f"当前值: {i}")

# while循环
count = 0
while count < 3:
    print(f"计数: {count}")
    count += 1

5. 文件操作

Python使文件读写变得非常简单:

# 写入文件
with open('data.txt', 'w') as f:
    f.write("第一行内容\n")
    f.write("第二行内容\n")

# 读取文件
with open('data.txt', 'r') as f:
    print("文件内容:")
    for line in f:
        print(line.strip())  # 移除行尾换行符

6. 函数使用

函数是组织和重用代码的基本方式:

# 定义函数
def calculate_area(length, width):
    return length * width

# 使用函数
print("矩形面积:", calculate_area(10, 5))

# 带默认参数的函数
def greet(name, message="你好"):
    print(f"{message}, {name}!")

greet("李四")  # 输出: 你好, 李四!
greet("王五", "早上好")  # 输出: 早上好, 王五!

9. 实战案例:批量重命名文件

下面是一个实用的Python脚本,用于批量重命名文件夹中的文件:

import os

def batch_rename_files(folder_path, prefix):
    """批量重命名文件夹中的文件"""
    try:
        # 获取文件夹中所有文件
        files = os.listdir(folder_path)
        
        for i, filename in enumerate(files, 1):
            # 分离文件名和扩展名
            name, ext = os.path.splitext(filename)
            
            # 构建新文件名
            new_name = f"{prefix}{i}{ext}"
            
            # 重命名文件
            os.rename(
                os.path.join(folder_path, filename),
                os.path.join(folder_path, new_name)
            )
            print(f"重命名: {filename} -> {new_name}")
        
        print("批量重命名完成!")
        
    except Exception as e:
        print("发生错误:", str(e))

# 使用示例
batch_rename_files("./photos", "vacation_")

学习建议

掌握Python脚本编程的最佳方法是实践:

  • 每天编写并运行一个小脚本
  • 尝试自动化日常重复任务
  • 阅读优秀开源项目的源代码
  • 参与实际项目积累经验

继续你的Python之旅

你已经掌握了Python脚本编程的基础知识!接下来可以探索:

网络爬虫 数据分析 Web开发 机器学习

发表评论