All 57 lessons
Lesson 2 of 57 · Getting Started
Setting Up Python, Jupyter and Your First Script
By Skillancy Editorial Team
Run the code in the free Python Compiler or on your own computer. Lessons that read files use the FreshBasket practice data: download the dataset (ZIP).
Before you write real analysis code you need a place to write and run it. The good news is that setting up Python takes about fifteen minutes, costs nothing, and you only do it once. The better news is that if you do not want to install anything today, Google Colab gives you a working Python notebook in your browser in under a minute.
In this lesson you will pick a setup that suits you, install the libraries the rest of the tutorial uses, and run your first script. Along the way you will learn how to check what is installed, how scripts differ from notebooks, and how to read the error message Python prints when something goes wrong.
Choose your setup
You have three sensible options. Pick one now, and you can always switch later because the Python code is identical everywhere.
| Option | Best for | Install needed? | Notes |
|---|---|---|---|
| Google Colab | Absolute beginners, any laptop | None, just a Google account | Runs in your browser; files disappear unless saved to Drive |
| Jupyter Lab | Analysis work, learning | Yes | Notebook cells with code, tables and charts together |
| VS Code | Scripts, automation, larger projects | Yes | A full code editor; also runs notebooks |
A practical recommendation: use Jupyter Lab for learning and exploration, and VS Code for scripts that you will schedule or share. If you are on a locked-down office laptop that does not allow installations, Colab is your friend.
Installing Python
1. Go to python.org/downloads and download the latest stable release (3.12 or newer is ideal; 3.10 is the minimum for this tutorial).
2. On Windows, tick the box "Add python.exe to PATH" on the first installer screen. This single checkbox prevents the most common beginner problem.
3. On macOS, run the installer package; on Linux, Python is usually pre-installed, and you can add what is missing with your package manager.
4. Open a terminal (Command Prompt or PowerShell on Windows, Terminal on macOS and Linux) and check:
python --versionOn some macOS and Linux systems the command is python3 --version. If the number printed is 3.10 or higher, you are done with this step.
Virtual environments: one box per project
Imagine project A needs an old version of a library and project B needs the newest. If both install into the same place, one will break. A virtual environment is a private folder that holds the libraries for one project only.
# 1. create an environment called .venv inside your project folder
python -m venv .venv
# 2. activate it
# Windows (PowerShell): .venv\Scripts\Activate.ps1
# macOS / Linux: source .venv/bin/activate
# 3. your prompt now starts with (.venv); install libraries into it
pip install pandas numpy matplotlib seaborn scipy openpyxl requests beautifulsoup4 jupyterlab pytest
# 4. start a notebook
jupyter labpip is Python's package installer. It downloads libraries from the Python Package Index (PyPI). The pip install line above installs everything this tutorial needs. You only run it once per environment, and you can run deactivate when you are finished to leave the environment.
Running code three ways
# Interactive shell: type python, then one line at a time (exit with exit())
python
# Script: put code in hello.py and run the whole file
python hello.py
# Notebook: run `jupyter lab`, create a new notebook, run cells with Shift+EnterIn Google Colab, go to colab.research.google.com, choose New notebook, type code in a cell and press Shift+Enter. Colab already has pandas, NumPy, matplotlib and seaborn installed.
Worked examples
All the examples below were run on a real machine, so the output you see is genuine. Your version numbers will probably differ slightly, which is perfectly fine.
Example 1: Check your Python version
Question: How do I confirm which Python I am running from inside Python itself?
import sys
print(sys.version_info.major, sys.version_info.minor)
print(sys.version_info >= (3, 10))Output
3 13
TrueHow it works: import sys loads a built-in module about the Python system. sys.version_info holds the version as a tuple-like object. Comparing it with (3, 10) asks, "is this at least 3.10?", and the answer is a boolean (True or False).
Reading the result: This build of Python is 3.13, so the check printed True. If yours prints False, install a newer Python before continuing.
Example 2: Check which libraries are installed
Question: Are pandas, NumPy and matplotlib installed, and which versions?
from importlib.metadata import version
for lib in ["pandas", "numpy", "matplotlib", "seaborn", "openpyxl"]:
print(f"{lib:<12} {version(lib)}")Output
pandas 3.0.5
numpy 2.5.3
matplotlib 3.11.2
seaborn 0.13.2
openpyxl 3.1.5How it works: importlib.metadata.version() asks Python for the installed version of a package. The for loop repeats the print for each library name, and {lib:<12} pads the name to 12 characters so the versions line up in a column.
Reading the result: Each line shows a library and its version. If a library is missing, Python raises PackageNotFoundError, and the fix is pip install <name>. Pandas 3.0.5 is what these lessons were built with. Pandas 2.x behaves the same for almost everything in this tutorial, and we flag the small differences where they matter.
Example 3: Create and run your first script
Question: How do I put code in a file and run it as a program?
from pathlib import Path
import subprocess, sys
Path("hello.py").write_text('print("Hello from a script!")\nprint(2 + 3)\n')
done = subprocess.run([sys.executable, "hello.py"], capture_output=True, text=True)
print(done.stdout)Output
Hello from a script!
5How it works: In your own setup you would simply create hello.py in an editor and type python hello.py in the terminal. Here the code writes the file for us (Path.write_text) and then runs it exactly like the terminal would (subprocess.run), capturing whatever it prints.
Reading the result: The script printed two lines. Notice that 2 + 3 appears as 5 only because we wrapped it in print(). That brings us to the key difference between scripts and notebooks.
Example 4: Notebooks echo, scripts do not
Question: Why did my code show a value in the notebook but print nothing when I ran the same code as a script?
Path("quiet.py").write_text("revenue = 4500\nrevenue * 2\n")
done = subprocess.run([sys.executable, "quiet.py"], capture_output=True, text=True)
print(repr(done.stdout))Output
''How it works: In a notebook, the last expression in a cell is displayed automatically. In a script, expressions are evaluated but their values are thrown away unless you pass them to print(). We ran a file that ends with revenue * 2 and captured its output.
Reading the result: The output is an empty string ''. If you move code from a notebook into a script, remember to wrap anything you want to see in print().
Example 5: Reading a traceback
Question: My script crashed. What is Python telling me?
Path("broken.py").write_text('total = 120\nprint(totl)\n')
done = subprocess.run([sys.executable, "broken.py"], capture_output=True, text=True)
print(done.stderr.replace(str(Path.cwd()) + "/", ""))Output
Traceback (most recent call last):
File "broken.py", line 2, in <module>
print(totl)
^^^^
NameError: name 'totl' is not defined. Did you mean: 'total'?How it works: We wrote a script with a typo: totl instead of total. When a program fails, Python prints a traceback to a channel called standard error. A traceback reads from top to bottom, and the most important line is the last one.
Reading the result: Read it in this order. The last line says NameError: name 'totl' is not defined, so the error type is NameError and the problem is a name Python does not know. The line above shows the exact code that failed, and the line above that gives the file name and line number (line 2). With those three facts you can almost always fix the bug in seconds.
Example 6: Getting help without leaving Python
Question: What does the round function do, and how do I find out without Googling?
print(round.__doc__.split("\n")[0])
print(type(round))Output
Round a number to a given precision in decimal digits.
<class 'builtin_function_or_method'>How it works: Every built-in function carries a short description called a docstring, stored in __doc__. In a notebook you can also type round? or help(round) to see the full manual. The type() function tells you what kind of thing an object is.
Reading the result: The docstring's first line explains that round rounds a number to a given precision, and type reports it is a built-in function. Learning to read these small manuals is how professionals learn new libraries.
Example 7: Comments keep code understandable
Question: How do I leave notes for future me (and my teammates) inside the code?
# Daily target for the Pune store (comment: ignored by Python)
daily_target = 150 # orders per day
monthly_target = daily_target * 30
print("Monthly target:", monthly_target)Output
Monthly target: 4500How it works: Everything after a # on a line is a comment. Python ignores it completely. Good comments explain why you did something, not what the line obviously does.
Reading the result: The comments did not affect the output at all. Use them generously while learning, then aim for clear variable names that need fewer comments.
Example 8: A script that adapts to where it runs
Question: How can a file behave differently when run directly versus imported by another file?
Path("report.py").write_text('''
def main():
print("Running the daily report")
if __name__ == "__main__":
main()
''')
done = subprocess.run([sys.executable, "report.py"], capture_output=True, text=True)
print(done.stdout.strip())Output
Running the daily reportHow it works: Every Python file has a built-in variable __name__. When you run the file directly it equals "__main__", so the block under the if runs. If another file imports this one, __name__ is the file's name instead and the block is skipped. You will see this pattern in almost every professional script, and we return to it in the modules lesson.
Reading the result: The message printed because we ran the file directly. This tiny pattern lets you reuse the same file as a tool and as a library.
Common mistakes
1. Forgetting to activate the virtual environment. If pip install succeeds but import pandas still fails, you probably installed into a different Python than the one running your code. Activate the environment, then reinstall.
2. Running python when the command is python3. On macOS and Linux, try python3 and pip3 if python is not found. On Windows, py is another launcher that works.
3. Misspelling a name. The most common runtime error for beginners is NameError. Compare the name in the error with the spelling in your code.
revenu = 5000
print(revenue)Output
Traceback (most recent call last):
File "example.py", line 2, in <module>
print(revenue)
^^^^^^^
NameError: name 'revenue' is not defined. Did you mean: 'revenu'?4. Saving a script with the wrong name. Never name your file pandas.py, random.py or csv.py. Python would import your file instead of the real library, and you would get baffling errors.
Practice questions
Practice 1 (Easy): Version gate
Write code that prints "OK" when your Python is 3.10 or newer, and "Please upgrade" otherwise.
Show solution
import sys
if sys.version_info >= (3, 10):
print("OK")
else:
print("Please upgrade")Output
OKThe comparison of version tuples works element by element, so (3, 13) is greater than (3, 10). The if/else prints one of two messages.
Practice 2 (Medium): Write and run a script
Create a script called cities.py that prints the three city names Bengaluru, Mumbai and Delhi on separate lines, then run it and show its output.
Show solution
Path("cities.py").write_text('for c in ["Bengaluru", "Mumbai", "Delhi"]:\n print(c)\n')
done = subprocess.run([sys.executable, "cities.py"], capture_output=True, text=True)
print(done.stdout)Output
Bengaluru
Mumbai
DelhiThe script contains a loop that prints each city. subprocess.run executed it as a separate program and we displayed whatever it printed.
Practice 3 (Hard): Library report
Print a tidy table of the versions of numpy, pandas and requests, but if a library is missing, print not installed instead of crashing.
Show solution
from importlib.metadata import version, PackageNotFoundError
for lib in ["numpy", "pandas", "requests", "not_a_real_library"]:
try:
v = version(lib)
except PackageNotFoundError:
v = "not installed"
print(f"{lib:<20} {v}")Output
numpy 2.5.3
pandas 3.0.5
requests 2.34.2
not_a_real_library not installedtry/except catches the specific error raised when a package is missing, so the loop continues. We added a fake library name on purpose to prove the fallback works. Error handling gets its own lesson later.
Key takeaways
- Use Google Colab for zero setup, Jupyter Lab for learning and exploring, and VS Code for scripts and projects.
- Install Python 3.10 or newer, and tick Add to PATH on Windows.
- A virtual environment keeps each project's libraries separate;
pip installadds libraries to it. - Notebooks echo the last value of a cell, but scripts only show what you
print(). - Read a traceback from the bottom: the last line names the error, and the lines above point to the file and line.
- You are running Python 3.13 with pandas 3.0.5 in this build; your versions may differ slightly without any effect on the lessons.
Frequently asked questions
Should I use Anaconda instead of plain Python?
Anaconda is a distribution that bundles Python with many scientific libraries and its own package manager (conda). It is a fine choice, especially on Windows, but plain Python with venv and pip is lighter and is what most companies use in production. Everything in this tutorial works with either.
What is the difference between Python, pip and a library?
Python is the language and interpreter. pip is a tool that installs libraries. A library (or package) is a collection of ready-made code, such as pandas, that you load with import.
Why do I get "ModuleNotFoundError: No module named pandas"?
The library is not installed in the Python environment that is running your code. Install it with pip install pandas while your virtual environment is active, or run %pip install pandas in a notebook cell to install into the notebook's own environment.
Is Jupyter Lab or VS Code better?
Neither is better; they do different jobs. Jupyter is ideal for exploring data step by step. VS Code is better for writing reusable scripts, using version control and debugging. Many analysts use both, and VS Code can also open notebooks.
Do my files in Google Colab stay forever?
No. A Colab session is temporary, and uploaded files vanish when it ends. Mount Google Drive in your notebook, or download your results, if you need to keep them.
Do I need to memorise installation commands?
No. Keep this lesson bookmarked and copy the commands when you need them. What matters is understanding what a virtual environment and pip are for.
Keep learning Python
One email a week with Python and analytics guides, new practice questions and cohort dates. No spam, unsubscribe anytime.
Ready to practise? Try the Python interview questions