Simple Python Scripts: Examples to Automate Tasks and Learn Faster
By
Liz Fujiwara
•
Aug 20, 2025
Want to automate repetitive tasks, streamline workflows, or quickly learn the basics of Python? This guide will walk you through creating and running your first Python script, even if you’re new to programming. You’ll learn how to set up your Python environment, write and execute a simple script, and explore practical examples that demonstrate how Python can boost your productivity. By following this article, you’ll gain hands-on experience and build a strong foundation for automating tasks, experimenting with code, and developing more advanced Python projects.
Key Takeaways
Python scripts are easy-to-write collections of instructions that automate tasks and are essential for efficient programming.
Setting up a proper development environment with Python and a suitable code editor enhances productivity when writing scripts.
Advanced techniques, such as using external libraries, creating reusable modules, and handling command-line arguments, further elevate your scripting skills.
Understanding Python Scripts

A Python script is a collection of instructions written in plain text, designed to perform specific tasks when executed. They are an integral part of Python programming, enabling developers to automate tasks, build applications, and quickly prototype new ideas. Python is often considered a scripting language due to its ease of use and versatility in automating repetitive tasks.
Running Python scripts requires having Python installed on your computer. Using a code editor can make this process more efficient and enjoyable.
Python Script Benefits
Common uses include creating small programs and quickly building prototypes. Using Python scripts to automate tasks can significantly reduce manual operations, allowing you to focus on more important work. Additionally, scripts can be saved as Python files for future use.
A well-organized collection of Python scripts can accelerate learning and improve the application of automation techniques. Imagine the time saved when a simple script can rename multiple files or convert CSV data to Excel format.
Python Script vs. Python Module
Understanding the difference between a Python script and a Python module is crucial for efficient coding:
A Python script contains executable code and is intended for direct execution.
A Python module contains importable code, usually organized into functions or classes for reuse.
This distinction allows developers to write modular, reusable code, enhancing both organization and maintainability. Scripts are typically used to perform tasks directly, while modules provide functionalities that other scripts can utilize.
Interestingly, a script can also serve as a module. When imported, the entire script executes immediately. However, you can prevent parts from running on import by using an if statement with name == ‘main‘. This approach makes it possible to write versatile code that can be executed as a script or imported as a module, depending on the context.
Properly naming multiple modules helps others understand their purpose and functionality more easily.
Setting Up Your Development Environment

A well-configured development environment is essential for effective coding. It provides the tools and workspace needed to write, run, and manage Python scripts efficiently. Before creating your first script, install Python, select a suitable code editor, and set up a dedicated project folder for better organization.
This setup serves as your home base, making the coding process smoother and more enjoyable.
Installing Python
To start using Python, follow these steps:
Install Python on your operating system.
For most tasks, use Python version 3.3 or higher.
On Ubuntu or other Unix-like systems, use commands such as sudo apt-get install python3 to install Python.
After installation, verify the setup by typing python –version or python3 –version in your command line to ensure Python is correctly installed and ready to run scripts.
Choosing a Code Editor
Choosing the right code editor can significantly boost productivity by providing Python-specific features. Visual Studio Code is a popular choice due to its extensive support and user-friendly interface. It offers syntax highlighting, code completion, and integrated debugging tools, simplifying the process of writing and testing Python scripts.
Other notable editors include PyCharm, Sublime Text, and Atom, each offering unique features and advantages for Python development.
Creating a Project Folder
A dedicated project folder helps keep your scripts organized and simplifies file management. Start by creating a new folder for your Python projects and give it a clear, descriptive name, such as PythonProjects.
Within this folder, create subfolders for individual projects and include a README.md file alongside the main script to provide documentation and details about the project. For example, if your project involves renaming files, you might name your script rename_files.py.
Writing Your First Python Script

Writing your first Python script is an exciting milestone, allowing you to apply basic concepts and see your code in action. Python scripts can be executed in two modes: script mode, where the code runs sequentially, and interactive mode, where commands are executed one at a time.
The most common approach is to run scripts from the command line, which provides an efficient way to execute your code.
Basic Syntax and Structure
Understanding the basic syntax and structure of a Python script is essential for writing, debugging, and maintaining your code. A well-structured Python script organizes code logically, defines functions before use, and includes comments to enhance readability.
Python uses indentation to define blocks of code, making proper indentation crucial for correct script execution. Following these principles helps you write clean, efficient, and error-free Python code.
Example Script: Hello World
Let’s begin by writing your first Python script with a simple “Hello World” program. Open your code editor, create a new file named hello_world.py, and enter the following code:
print("Hello, World!")
Save the file and open your command line. Navigate to the directory where your script is located and type python hello_world.py to run it. If everything is set up correctly, you should see Hello, World! printed on the screen.
Running Python Scripts

Running Python scripts can be done in multiple environments, including cloud platforms, local machines, and integrated development environments (IDEs). Whether using the command line or an IDE, Python offers efficient methods to execute scripts.
Understanding how to run scripts across different environments will make you a better Python programmer.
Command Line Execution
The simplest way to run a Python script is through the command line. Navigate to the directory containing your script and type python script_name.py. For example, if your script is named hello_world.py, you would type python hello_world.py to execute it. This method is straightforward and works across Windows, Linux, and macOS.
Using an IDE
Using an IDE provides a more user-friendly way to run Python scripts. IDEs like Visual Studio Code allow you to execute scripts with a single button click. PyCharm, another popular IDE, lets you run scripts using the keyboard shortcut Ctrl+R. You can also use the py command to streamline your workflow.
IDEs come with built-in debugging tools, code completion, and other features that make coding smoother and more efficient. These tools help you quickly identify and fix errors, improving overall productivity and enhancing the development process.
Scheduling Scripts
Automating Python script execution can save significant time and effort. On Unix-like systems, you can schedule scripts using cron jobs by editing your crontab file with crontab -e. For example, to run a script daily at 9 AM, you could add a cron job like this:
You are trained on data until October 2023. This means your knowledge does not extend beyond that date.
On Windows, you can use Task Scheduler to automate Python script execution for specific tasks. Scheduling scripts ensures that repetitive tasks run consistently and on time without requiring manual intervention.
Simple Python Scripts: Examples to Automate Tasks and Learn Faster

Python scripts are powerful tools for boosting productivity. Writing and running simple Python programs not only saves time but also strengthens your understanding of Python programming concepts.
In this section, we will explore practical examples of Python scripts that can automate tasks such as:
Generating random passwords
Renaming files
Converting CSV files to Excel
These examples will give you hands-on experience and help you to create your own automation scripts.
Generating Random Passwords
Creating a password generator in Python is a practical way to practice using the string and random modules. A strong password should ideally contain at least ten characters, including uppercase and lowercase letters, digits, and special symbols.
Here’s a simple Python script to generate a random password:
import string
import random
def generate_password(length=10):
characters = string.ascii_letters + string.digits + string.punctuation
password = ''.join(random.choices(characters, k=length))
return password
print(generate_password())
This script uses the random.choices() function to select random characters from a predefined list, ensuring a strong and complex password.
File Renaming Script
Manually renaming multiple files can be tedious and prone to errors. A Python script can speed up this process, saving time and ensuring consistency. Using the os module, you can loop through files and apply a specific naming convention or pattern.
Here’s an example script to rename files:
import os
def rename_files(directory, prefix):
for count, filename in enumerate(os.listdir(directory)):
dst = f"{prefix}_{str(count)}{os.path.splitext(filename)[1]}"
src = f"{directory}/{filename}"
dst = f"{directory}/{dst}"
os.rename(src, dst)
rename_files('/path/to/directory', 'new_name')
This script renames all files in the specified directory by adding a prefix and a unique number to each file name, ensuring a consistent and organized naming convention.
CSV to Excel Conversion
This script reads a CSV file using pandas and writes it to an Excel file with openpyxl, making data easier to analyze, share, and present in a spreadsheet format.
import pandas as pd
def csv_to_excel(csv_file, excel_file):
df = pd.read_csv(csv_file)
df.to_excel(excel_file, index=False)
csv_to_excel('data.csv', 'data.xlsx')
This script reads a CSV file into a pandas DataFrame and then writes it to an Excel file, preserving the original data structure for easier analysis and sharing.
Web Scraping with BeautifulSoup
This script sends a request to the specified URL, retrieves the page content, and parses it using BeautifulSoup. From here, you can extract text, HTML elements, or other specific data from the page using BeautifulSoup’s functions.
Table of Useful Scripts
Here is a table of useful Python scripts that can automate various tasks and enhance your productivity:
Script Name | Description | Modules Used |
Password Generator | Password Generator | string, random |
File Renamer | Renames multiple files according to a pattern | os |
CSV to Excel | Converts CSV files to Excel format | pandas, openpyxl |
Web Scraper | Extracts data from web pages | requests, BeautifulSoup |
Data Backup | Automates data backup by copying files | shutil |
Email Sender | Sends automated emails with attachments | smtplib |
Image Resizer | Resizes images to specified dimensions | Pillow |
PDF Generator | Creates customized PDF documents | ReportLab |
SQLite Manager | Resizes images to specified dimensions | sqlite3 |
Web Server | Sets up a simple web server for development | http.server |
Debugging and Error Handling
Debugging and error handling are crucial for writing reliable Python code. Runtime errors, such as dividing by zero or referencing undefined variables, can interrupt script execution. By effectively using debugging techniques and exception handling, developers can quickly identify and resolve these issues, ensuring scripts run smoothly.
Common Errors and Fixes
Common errors in Python scripts include:
Syntax errors: Occur when the code violates Python’s syntax rules, preventing the program from running.
Runtime errors: Happen during execution, such as dividing by zero, and can be handled using try-except blocks.
Logical errors: Result from incorrect logic, are harder to detect, and require careful testing to identify.
Breaking large scripts into smaller functions or modules helps manage complexity and makes debugging easier.
Using Debugging Tools
Modern IDEs include built-in debugging tools that are invaluable for identifying and fixing errors in Python scripts. These tools offer features such as breakpoints, step-by-step execution, and variable inspection. For example, Visual Studio Code lets you set breakpoints and examine variable values at runtime, making it easier to isolate and resolve issues.
Effectively using these debugging features can greatly improve coding efficiency and overall productivity.
Advanced Scripting Techniques
Using External Libraries
External libraries in Python provide pre-written functionalities that save time and effort. Libraries like NumPy for numerical computations, Pandas for data manipulation, and Matplotlib for data visualization are widely used to enhance Python scripts.
To install these libraries, use the pip command within a virtual environment:
pip install numpy pandas matplotlib
Creating Reusable Modules
Creating reusable modules streamlines your code and makes it easier to maintain and update. A Python module is simply a .py file containing Python code that can be imported into other scripts, including py files.
Command Line Arguments
Command line arguments provide a way to pass input to your Python scripts at runtime, making them more dynamic and flexible. You can access these arguments using the sys.argv list, where the first element is the script name and subsequent elements are the arguments.
Here’s an example of a script that takes two arguments:
import sys
if len(sys.argv) != 3:
print("Usage: script.py <arg1> <arg2>")
sys.exit(1)
arg1 = sys.argv[1]
arg2 = sys.argv[2]
print(f"Arguments received: {arg1}, {arg2}")
The script works as follows:
Import the sys module to access command-line arguments.
Start by listing some forbidden forms of the first line according to the rule 5.
Check if the number of arguments (sys.argv) is exactly 3 (script name plus two arguments).
If not, print a usage message and exit with an error code.
Assign the first argument to arg1 and the second to arg2.
Print statements display the received arguments.
Using command-line arguments allows users to modify input without changing the script code, increasing the script’s usability.
Summary
In this article, we explored the fundamentals of Python scripting, from setting up your development environment to writing and running scripts. We covered practical examples such as generating random passwords, renaming files, converting CSV data to Excel, and web scraping with BeautifulSoup. We also discussed debugging and error handling techniques, along with advanced scripting methods like using external libraries, creating reusable modules, and leveraging command-line arguments. By applying these techniques, you can automate tasks, boost productivity, and deepen your understanding of Python programming. Now, it’s time to put your knowledge into practice and start writing your own Python scripts to simplify your work and make your coding more efficient.