Maintenance

Site is under maintenance — quizzes are still available.

Go to quizzes

First Python Script

Write and run your first Python script in this hands-on tutorial. Learn the core concept, step-by-step walkthrough, troubleshooting, and what to study next in the Python fundamentals track.

Focus: write and run your first python script

Sponsored

You've installed Python and written a few lines in the REPL, but now it's time to move beyond one-off commands and create something you can save, share, and run again. The problem is that typing code directly into the interpreter is ephemeral — close the window and it's gone. To write real programs, you need to create a Python script: a file that contains your code and can be executed repeatedly. This lesson shows you exactly how to write and run your first Python script, turning your ideas into reusable, runnable programs.

The problem this lesson solves

When you run Python interactively in the terminal or REPL, every command you type is forgotten the moment you exit. This makes it impossible to build anything larger than a few lines. Without script files, you cannot:

  • Share your code with others
  • Automate repetitive tasks
  • Build multi-step workflows
  • Debug or edit your code over time

The REPL is great for quick experiments, but it's not a real development environment. The solution is to save your code in a file — a Python script — and run it with the Python interpreter. This lesson bridges the gap between testing a single expression and creating your first standalone program.

Core concept / mental model

Think of a Python script as a recipe for the computer. Just as a recipe lists ingredients and steps to bake a cake, a script lists instructions (lines of Python code) that the interpreter reads and executes in order, from top to bottom.

  • File extension: Python scripts always end with .py. For example, hello.py or script.py.
  • Interpreter: The Python interpreter (python3 on most systems) reads your script and performs each instruction.
  • Execution: When you run python3 my_script.py, the interpreter opens the file, reads every line, and runs each one, printing output to the terminal.

Pro tip: You can create a script with any text editor — even Notepad or TextEdit — but using a code editor like VS Code, Sublime Text, or PyCharm gives you syntax highlighting and error hints as you type.

How it works step by step

Follow these steps to write and run your first Python script:

Step 1: Choose a working directory

Open your terminal (Command Prompt on Windows, Terminal on macOS/Linux) and navigate to a folder where you'll store your projects. For example:

mkdir ~/python_projects
cd ~/python_projects

Step 2: Create the script file

Using a text editor, create a new file named hello.py. Add this content:

# hello.py - My first Python script
print("Hello, Python world!")
print("This is my first script.")
  • The # at the beginning of a line makes it a comment — Python ignores it. Use comments to explain your code.
  • The print() function displays text on the screen.

Step 3: Run the script

Back in the terminal, make sure you're in the same directory as hello.py, then run:

python3 hello.py

You should see:

Hello, Python world!
This is my first script.

If you see an error like python3: command not found, try python hello.py instead. See the Troubleshooting section below.

Step 4: Modify and run again

Now edit hello.py to include a simple calculation:

# hello.py - My first script with calculation
print("Hello, Python world!")
print("The sum of 3 and 5 is:", 3 + 5)

Save the file and run python3 hello.py again:

Hello, Python world!
The sum of 3 and 5 is: 8

Key insight: You can run the same script as many times as you like. Each change you save becomes permanent until you edit it again.

Hands-on walkthrough

Let's create a more practical script: a simple greeting program that asks for the user's name and responds.

Example 1: Interactive script with input

Create a file named greet.py:

# greet.py - Ask for name and greet
name = input("What is your name? ")
print("Hello, " + name + "! Welcome to Python.")

Now run it:

python3 greet.py

When prompted, type your name and press Enter. Output:

What is your name? Alice
Hello, Alice! Welcome to Python.

Example 2: Script with multiple outputs

Create countdown.py to demonstrate sequential execution:

# countdown.py - Countdown from 5 to 1
print("Counting down...")
for number in range(5, 0, -1):
    print(number)
print("Blast off!")

Run it:

python3 countdown.py

Output:

Counting down...
5
4
3
2
1
Blast off!

Pro tip: The for number in range(5, 0, -1) line creates a loop that counts backward from 5 to 1. Don't worry about the syntax yet — later lessons cover loops in detail. For now, notice how the script runs each line in order.

Example 3: Using the script as a module (advanced peek)

Python scripts can also be imported from other scripts. Create helper.py:

# helper.py

def greet(name):
    return f"Hi, {name}!"

print("Helper script loaded.")

Then create main.py in the same folder:

# main.py
import helper

print(helper.greet("Bob"))

Run main.py:

python3 main.py

Output:

Helper script loaded.
Hi, Bob!

This shows how you can reuse code across scripts — a powerful practice we'll expand in later lessons.

Compare options / when to choose what

Here's when to use a script versus the interactive REPL:

Use Case REPL (Interactive) Script (.py file)
Quick test of a single expression ✅ Best choice ❌ Overkill
Multi-step logic ❌ Not possible ✅ Perfect
Reusable code for later ❌ Lost on exit ✅ Saved permanently
Sharing code with others ❌ Can't share easily ✅ Send the .py file
Debugging complex code ❌ Hard to repeat ✅ Run multiple times with edits
  • Use the REPL when you want to check a single function's behavior or explore a library quickly.
  • Write a script when your logic spans more than two lines, when you need to save your work, or when you plan to run the same code again.

Troubleshooting & edge cases

Here are common errors beginners encounter when writing and running their first Python script.

"python3: command not found" or "'python' is not recognized"

Cause: The system cannot find the Python interpreter.

Solution: - On Windows, try python instead of python3. - On macOS/Linux, ensure Python 3 is installed by running which python3. If it's missing, install it from python.org. - If you have both Python 2 and 3 installed, use python3 explicitly to avoid running the older version.

IndentationError: unexpected indent

Cause: Your script has spaces or tabs where they aren't expected, or the indentation is inconsistent.

Example:

print("Hello")
   print("World")  # Extra spaces before print

Running this gives:

  File "script.py", line 2
    print("World")
    ^
IndentationError: unexpected indent

Solution: Remove extra spaces. Python uses indentation to group statements, but you should only indent inside blocks (like loops, functions, conditionals). For now, keep all lines flush left.

SyntaxError: invalid syntax

Cause: A typo, missing parenthesis, or incorrect punctuation.

Example:

print("Hello"  # Missing closing parenthesis

Solution: Check the line Python points to. Often it's a missing ) or ". Use a code editor with syntax highlighting to spot errors faster.

ModuleNotFoundError: No module named 'something'

Cause: You tried to import a file that doesn't exist in the same folder, or you misspelled the filename.

Solution: Verify the filename and ensure it's in the same directory as your main script. Use import module_name (without the .py extension).

What you learned & what's next

You now know how to write and run your first Python script. You understand:

  • The problem that scripts solve (code permanence, reusability, sharing)
  • The mental model of a script as a recipe executed from top to bottom
  • How to create a .py file in any text editor
  • How to run it with python3 filename.py
  • How to use print() and input() in a script
  • The difference between the REPL and scripts
  • Common beginner errors and how to fix them

This skill is the foundation for everything else in Python. In the next lesson, you'll learn about variables and data types — how to store and manipulate information inside your scripts. You'll also explore conditional logic and loops, allowing your scripts to make decisions and repeat tasks. Keep that script file handy; you'll build on it next time.

Remember: The key to mastery is practice. Write at least one new script every day, even if it's just a single print() statement. Experiment, break things, and fix them. That's how you learn.

Practice recap

Create a script named myself.py that prints your name, age, and favorite hobby on separate lines using three print() statements. Then run it with python3 myself.py. Next, modify it to ask for a fourth detail using input() (like "What is your dream job?") and print a complete sentence using all the information.

Common mistakes

  • Running python instead of python3 on macOS/Linux — this may invoke an older Python 2 interpreter that doesn't support modern syntax.
  • Forgetting to save the file before running it — always do Ctrl+S (Cmd+S on Mac) before executing python3 script.py.
  • Typing python3 script.py from a different directory — the script won't be found. Use cd to the correct folder first or provide the full path.
  • Including the .py extension in the import statement, like import my_script.py — this causes a ModuleNotFoundError.

Variations

  1. Using python on Windows versus python3 on macOS/Linux — check your shell by running python --version first.
  2. Running a script with python -i script.py — this opens the REPL after the script runs, letting you interact with the variables it created.
  3. Using IPython or Jupyter Notebook as an interactive alternative — good for data exploration but different from standard script-based workflows.

Real-world use cases

  • Automating daily server backups — write a script that copies files and sends a status email, then schedule it with cron or Task Scheduler.
  • Processing CSV files — a script reads rows of data, transforms them, and exports a cleaned report for a business analytics team.
  • Building a simple web scraper — write a script that downloads headlines from a news site every hour and saves them to a text file.

Key takeaways

  • A Python script is a text file with a .py extension that contains code executed from top to bottom.
  • Run scripts from the terminal using python3 filename.py — the interpreter reads and executes every line in order.
  • Use print() to see output and input() to get user input — both work the same in scripts as in the REPL.
  • Save your script before running; unsaved changes won't appear when you execute the file.
  • Choose scripts over the REPL when you need code permanence, reuse, or sharing with others.
  • Common errors like 'command not found', indentation issues, and missing parentheses are easy to fix once you know what to look for.

Sponsored

Sponsored

Discussion

Questions, corrections, and tips help everyone reading this page.

0 comments

Add a comment

Shown publicly with your comment.

Be constructive · max 4,000 characters

No comments yet — start the thread.

Related tutorials, quizzes, and articles for this topic.