[object Object]

A Practical Guide to Python Scripting for Beginners [2026]

Python scripts are the fastest way to automate small tasks with code. Learn what a script is, how to structure one cleanly, and build your first script step by step.

POSTED ON JANUARY 26, 2026

Python scripts let you automate repetitive tasks, process data, and handle the kind of work you’d otherwise do manually.

The difference between scripts and full programs? Scripts are focused. They do one thing and get out of the way.

This guide covers all you need to know about Python scripting for beginners: how scripts work, how to structure them, and how to write your first one.

What is a Python script?

A Python script is a .py file containing Python code that performs a specific task when you run it—like renaming files, backing up folders, or pulling data from websites.

Scripts let you:

  • Write multiple lines of code
  • Save them in a file
  • Run the entire program with a single command

They are faster to write and easier to test because Python runs your code directly without a separate compilation step.rganizw

They’re also reusable, meaning you can run the same script multiple times with different inputs.

How can you structure your Python script?

Structure your Python scripts with imports at the top, functions in the middle, and a main execution block at the bottom. 

This standard layout makes your code easier to debug and maintain.

Follow this logical flow to structure a Python script:

  1. Shebang line (only for Unix/Linux/macOS systems): Tells Unix-based systems which Python version to use. Skip this if you’re on Windows.
  1. Imports: The external libraries and modules for your script. Put these at the top so it’s clear what dependencies you’re using right from the start.
  1. Functions: Reusable blocks of code that perform specific tasks. Define these before you use them, or Python won’t know they exist yet.
  1. Main execution block: The if __name__ == “__main__”: section is where your script runs. This is where you call your functions and perform the key work.

Here’s how this looks in practice with a script that calculates how many days are left until a specific date:

#!/usr/bin/env python3  # Shebang (optional on Windows)
# Imports - we need datetime to work with dates
import datetime
# Functions - define what we want to do
def calculate_days_until(target_date):
    """Calculate days remaining until a target date."""
    today = datetime.date.today()
    delta = target_date - today
    return delta.days
# Main execution - actually run the script
if __name__ == "__main__":
    deadline = datetime.date(2026, 12, 31)
    days_left = calculate_days_until(deadline)
    print(f"Days until year end: {days_left}")

Notice how the script flows from top to bottom?

  • First, we import datetime because we need it to work with dates. 
  • Then we define our calculate_days_until() function that does the math. 
  • Finally, in the main execution block, we create a deadline, call our function, and print the result.

The if __name__ == “__main__”: block might look strange, but it’s telling Python, “only run this code if someone executes this file directly.”

If you later import this script into another project to use the calculate_days_until() function, Python won’t automatically run the code in that block. This keeps your functions reusable without side effects.

How to build your first Python script

To build your first Python script, set up your environment, write functions to organize your code, handle user input, check for errors, and test if everything works properly.

Let’s go over each step.

1. Set up your environment

Before writing any Python script, make sure you can write and run Python code. 

You can either set up Python locally on your computer with a text editor or use an online tool like Mimo’s Python Compiler.

Option 1: Practice online (fastest way to start)

Go to Mimo’s Python Compiler in your browser to start writing and running Python code immediately without installing anything. 

Mimo Python Compiler

This is perfect if you want to learn the basics and test things before committing to a local setup. 

Option 2: Set up Python locally (for serious projects)

If you want to build scripts that work with files on your computer or run automatically, you’ll need a local setup.

First, check if Python is already installed. Open your terminal (Mac/Linux) or Command Prompt (Windows) and type this command:

python --version

You’ll see either a version number like Python 3.14.2 (which means you’re ready to go) or an error message (which means you need to install Python).

  • If you need to install Python, go to python.org, download the latest Python 3 version for your operating system, and run the installer. 

During installation, check the box that says “Add Python to PATH” so you can run Python from anywhere on your computer.

Python 3.14.2 download

Tip: Throughout this guide, we use python in all command examples. Depending on your system, you might need to use python3 (common on Mac/Linux) or py (on some Windows installations) instead. If python my_script.py doesn’t work, try python3 my_script.py or py my_script.py.

  • Next, install a text editor

For example, you can download a free tool like VS Code from code.visualstudio.com.

  • Finally, create a project folder to organize your scripts

On Windows, open File Explorer, navigate to your Documents folder, right-click, select “New > Folder“, and name it python-scripts

On Mac, open Finder, go to your Documents folder, right-click, select “New Folder“, and also name it python-scripts.

From here, open VS Code, go to File > Open Folder, and select your python-scripts folder. 

Then go to File > New File and save it—for example, as my_script.py.

2. Write the basic structure for your Python script

Start by writing the basic structure for your Python script: imports at the top and a main execution block at the bottom.

Open your my_script.py file in VS Code (or use Mimo’s Python Compiler) and define the structure.

For instance, let’s imagine we’re building a Python script for a file organizer:

import os
import shutil
if __name__ == "__main__":
    print("File organizer starting...")

Next, run this script to make sure everything works well:

python my_script.py

You should see:

File organizer starting...

This confirms Python is running your script correctly. 

  • The import os and import shutil lines bring in Python’s built-in modules for working with files and folders. 
  • The if __name__ == “__main__”: block is where your script executes when you run it directly.

3. Define your functions

Next, break down what your script has to do into separate functions. 

For example, to build a script for a file organizer, you need to: 

  • Scan a folder for files
  • Figure out what type each file is
  • Move files to the right folders

Add these functions above your main block:

import os
import shutil
def get_file_extension(filename):
    """Get the file extension from a filename."""
    return filename.split('.')[-1].lower()
def organize_files(folder_path):
    """Organize files in a folder by their type."""
    # Categories for different file types
    categories = {
        'images': ['jpg', 'jpeg', 'png', 'gif', 'svg'],
        'documents': ['pdf', 'doc', 'docx', 'txt', 'xlsx'],
        'videos': ['mp4', 'avi', 'mov', 'mkv'],
        'audio': ['mp3', 'wav', 'flac']
    }
    print(f"Organizing files in: {folder_path}")
if __name__ == "__main__":
    organize_files("/path/to/test/folder")

Have a look at how functions are defined before the main block. 

Each of them has a clear purpose: get_file_extension() extracts the file type, and organize_files() will handle the organization logic. 

4. Add the core logic to your Python script

Now you can add the actual logic of the script—in our example, we want the script to scan files and organize them. 

Update your organize_files() function:

def organize_files(folder_path):
    """Organize files in a folder by their type."""
    categories = {
        'images': ['jpg', 'jpeg', 'png', 'gif', 'svg'],
        'documents': ['pdf', 'doc', 'docx', 'txt', 'xlsx'],
        'videos': ['mp4', 'avi', 'mov', 'mkv'],
        'audio': ['mp3', 'wav', 'flac']
    }
    # Get all files in the folder
    files = os.listdir(folder_path)
    for filename in files:
        file_path = os.path.join(folder_path, filename)
        # Skip if it's a folder
        if os.path.isdir(file_path):
            continue
        # Get file extension
        extension = get_file_extension(filename)
        # Find which category this file belongs to
        for category, extensions in categories.items():
            if extension in extensions:
                # Create category folder if it doesn't exist
                category_path = os.path.join(folder_path, category)
                os.makedirs(category_path, exist_ok=True)
                # Move the file
                new_path = os.path.join(category_path, filename)
                shutil.move(file_path, new_path)
                print(f"Moved {filename} to {category}/")
                break

This code scans every file in the folder, checks its extension, and moves it to the appropriate category folder. 

And, the os.makedirs(category_path, exist_ok=True) creates the category folder if it doesn’t already exist.

Note: This script only moves files that match the extensions defined in the categories dictionary. Files with other extensions are left unchanged.

5. Add user input

From here, add command-line arguments so users can specify which folder they want to organize without editing the code each time they run the script.

Right now, the folder path is hard-coded at /path/to/test/folder—you’d have to open the file and change it every time you want to organize a different folder. 

Instead, you can let users pass the folder path when they run the script.

Update your code to accept this input—add import sys at the top with your other imports, then replace your main block with this:

import os
import shutil
import sys
def get_file_extension(filename):
    """Get the file extension from a filename."""
    return os.path.splitext(filename)[1].lower().lstrip('.')
def organize_files(folder_path):
    """Organize files in a folder by their type."""
    categories = {
        'images': ['jpg', 'jpeg', 'png', 'gif', 'svg'],
        'documents': ['pdf', 'doc', 'docx', 'txt', 'xlsx'],
        'videos': ['mp4', 'avi', 'mov', 'mkv'],
        'audio': ['mp3', 'wav', 'flac']
    }
    files = os.listdir(folder_path)
    for filename in files:
        file_path = os.path.join(folder_path, filename)
        if os.path.isdir(file_path):
            continue
        extension = get_file_extension(filename)
        for category, extensions in categories.items():
            if extension in extensions:
                category_path = os.path.join(folder_path, category)
                os.makedirs(category_path, exist_ok=True)
                new_path = os.path.join(category_path, filename)
                shutil.move(file_path, new_path)
                print(f"Moved {filename} to {category}/")
                break
if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: python my_script.py <folder_path>")
        sys.exit(1)
    folder_to_organize = sys.argv[1]
    organize_files(folder_to_organize)

Now you can run the script like this:

python my_script.py /Users/yourname/Downloads

When you run the script with python my_script.py /Users/yourname/Downloads, Python saves that folder path so your script can use it. 

The if statement checks whether the user actually provided a folder path. 

If they forgot and just typed python my_script.py, the script reminds them what to include instead of breaking.

6. Add error handling

Next, protect your Python script against potential errors.

Scripts might fail for many reasons—e.g., folders don’t exist, you don’t have permission to move files, or file names conflict.

You can add error handling to catch these issues:

import os
import shutil
import sys
def get_file_extension(filename):
    """Get the file extension from a filename."""
    return filename.split('.')[-1].lower()
def organize_files(folder_path):
    """Organize files in a folder by their type."""
    # Check if folder exists
    if not os.path.exists(folder_path):
        print(f"Error: Folder '{folder_path}' does not exist.")
        return
    if not os.path.isdir(folder_path):
        print(f"Error: '{folder_path}' is not a folder.")
        return
    categories = {
        'images': ['jpg', 'jpeg', 'png', 'gif', 'svg'],
        'documents': ['pdf', 'doc', 'docx', 'txt', 'xlsx'],
        'videos': ['mp4', 'avi', 'mov', 'mkv'],
        'audio': ['mp3', 'wav', 'flac']
    }
    try:
        files = os.listdir(folder_path)
    except PermissionError:
        print(f"Error: No permission to access '{folder_path}'.")
        return
    files_moved = 0
    for filename in files:
        file_path = os.path.join(folder_path, filename)
        if os.path.isdir(file_path):
            continue
        extension = get_file_extension(filename)
        for category, extensions in categories.items():
            if extension in extensions:
                try:
                    category_path = os.path.join(folder_path, category)
                    os.makedirs(category_path, exist_ok=True)
                    new_path = os.path.join(category_path, filename)
if os.path.exists(new_path):
    print(f"Skipping {filename}: file already exists in {category}/")
    continue
                    shutil.move(file_path, new_path)
                    print(f"Moved {filename} to {category}/")
                    files_moved += 1
                except Exception as e:
                    print(f"Error moving {filename}: {e}")
                break
    print(f"\nDone! Organized {files_moved} files.")
if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: python my_script.py <folder_path>")
        sys.exit(1)
    folder_to_organize = sys.argv[1]
    organize_files(folder_to_organize)

The try/except blocks catch errors without crashing your script. 

If something goes wrong with one file, the script continues organizing the rest and tells you what failed. 

The script also validates that the folder exists and is really a folder before trying to organize it.

7. Test and debug your Python script

Finally, make sure that everything works properly before finalizing the script.

Testing means running your script with different inputs to check if it functions correctly and handles errors properly.

For our file organizer example, create a test folder somewhere on your computer, put a few random files in it, and name the folder—e.g., test_folder.

Once you have your test folder ready, run your script on it. Open your terminal, navigate to where your script is saved, and run:

python my_script.py test_folder

If your test folder is in the same directory as your script, you can use just test_folder. If it’s somewhere else on your computer, use the full path like /Users/yourname/Desktop/test_folder.

You should see an output like:

Moved photo.jpg to images/
Moved document.pdf to documents/
Moved song.mp3 to audio/
Moved video.mp4 to videos/
Done! Organized 4 files.

Open your test folder and look inside. If you see new folders (images, documents, audio, videos) with your files sorted into them, it means your script works.

Next, test that your error handling works. Try running the script on a folder that doesn’t exist:

python my_script.py /fake/folder

You should see:

Error: Folder '/fake/folder' does not exist.

The script caught the error instead of crashing. 

Now try running the script without specifying any folder:

python my_script.py

You should see:

Usage: python my_script.py <folder_path>

The script reminded you what to include.

If your script crashes or doesn’t work as expected, Python will show you an error message with a line number. 

Common errors you might come across include:

  • IndentationError: inconsistent spacing
  • NameError: using a variable before defining it
  • SyntaxError: missing colons or unclosed quotes

What’s next?

We’ve explored how to structure and build a proper Python script.

The approach we used here—functions, input handling, error checks, testing—applies to any script you’ll write. 

The real learning happens when you start writing more. You’ll spot patterns faster, debug quicker, and know which strategy fits which problem.

Ready to move beyond tutorials and learn Python faster

The Python Career Path by Mimo teaches practical skills for automation, data work, and AI-assisted coding. You’ll build a coding portfolio, get an official certification, and create real apps with AI.

Henry Ameseder

AUTHOR

Henry Ameseder

Henry is the COO and a co-founder of Mimo. Since joining the team in 2016, he’s been on a mission to make coding accessible to everyone. Passionate about helping aspiring developers, Henry creates valuable content on programming, writes Python scripts, and in his free time, plays guitar.

Learn to code and land your dream job in tech

Start for free