Sub topic 9
Writing your first script file
A script file is a plain text file that holds Python statements and runs from top to bottom. This chapter covers creating one, saving it correctly, and avoiding the errors that most often trip up a first script.
Prerequisites
This chapter assumes you have already done the following:
- Installed Python 3 and confirmed it with
python3 --version(orpy --versionon Windows). - Opened a terminal and moved between folders with
cd. - Used the REPL to evaluate a few expressions.
- Chosen a code editor. Any editor that saves plain text works.
Running the script is covered in the next chapter. Here you write it and check that it is saved correctly.
Why move from the REPL to a file
The REPL runs one statement at a time and forgets everything when you exit. A script file solves three problems:
- Persistence. The code stays on disk and you can edit it.
- Repeatability. Each run executes the same statements in the same order.
- Size. You can write programs of dozens or thousands of lines and organize them.
The REPL is still useful for quick experiments. Once you want to keep the code, put it in a file.
Set up a project folder
Keep scripts in a dedicated folder. Later chapters add a virtual environment, and that works best when each project has its own directory.
mkdir first-script
cd first-scriptAvoid spaces in folder names while you are learning. Spaces are legal, but you then have to quote the path in every command.
Create the file
Open your editor, create a new file, and save it as hello.py inside first-script. Three details matter.
- The extension is
.py. Python does not require it when you run a file by name, but editors use it for syntax highlighting, and tools such asimportrely on it. - The name is a valid identifier. Use lowercase letters, digits, and underscores, and do not start with a digit. A file named
my-script.pyruns, but you cannot import it later, because a hyphen is not allowed in a module name. - The name does not shadow a standard library module. Do not call your file
random.py,string.py,json.py, ortest.py. If you later writeimport random, Python can find your file first and fail in confusing ways.
Write the first line of code
Type this into hello.py:
print("Hello, world!")This is one statement. print is a built-in function. The text in quotes is a string. The parentheses pass the string to the function as an argument.
Two differences from the REPL are worth knowing. A script does not echo the value of a bare expression, so a line containing only 2 + 3 produces no output. You must call print to see a result. Also, the script ends when the last line finishes, and there is no prompt waiting for you.
Extend it with variables and several statements
Python runs statements in order. Replace the file contents with this:
name = "Ada"
language = "Python"
year = 2026
print("Hello, " + name)
print(f"{name} is learning {language} in {year}.")
print("Lines run", "in", "order.")What each part does:
name = "Ada"assigns a string to a variable. A variable is a name that refers to a value.f"..."is an f-string. Expressions inside{}are replaced by their values.printwith several arguments separates them with a space.- Blank lines are ignored. Use them to group related statements.
Because Python reads top to bottom, a variable must be assigned before you use it. If you move the print("Hello, " + name) line above name = "Ada", you get a NameError.
Comments
A comment starts with # and runs to the end of the line. Python ignores it.
# Greeting script: prints a short message.
name = "Ada" # who we are greeting
print(f"Hello, {name}!")Explain why code does something, not what it plainly does. # assign "Ada" to name adds nothing.
Indentation and whitespace
Python uses indentation to define blocks. A top-level statement in a simple script starts in column one. This fails:
name = "Ada"
print(name)It raises IndentationError: unexpected indent, because the second line is indented with no block that opens it. Blocks, such as the body of an if statement, come in later chapters. For now, remember two rules:
- Start top-level statements at the left edge.
- Use four spaces per indentation level, and never mix tabs and spaces in one file.
Most editors can insert four spaces when you press Tab. Check this setting once.
Save as plain text with UTF-8
Python 3 reads source files as UTF-8 by default. Most editors save UTF-8 already, but verify it if you use non-English characters or symbols:
city = "Zürich"
print(city, "→ 🙂")If a file is saved in another encoding, Python can raise a SyntaxError that mentions decoding. Set your editor's encoding to UTF-8. Printing may also look garbled in some Windows terminals even though the file is correct. That is a terminal display issue, not a file issue.
Word processors such as Microsoft Word or Google Docs are the wrong tool. They add formatting and can convert quotes. Use a plain text editor or a code editor.
Straight quotes versus curly quotes
Python accepts only straight quotes, " and '. Curly quotes, such as “Hello”, appear when text is pasted from web pages or documents. They cause SyntaxError: invalid character.
Quick checklist before running
| Check | What to look for |
|---|---|
| File name | Ends in `.py`, has no spaces, and does not shadow a standard library module |
| Location | You know which folder holds it, because you will `cd` there |
| Saved | The editor shows no unsaved marker, such as a dot or an asterisk |
| Quotes | Straight quotes, and each opening quote has a closing one |
| Parentheses | Every `(` has a matching `)` |
| Indentation | Top-level lines start at the left edge |
| Encoding | UTF-8 |
The "saved" check catches many problems. If you edit a file and run it without saving, you run the old version, and your change seems to have no effect.
Common first-script errors
Python reports errors with a traceback. Reading tracebacks has its own chapter. This table covers the errors you are most likely to see while writing the file.
| Error message | Likely cause | Fix |
|---|---|---|
| `SyntaxError: unterminated string literal` | A string is missing its closing quote | Add the closing quote |
| `SyntaxError: '(' was never closed` | A missing closing parenthesis | Add `)` |
| `NameError: name 'Print' is not defined` | Wrong capitalization. Python is case-sensitive | Use `print` |
| `IndentationError: unexpected indent` | A stray space or tab at the start of a line | Remove the indentation |
| `SyntaxError: invalid character` | Curly quotes or another pasted symbol | Retype it with a straight quote |
Python often reports a syntax error on the line after the real mistake. If the reported line looks correct, check the line above it.
A slightly larger example
This script combines the pieces from this chapter. It uses variables, a simple calculation, a comment, and formatted output.
# Compute a simple order total.
item = "notebook"
price = 3.50
quantity = 4
total = price * quantity
print(f"Item: {item}")
print(f"Quantity: {quantity}")
print(f"Total: {total:.2f}")Expected output when you run it:
Item: notebook
Quantity: 4
Total: 14.00{total:.2f} formats the number with two digits after the decimal point. Without it, Python would print 14.0.
Shebang lines on macOS and Linux
You may see #!/usr/bin/env python3 as the first line of a script. This is a shebang line. It tells Unix-like systems which interpreter to use if you run the file directly as an executable, after chmod +x. It is optional. Running python3 hello.py works with or without it, and Windows ignores it (the py launcher can read it to choose a version). Skip it for now. The next chapter shows the standard way to run a script.
Summary of what you built
You now have a saved .py file with several statements, comments, and formatted output. The file is ready to run. You also know the main ways a first file goes wrong: a hidden extension, a name that shadows a module, unsaved changes, curly quotes, and stray indentation.
Exercise
You save a file as random.py in your project folder. It contains import random and a call to random.randint(1, 6). Running it fails with an error saying the module has no attribute randint. Why does this happen, and how do you fix it?
Show answer
Python searches the script's own folder first when resolving imports, so import random loads your file random.py instead of the standard library module. Your file has no randint, so the attribute lookup fails. Rename the file to something that does not match a standard library module, such as dice.py. Also delete the __pycache__ folder that was created next to it, so the stale compiled copy of the shadowing module is not reused.
Exercise
A script contains the single line 2 + 3. You run it and nothing is printed. Change the script so that it displays the result, and explain why the original printed nothing.
Show answer
Change the line to print(2 + 3). The REPL echoes the value of a bare expression, but a script does not. A script only produces output when the code asks for it, for example by calling print.
Exercise
You edit hello.py to change the greeting, run it, and see the old greeting. Name two likely causes.
Show answer
The most likely cause is that the editor did not save the file, so the run used the old version on disk. Another is that you are running a different copy of the file, for example one in another folder, or that Windows has saved it as hello.py.txt. Check the saved state, the current folder, and the full file name.