DEV Community

Cover image for Python for Web Developers: A Fast-Paced Guide to the Language
Austin W
Austin W

Posted on

Python for Web Developers: A Fast-Paced Guide to the Language

👋 Let's Connect! Follow me on GitHub for new projects.


Introduction

Python is a powerful, high-level programming language widely used in web development, automation, data science, and scripting. If you're already a full-stack web developer familiar with JavaScript, TypeScript, Node.js, and frameworks like React or Next.js, learning Python can open doors to backend development with Django, Flask, and FastAPI, as well as automation, data analysis, and AI.

This guide is a fast-paced walkthrough of Python, focusing on concepts that web developers need to know. If you’re comfortable with JavaScript, you’ll find Python’s syntax clean and easy to pick up.


1. Python Syntax & Basics

Hello World (No Semicolons, No Braces)

print("Hello, world!")  
Enter fullscreen mode Exit fullscreen mode

✔ No semicolons (;).

✔ No curly braces {}—uses indentation.

✔ No console.log(), just print().

Variables & Dynamic Typing

name = "Austin"  # No `let` or `const`
age = 30  # Python infers types
Enter fullscreen mode Exit fullscreen mode

✔ No need to declare var, let, or const.

✔ Types are inferred dynamically.

How Does const Work in Python?

Python does not have const like JavaScript, but you can define constants by using all-uppercase variable names as a convention.

PI = 3.14159  # By convention, constants are uppercase
Enter fullscreen mode Exit fullscreen mode

However, this does not enforce immutability. If you need true immutability, use a dataclass or a frozen set.

Data Types (Compared to JavaScript)

JavaScript Python
let num = 42; num = 42
const name = "Austin"; NAME = "Austin"
let arr = [1, 2, 3]; arr = [1, 2, 3]
let obj = {key: "value"}; obj = {"key": "value"}

2. Control Flow (Loops & Conditionals)

If/Else

x = 10

if x > 5:
    print("X is large")
elif x == 5:
    print("X is five")
else:
    print("X is small")
Enter fullscreen mode Exit fullscreen mode

✔ No parentheses () needed for conditions.

✔ Uses indentation instead of {}.

Loops (For & While)

# Loop over a list
for num in [1, 2, 3]:
    print(num)

# While loop
x = 5
while x > 0:
    print(x)
    x -= 1
Enter fullscreen mode Exit fullscreen mode

for loops iterate directly over lists/arrays.

while loops work like JavaScript.


3. Functions & Lambda Expressions

Defining Functions

def greet(name):
    return f"Hello, {name}!"

print(greet("Austin"))  
Enter fullscreen mode Exit fullscreen mode

def replaces function.

✔ No {}, just indentation.

Lambda (Arrow Function Equivalent)

add = lambda x, y: x + y
print(add(5, 10))  # Output: 15
Enter fullscreen mode Exit fullscreen mode

✔ Equivalent to JavaScript’s arrow function:

const add = (x, y) => x + y;
Enter fullscreen mode Exit fullscreen mode

4. Python Collections (Lists, Dicts, Sets)

JavaScript Python Equivalent
let arr = [1, 2, 3]; arr = [1, 2, 3] # List
let obj = { key: "value" }; obj = {"key": "value"} # Dictionary
const unique = new Set([1, 2, 3]); unique = {1, 2, 3} # Set

Lists (Like Arrays)

nums = [1, 2, 3]
nums.append(4)  # Add item
nums.remove(2)  # Remove item
print(nums)  # Output: [1, 3, 4]
Enter fullscreen mode Exit fullscreen mode

Dictionaries (Like Objects)

user = {"name": "Austin", "age": 30}
print(user["name"])  # Output: Austin
Enter fullscreen mode Exit fullscreen mode

5. Object-Oriented Programming (OOP) in Python

Defining a Class

class Person:
    def __init__(self, name):
        self.name = name

    def greet(self):
        return f"Hello, my name is {self.name}"

p = Person("Austin")
print(p.greet())  # Output: Hello, my name is Austin
Enter fullscreen mode Exit fullscreen mode

__init__ is the constructor (like constructor() in JS).

self is like this.


6. Python for Web Development

Django (Full-Stack Framework)

pip install django
django-admin startproject myproject
Enter fullscreen mode Exit fullscreen mode

Django is a batteries-included backend framework.

✔ Built-in ORM, authentication, and templating.

Flask (Lightweight API Framework)

from flask import Flask

app = Flask(__name__)

@app.route("/")
def home():
    return "Hello from Flask!"

app.run(debug=True)
Enter fullscreen mode Exit fullscreen mode

Flask is minimal and great for APIs.

FastAPI (High-Performance API)

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"message": "Hello from FastAPI!"}
Enter fullscreen mode Exit fullscreen mode

FastAPI is async-native and perfect for microservices.


7. Python & Databases

SQLite Example (Django & Flask Compatible)

import sqlite3

conn = sqlite3.connect("database.db")
cursor = conn.cursor()

cursor.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)")
cursor.execute("INSERT INTO users (name) VALUES ('Austin')")
conn.commit()
Enter fullscreen mode Exit fullscreen mode

SQLite is built-in, no installation needed.


8. Asynchronous Programming in Python

Async/Await (Similar to JavaScript)

import asyncio

async def fetch_data():
    await asyncio.sleep(2)
    return "Data received"

async def main():
    result = await fetch_data()
    print(result)

asyncio.run(main())
Enter fullscreen mode Exit fullscreen mode

✔ Uses async/await like JavaScript.

asyncio is the event loop equivalent of Node.js.


9. Python Package Management

Task JavaScript Python
Install Package npm install axios pip install requests
Create Virtual Environment nvm use python -m venv env
Run Script node script.js python script.py

Use pip for package management.

Virtual environments (venv) isolate dependencies.


10. Best Practices for Python Development

Writing clean, efficient, and maintainable Python code is essential for long-term scalability. Here are the key best practices that every Python developer should follow:

Follow PEP 8 (Python Style Guide)

Python has an official style guide called PEP 8, which provides conventions for writing Python code.

✔ Use 4 spaces per indentation level (not tabs).

✔ Limit line length to 79 characters.

✔ Use meaningful variable and function names.

✔ Use snake_case for variable and function names, and PascalCase for class names.

Example:

# Good (PEP 8 Compliant)
def calculate_area(radius):
    return 3.14 * radius ** 2

# Bad
def calcArea(r): return 3.14*r**2
Enter fullscreen mode Exit fullscreen mode

Use Virtual Environments

Python’s virtual environments isolate dependencies for different projects, preventing conflicts.

Creating a Virtual Environment

python -m venv venv
Enter fullscreen mode Exit fullscreen mode

Activating the Virtual Environment

  • Windows:
  venv\Scripts\activate
Enter fullscreen mode Exit fullscreen mode
  • Mac/Linux:
  source venv/bin/activate
Enter fullscreen mode Exit fullscreen mode

Deactivating the Virtual Environment

deactivate
Enter fullscreen mode Exit fullscreen mode

Use Type Hinting for Readable Code

Python is dynamically typed, but you can use type hints to improve code clarity.

Example:

def add(x: int, y: int) -> int:
    return x + y
Enter fullscreen mode Exit fullscreen mode

✔ This makes the code self-documenting.

✔ Helps tools like mypy catch type errors.


Write Readable Docstrings

Always document your functions and classes using docstrings (""" """).

Example:

def greet(name: str) -> str:
    """
    Returns a greeting message for the given name.

    :param name: The name to greet.
    :return: Greeting string.
    """
    return f"Hello, {name}!"
Enter fullscreen mode Exit fullscreen mode

✔ Use triple quotes for multi-line docstrings.

✔ Explain parameters, return values, and purpose.


11. Commenting in Python

Python uses # for single-line comments and triple quotes (""" """) for docstrings.

Single-Line Comments

# This is a single-line comment
print("Hello, world!")  # Inline comment
Enter fullscreen mode Exit fullscreen mode

Multi-Line Docstrings

"""
This is a multi-line docstring.
It is often used for documentation.
"""
print("Hello, world!")
Enter fullscreen mode Exit fullscreen mode

Use comments only where necessary—good code should be self-explanatory.

Docstrings are not comments—they are for documentation and can be accessed with help().


12. Common Python Imports for Web Development

Here are some of the most common Python imports used in web development:

Built-in Modules

Feature Import
System operations import os
File handling import pathlib
Environment variables import dotenv
Dates & time import datetime
JSON parsing import json
HTTP requests import requests
Logging import logging

Example Usage

import os
import json
import requests

response = requests.get("https://api.example.com/data")
data = response.json()
print(data)
Enter fullscreen mode Exit fullscreen mode

13. Setting Up a requirements.txt File

A requirements.txt file is similar to package.json in Node.js—it lists dependencies for a Python project.

Creating a requirements.txt File

pip freeze > requirements.txt
Enter fullscreen mode Exit fullscreen mode

Installing Dependencies from requirements.txt

pip install -r requirements.txt
Enter fullscreen mode Exit fullscreen mode

✔ This ensures that all team members and deployment environments have the same package versions.


14. Writing & Running Tests in Python

Python has built-in testing with unittest, but pytest is another option - one that aims for simplicity.

Basic Test with unittest

import unittest

def add(x, y):
    return x + y

class TestMath(unittest.TestCase):
    def test_add(self):
        self.assertEqual(add(2, 3), 5)

if __name__ == "__main__":
    unittest.main()
Enter fullscreen mode Exit fullscreen mode

✔ Use assertEqual() to check expected results.


Testing with pytest

Install pytest:

pip install pytest
Enter fullscreen mode Exit fullscreen mode

Example test_math.py

def add(x, y):
    return x + y

def test_add():
    assert add(2, 3) == 5
    assert add(-1, 1) == 0
Enter fullscreen mode Exit fullscreen mode

Run all tests:

pytest
Enter fullscreen mode Exit fullscreen mode

No need to use classes—just use assert.

Auto-discovers test files named test_*.py.


15. Fetching Data with API Calls in Python

Python uses requests to fetch data, similar to fetch() in JavaScript.

Basic API Request

import requests

response = requests.get("https://jsonplaceholder.typicode.com/posts")
data = response.json()
print(data)
Enter fullscreen mode Exit fullscreen mode

requests.get() is like fetch(url) in JavaScript.

.json() works the same way in both languages.

Sending Data (POST Request)

payload = {"title": "Hello", "body": "World"}
response = requests.post("https://jsonplaceholder.typicode.com/posts", json=payload)

print(response.status_code)  # 201 Created
print(response.json())
Enter fullscreen mode Exit fullscreen mode

✔ Use json=payload instead of data=payload to send JSON.


16. Logging in Python

Logging is essential for debugging and monitoring applications.

Basic Logging

import logging

logging.basicConfig(level=logging.INFO)
logging.info("This is an info message")
logging.warning("This is a warning")
logging.error("This is an error")
Enter fullscreen mode Exit fullscreen mode

✔ Works like console.log() but supports different log levels.

Writing Logs to a File

logging.basicConfig(filename="app.log", level=logging.DEBUG)
logging.debug("Debugging info")
Enter fullscreen mode Exit fullscreen mode

✔ Saves logs for later analysis.


17. Raising & Handling Errors in Python Logging

When an error occurs, Python lets you raise exceptions or log errors.

Raising an Exception

def divide(x, y):
    if y == 0:
        raise ValueError("Cannot divide by zero")
    return x / y

print(divide(10, 2))  # Works
print(divide(10, 0))  # Raises ValueError
Enter fullscreen mode Exit fullscreen mode

✔ Use raise to manually trigger an error.

Logging Errors

Instead of crashing, log errors with a traceback:

import logging

logging.basicConfig(filename="error.log", level=logging.ERROR)

try:
    result = 10 / 0
except ZeroDivisionError as e:
    logging.error("An error occurred", exc_info=True)
Enter fullscreen mode Exit fullscreen mode

exc_info=True logs the full error traceback.


Conclusion

Python is a useful language for web developers, expanding your stack beyond JavaScript. Whether you’re building APIs with FastAPI, full-stack apps with Django, or automating tasks, Python makes it easy and powerful.

🚀 Next Steps: Try building a small Flask or FastAPI project today!


Tags

Python #WebDev #Django #Flask #FastAPI

Meta Description

A fast-paced guide to Python for web developers! Learn how to use Python for full-stack development, APIs, databases, async programming, and more. 🚀


TLDR – Highlights for Skimmers

  • Python syntax is simpler than JavaScript—no semicolons, indentation replaces {}.
  • const does not exist in Python; uppercase variables are used for constants.
  • Lists ([]) are like arrays, but dictionaries ({}) are not JavaScript objects.
  • Classes & objects are similar, but Python uses self instead of this.
  • Python async/await requires asyncio, unlike JavaScript’s built-in event loop.
  • Django, Flask, and FastAPI are top backend frameworks for Python web dev.

💬 Do you use Python in web dev? Share your experience in the comments!

Top comments (1)

Collapse
 
austinwdigital profile image
Austin W

If you’re coming from a JavaScript/Node.js background, what was the most surprising difference when learning Python? Let’s compare notes!