KAHIBARO
Discord Login Register

5.1 Introduction to Python

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:

python
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:

TaskPopular Python Library / Tool
Building APIsFastAPI, Flask, Django REST
Working with databasesSQLAlchemy, Django ORM
Sending HTTP requestsrequests, httpx
Handling background tasksCelery, RQ
Caching with Redisredis-py
Testingpytest

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:

python
name = input("What is your name? ")
print("Hello,", name)

A small function that adds two numbers:

python
def add(a, b):
    return a + b
result = add(3, 5)
print(result)  # 8

A simple loop:

python
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?

You can check your installed version with:

bash
python --version
# or sometimes
python3 --version

Python 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:

LayerExample with Python
Web server / reverse proxyNginx
Application serverUvicorn, Gunicorn
Web frameworkFastAPI, Django, Flask
Business logicYour Python code
DatabasePostgreSQL, MySQL, Redis, etc.
ORM / DB layerSQLAlchemy, Django ORM

For example, a very typical combination for modern APIs is:

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.

Example:

bash
  python app.py

The interpreter reads app.py and executes it line by line.

What does this mean for you as a backend developer?

Python Scripts vs Python Applications

In backend development you will see two common ways Python is used:

  1. 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:

python
   # 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:

bash
   python import_users.py
  1. 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:

python
   # 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:

ModulePurpose
osOperating system interaction, paths, env vars
pathlibObject oriented file path handling
sysSystem-specific parameters and functions
jsonEncoding and decoding JSON
datetimeWorking with dates and times
loggingLogging messages from your application
subprocessRunning external commands
uuidGenerating unique IDs
hashlibHashing functions (useful in security topics)
httpBasic HTTP tools (status codes, clients)

Example: Encoding and decoding JSON, a very common backend task:

python
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"])  # Alice

You 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:

bash
python

You will see something like:

text
Python 3.12.2 (main, Feb 28 2024, 10:00:00)
>>> 

Now you can type expressions:

text
>>> 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:

For longer code, you should write .py files and run them, because:

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:

bash
pip install requests

Then create client.py:

python
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:

bash
python client.py

You 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:

python
  def get_user_name():
      user_name = "Alice"
      return user_name

There are tools that check and fix style automatically, for example:

ToolPurpose
blackAutomatic code formatter
flake8Style and error checker
isortSorts 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:

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:

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

Comments

Please login to add a comment.

Don't have an account? Register now!