1.3 Writing Your First Python Script
Completion requirements
Go through the activity to the end
Two Modes of Using Python in the Terminal
Before You Begin...
Now that you have Python installed, let's pause and learn about the two main ways to run Python code through the terminal (command line).
You'll see both used throughout this course and in real-world research workflows.
Two Ways to Use Python
| Mode | What it is | What it looks like | When to use |
|---|---|---|---|
| Interactive Mode | You type Python code one line at a time and get immediate feedback | You'll see a >>> prompt in your terminal. |
Trying out small pieces of code, learning, quick tests |
|
Script Mode (Non-interactive) |
You write Python code in a plain text file with a .py extension using a text editor (like vi, emacs, nano, VS Code or Notepad). Once your code is saved, you run the entire script at once through the terminal (or command line), rather than executing it line by line. |
You write code in a text editor and run with
|
Best for saving your work, writing multi-line programs, running larger tasks, or automating your workflow |
Examples:
Interactive Mode:
>>>
print("Hello!") # Example 1: You enter a
command
Hello!
# Python returns something to
you
>>>
2 + 3
# Example
2
5 # Output
>>>
a = 6 #
Example 3
>>>
b = 20
>>>
print(a + b)
26 # Output
- Note: Be sure to run
python3in the Terminal to start Python before writing any python codes. - Once you do, the prompt will change from
$to>>>. - In interactive mode, you can enter code line by line, and the output will be shown when you execute an expression or call a function (which we'll cover shortly).
Script Mode:
For this mode, first, write the python script in a code editor. For example:
1
2
2
# Saved in my_script.py
print("This is my first python script.")
print("This is my first python script.")
Then run the python script file in the terminal, like the following:
$
python3 my_script.py
Which Mode Should You Use?
Use Interactive Mode when you're:
- Learning
- Experimenting
- Exploring something new
Use Script Mode when you're:
- Writing longer code
- Automating tasks
- Saving your work
We'll try both in the next two pages.