5.1 Introduction to Python
Table of Contents
Why Python Is Popular for Backend Development
Python is one of the most popular languages for backend development, especially for beginners. There are several reasons for this.
First, Python code is very readable. The syntax is close to plain English, so a line like:
if age >= 18:
print("You are an adult")is easy to understand even for someone who has never written code before.
Second, Python has a huge ecosystem. There are thousands of libraries that solve common backend problems, for example:
| Task | Popular Python Library / Tool |
|---|---|
| Building APIs | FastAPI, Flask, Django REST |
| Working with databases | SQLAlchemy, Django ORM |
| Sending HTTP requests | requests, httpx |
| Handling background tasks | Celery, RQ |
| Caching with Redis | redis-py |
| Testing | pytest |
Third, Python is very beginner friendly. You can start with simple scripts, then move to web applications, then to complex backend architectures, without switching languages.
Finally, Python is widely used in other areas, such as data science, automation, and scripting. Learning it helps you outside backend work too.
How Python Code Looks
Before we go into details in later chapters, you should see what Python code feels like.
Here is a tiny script that greets a user:
name = input("What is your name? ")
print("Hello,", name)A small function that adds two numbers:
def add(a, b):
return a + b
result = add(3, 5)
print(result) # 8A simple loop:
for i in range(3):
print("Iteration:", i)
You will learn what def, for, and range mean in the Programming Fundamentals section, and how they work in Python in later Python-specific chapters. For now, focus on how clean and short the code is.
Python Versions: 2 vs 3
Python comes in major versions. Historically, there was Python 2 and Python 3, and they are not fully compatible.
For backend development today you should always use Python 3. Python 2 is officially end-of-life and no longer gets security updates.
Rule: Always use Python 3.10 or newer for new backend projects, unless a specific company requirement says otherwise.
Why use a recent Python 3 version?
- Newer syntax that makes code cleaner, for example:
- Pattern matching from Python 3.10.
- Better type hints from Python 3.9+.
- Security fixes.
- Better performance.
- Libraries sometimes drop support for older versions.
You can check your installed version with:
python --version
# or sometimes
python3 --versionPython in the Backend Ecosystem
In backend development, Python usually runs on a server and handles HTTP requests from clients. It does not run in the browser, that is the job of JavaScript in the frontend.
A typical Python backend stack might look like this:
| Layer | Example with Python |
|---|---|
| Web server / reverse proxy | Nginx |
| Application server | Uvicorn, Gunicorn |
| Web framework | FastAPI, Django, Flask |
| Business logic | Your Python code |
| Database | PostgreSQL, MySQL, Redis, etc. |
| ORM / DB layer | SQLAlchemy, Django ORM |
For example, a very typical combination for modern APIs is:
- FastAPI as the web framework.
- Uvicorn as the ASGI server.
- PostgreSQL as the database.
- SQLAlchemy as the ORM.
All the code that glues these parts together is Python code.
Later chapters in this course will show you how to build complete stacks like this. In this chapter we focus on what makes Python itself suitable for that role.
Python Is Interpreted and High-Level
Python is an interpreted, high-level language.
- Interpreted means you do not need to compile your code into a separate binary file. You write
.pyfiles and run them directly with the Python interpreter.
Example:
python app.py
The interpreter reads app.py and executes it line by line.
- High-level means Python hides many low-level details from you, such as manual memory management or CPU instructions.
What does this mean for you as a backend developer?
- You can iterate quickly. Edit the file, run it again, see the result.
- You focus on the problem, not on low-level details.
- Performance is usually good enough for web APIs, especially when combined with good database design and caching. For very performance critical parts, you can use other tools or techniques, but that is an advanced topic.
Python Scripts vs Python Applications
In backend development you will see two common ways Python is used:
- Scripts
Small programs that perform a specific task, for example: - A script that imports data into a database.
- A script that sends a daily report email.
Example:
# import_users.py
import csv
def import_users(path: str) -> None:
with open(path, "r") as f:
reader = csv.DictReader(f)
for row in reader:
print("Importing", row["email"])
if __name__ == "__main__":
import_users("users.csv")Run with:
python import_users.py- Long-running applications
Programs that start once, then keep running, for example: - Web servers.
- Background worker processes.
- Scheduling services.
A simple skeleton of a web app entry point:
# main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/health")
def health_check():
return {"status": "ok"}
Here app will be started by an application server like Uvicorn, which will keep the process running and route HTTP requests to your Python functions.
Scripts and long-running applications use the same language, but they are structured differently. You start with small scripts, then you will learn standard patterns for structuring full backend applications in later sections.
The Python Standard Library
Python ships with a large "batteries included" standard library. This is a collection of modules that you can use without installing anything extra.
Some useful standard library modules for backend developers include:
| Module | Purpose |
|---|---|
os | Operating system interaction, paths, env vars |
pathlib | Object oriented file path handling |
sys | System-specific parameters and functions |
json | Encoding and decoding JSON |
datetime | Working with dates and times |
logging | Logging messages from your application |
subprocess | Running external commands |
uuid | Generating unique IDs |
hashlib | Hashing functions (useful in security topics) |
http | Basic HTTP tools (status codes, clients) |
Example: Encoding and decoding JSON, a very common backend task:
import json
data = {"id": 123, "name": "Alice"}
# Convert Python object to JSON string
json_text = json.dumps(data)
print(json_text) # {"id": 123, "name": "Alice"}
# Convert JSON string back to Python object
parsed = json.loads(json_text)
print(parsed["name"]) # AliceYou will later see how third party libraries extend this functionality, but the standard library already covers many needs.
Running Python Code Interactively
You do not always need a file to run Python. You can also use the interactive interpreter or a REPL (Read Eval Print Loop).
Start it in the terminal:
pythonYou will see something like:
Python 3.12.2 (main, Feb 28 2024, 10:00:00)
>>> Now you can type expressions:
>>> 1 + 2
3
>>> print("Hello backend")
Hello backend
Press Ctrl + D (on Linux/macOS) or Ctrl + Z then Enter (on Windows) to exit.
The interactive interpreter is useful for:
- Trying tiny pieces of code.
- Learning how a function behaves.
- Quickly exploring a library.
For longer code, you should write .py files and run them, because:
- Files can be committed to Git.
- Files can be tested.
- Files can be reused and imported elsewhere.
Example: A Tiny HTTP Client in Pure Python
To connect Python to web concepts you are learning, here is a very simple example that fetches data from an HTTP API.
Python has a basic HTTP module in the standard library, but beginners often use the third party requests library because it is easier. In later chapters we will use more modern tools, but this demonstrates Python quickly interacting with the web.
Install the requests library with:
pip install requests
Then create client.py:
import requests
def get_todo(todo_id: int) -> None:
url = f"https://jsonplaceholder.typicode.com/todos/{todo_id}"
response = requests.get(url)
print("Status code:", response.status_code)
print("Body:", response.json())
if __name__ == "__main__":
get_todo(1)Run:
python client.pyYou will see a JSON object printed. This is a simple but real backend-related task: calling an HTTP endpoint, checking the status code, and working with JSON data.
Even before you build servers, understanding how to consume APIs in Python gives you a practical feeling for the language.
Python Style and Readability
Python has a strong culture of code readability. There is a document called "PEP 8" that describes the standard style.
You do not need to memorize PEP 8, but you should know a few important points:
- Use 4 spaces for indentation, not tabs.
- Use lowercase_with_underscores for function and variable names.
def get_user_name():
user_name = "Alice"
return user_name- Keep lines reasonably short, typically under 79 or 88 characters.
- Name things clearly, for example
user_idinstead ofx.
There are tools that check and fix style automatically, for example:
| Tool | Purpose |
|---|---|
black | Automatic code formatter |
flake8 | Style and error checker |
isort | Sorts imports |
In real backend projects, these tools are usually part of the development workflow and CI.
How Python Fits into This Course
In this course, Python is your main backend language. Here is how the topics connect:
- Programming Fundamentals teaches concepts like variables, loops, and functions in a language agnostic way.
- Python for Backend Development (this section) focuses on how these concepts look and work in Python specifically.
- Introduction to Web Backends and FastAPI show you how to use Python to build web servers and APIs.
- Databases, ORM and Database Integration, and later sections show you how Python interacts with databases, caches, and other backend systems.
You should think of Python as the tool you will use to implement the backend concepts you learn elsewhere in the course.
For now, you only need to:
- Know that Python 3 is the version you care about.
- Understand that Python code is read and executed by the interpreter.
- Recognize basic Python syntax when you see it.
- Be comfortable running small Python programs from the command line.
The next chapters on installing Python and setting up environments will turn this understanding into a working local setup where you can start building real backend applications.
Views: 7
KAHIBARO