TechLead
Lesson 1 of 25
5 min read
Python

Python Fundamentals

Learn the basics of Python programming including syntax, execution model, and core concepts

Introduction to Python

Python is one of the most popular and versatile programming languages in the world. Created by Guido van Rossum and first released in 1991, Python has grown into a powerhouse for web development, data science, machine learning, automation, and more. Its clean syntax and readability make it an excellent first language and a favorite among experienced developers alike.

Why Python?

  • Readable Syntax: Python reads like English, reducing the learning curve and maintenance burden
  • Versatile: Used in web development, data science, AI/ML, DevOps, scripting, and more
  • Massive Ecosystem: Over 400,000 packages on PyPI covering virtually every use case
  • Community: One of the largest developer communities with extensive documentation and tutorials
  • Cross-Platform: Runs on Windows, macOS, Linux, and many other platforms

How Python Works

Python is an interpreted language. When you run a Python program, the Python interpreter reads your source code, compiles it to bytecode (an intermediate representation), and then executes that bytecode on the Python Virtual Machine (PVM). This is different from compiled languages like C or Go, where the source code is compiled to machine code before execution.

# Your first Python program
print("Hello, World!")

# Python can do math
result = 42 * 2
print(f"The answer is {result}")

# Python is dynamically typed
name = "Alice"       # string
age = 30             # integer
height = 5.7         # float
is_student = False   # boolean

print(f"{name} is {age} years old and {height}ft tall")

Python Versions: Python 2 vs Python 3

Python 2 reached its end of life on January 1, 2020. All new projects should use Python 3. As of 2026, the latest stable version is Python 3.13. Key differences include print being a function in Python 3, true integer division, Unicode strings by default, and many syntax improvements like f-strings and the walrus operator.

Installing Python

Most systems come with Python pre-installed, but you should ensure you have Python 3.10 or later for the best experience with modern features like structural pattern matching and improved error messages.

# Check your Python version
# In terminal:
# python3 --version
# Python 3.13.x

# On macOS with Homebrew:
# brew install python@3.13

# On Ubuntu/Debian:
# sudo apt update
# sudo apt install python3.13

# On Windows:
# Download from python.org or use winget:
# winget install Python.Python.3.13

The Python REPL

The Python REPL (Read-Eval-Print Loop) is an interactive shell where you can type Python code and see results immediately. It is invaluable for experimentation, debugging, and learning. Simply type python3 in your terminal to start it.

>>> 2 + 2
4
>>> "hello".upper()
'HELLO'
>>> [x**2 for x in range(5)]
[0, 1, 4, 9, 16]
>>> help(str.split)
# Shows documentation for the split method

Python Script Structure

A Python script is simply a text file with a .py extension. Unlike many languages, Python does not require a main function or boilerplate. Code at the top level of a module executes when the file is run. However, the if __name__ == "__main__" idiom is a best practice for scripts that may also be imported as modules.

# app.py - A well-structured Python script

import sys
from datetime import datetime


def greet(name: str) -> str:
    """Return a greeting message."""
    current_hour = datetime.now().hour
    if current_hour < 12:
        period = "morning"
    elif current_hour < 17:
        period = "afternoon"
    else:
        period = "evening"
    return f"Good {period}, {name}!"


def main():
    """Entry point for the script."""
    if len(sys.argv) > 1:
        name = sys.argv[1]
    else:
        name = "World"
    
    message = greet(name)
    print(message)


if __name__ == "__main__":
    main()

Indentation and Code Blocks

Python uses indentation to define code blocks instead of curly braces or keywords. This is not merely a style choice — it is part of the language syntax. The standard convention is 4 spaces per indentation level. Mixing tabs and spaces will cause errors.

# Indentation defines blocks
def calculate_grade(score):
    if score >= 90:
        grade = "A"
        print("Excellent!")
    elif score >= 80:
        grade = "B"
        print("Good job!")
    elif score >= 70:
        grade = "C"
        print("Not bad")
    else:
        grade = "F"
        print("Needs improvement")
    return grade

# Nested indentation
for i in range(3):
    for j in range(3):
        if i == j:
            print(f"({i},{j}) is on the diagonal")

Comments and Docstrings

Python supports single-line comments with # and multi-line documentation strings (docstrings) with triple quotes. Docstrings are not just comments — they are accessible at runtime via the __doc__ attribute and are used by tools like Sphinx to generate documentation.

# This is a single-line comment

"""
This is a module-level docstring.
It describes what this module does.
"""

def fibonacci(n: int) -> list[int]:
    """
    Generate the first n Fibonacci numbers.
    
    Args:
        n: The number of Fibonacci numbers to generate.
        
    Returns:
        A list of the first n Fibonacci numbers.
        
    Examples:
        >>> fibonacci(5)
        [0, 1, 1, 2, 3]
    """
    if n <= 0:
        return []
    fib = [0, 1]
    while len(fib) < n:
        fib.append(fib[-1] + fib[-2])
    return fib[:n]

Key Takeaways

  • Python is interpreted: No compilation step needed — write and run immediately
  • Indentation matters: Use 4 spaces consistently for code blocks
  • Use Python 3: Always use Python 3.10+ for modern features
  • The REPL is your friend: Use it for experimentation and quick testing
  • Write docstrings: Document your functions and modules with triple-quoted strings

Continue Learning