Python · lesson 1 of 34
Beginner
16- 1 Introduction to Python
- 2 Setting Up Python
- 3 Python Variables and Type System
- 4 Python Data Types
- 5 Python Operators
- 6 Python Strings
- 7 Control Flow in Python
- 8 Python Functions and Parameters
- 9 Python Data Structures
- 10 Python Collections
- 11 Python Modules and Packages
- 12 Object-Oriented Programming in Python
- 13 Encapsulation and Name Mangling in Python
- 14 Polymorphism and Duck Typing in Python
- 15 Abstraction with Abstract Base Classes in Python
- 21 Building a Python CLI Tool
Intermediate
12- 16 Multiple Inheritance and MRO in Python
- 17 Composition vs Inheritance in Python
- 18 Python Dataclasses
- 19 Error Handling in Python
- 20 File I/O, pathlib, and JSON in Python
- 22 Python Decorators and Closures
- 23 Python Generators
- 24 Python Context Managers
- 25 Python Concurrency
- 27 Testing Python Code
- 28 Python Security
- 34 Python Interview Prep
Advanced
6Introduction to Python
Learn what Python is, its history, and real-world use cases — a practical Python tutorial for beginners starting from scratch.
By SkillByExample · Updated
What Is Python?
Python is a high-level, interpreted, general-purpose programming language created by Guido van Rossum and first released in 1991. The name comes from Monty Python’s Flying Circus — Guido wanted something fun to work with. Python prioritizes developer productivity: its readable syntax reduces the cognitive overhead of writing code, so you can focus on solving problems rather than fighting the language.
Its design philosophy, captured in The Zen of Python (import this), prioritizes readability and simplicity:
“There should be one — and preferably only one — obvious way to do it.”
A Quick History
Understanding Python’s history helps explain why you might encounter both python and python3 commands, or why some older tutorials use outdated syntax. The Python 2 to Python 3 transition was a deliberate breaking change to fix deep design mistakes — everything you learn today targets Python 3.
| Year | Milestone |
|---|---|
| 1991 | Python 0.9.0 released |
| 2000 | Python 2.0 — list comprehensions, garbage collection |
| 2008 | Python 3.0 — Unicode strings, cleaner syntax, broke compatibility with Python 2 |
| 2020 | Python 2 officially end-of-life |
| 2022+ | Python 3.11 (October 2022) onward ships major speed improvements (up to 60% faster than 3.10 on some benchmarks) |
Where Python Is Used
Python’s versatility is one of its biggest strengths. Unlike languages that dominate a single domain, Python is productively used across web development, machine learning, automation, and scientific computing — often by the same team.
Web Development
Frameworks like Django and FastAPI power companies like Instagram, Dropbox, and thousands of startups. FastAPI in particular is used when you need high-performance async REST or GraphQL APIs — it generates OpenAPI documentation automatically and uses Python type hints for request validation.
from fastapi import FastAPI
from fastapi.testclient import TestClient
app = FastAPI()
@app.get("/users/{user_id}")
async def get_user(user_id: int): # the type hint drives validation
return {"user_id": user_id, "name": "Alice"}
client = TestClient(app) # calls the app in-process, no server needed
print(client.get("/users/42").json())
r = client.get("/users/abc")
print(r.status_code, r.json()["detail"][0]["msg"])
$ python users_api.py
{'user_id': 42, 'name': 'Alice'}
422 Input should be a valid integer, unable to parse string as an integer
The whole endpoint is the four lines from @app.get down. Because user_id is annotated as int, FastAPI converted the "42" in the URL to a number and rejected "abc" with a 422 before your function ever ran. (FastAPI and httpx2, which TestClient needs, are third-party: pip install fastapi httpx2.)
Data Science and Machine Learning
NumPy, Pandas, scikit-learn, PyTorch, and TensorFlow have made Python the default language for data work. The ecosystem is so mature that switching to another language for ML would mean rebuilding years of tooling from scratch.
import io
import pandas as pd
csv = io.StringIO("""product,revenue
laptop,1200
mouse,25
laptop,1100
keyboard,80
mouse,30
""")
df = pd.read_csv(csv) # a real file path works the same way
top_products = (
df.groupby("product")["revenue"]
.sum()
.sort_values(ascending=False)
.head(10)
)
print(top_products)
$ python top_products.py
product
laptop 2300
keyboard 80
mouse 55
Name: revenue, dtype: int64
One chained expression grouped the rows by product, summed each group and ranked the totals. The result is a pandas Series, which is why it prints with the product index on the left and a Name: footer. (pip install pandas first.)
Automation and Scripting
Python replaced Bash for complex automation tasks because it handles errors, data structures, and APIs far more cleanly. You can scrape websites, orchestrate cloud infrastructure (Ansible, Pulumi), or write CI/CD tooling in a fraction of the time it would take in other languages.
import os
import pathlib
import shutil
import tempfile
import time
base = pathlib.Path(tempfile.mkdtemp()) # a scratch folder standing in for /var/log/app
logs, archive = base / "logs", base / "archive"
logs.mkdir(); archive.mkdir()
for name, age_days in [("app.log", 1), ("old.log", 10), ("older.log", 30)]:
f = logs / name
f.write_text("log line\n")
mtime = time.time() - age_days * 86400
os.utime(f, (mtime, mtime)) # backdate the file's modification time
cutoff = time.time() - 7 * 86400
for log in logs.glob("*.log"): # archive logs older than 7 days
if log.stat().st_mtime < cutoff:
shutil.move(log, archive / log.name)
print("kept:", sorted(p.name for p in logs.iterdir()))
print("archived:", sorted(p.name for p in archive.iterdir()))
$ python archive_logs.py
kept: ['app.log']
archived: ['old.log', 'older.log']
Most of the script is setup that fakes old files; the real job is the four-line loop at the end. pathlib gives paths with methods (glob, stat, / for joining), and the results are sorted because glob() returns files in whatever order the filesystem lists them.
System Administration and DevOps
Tools like Ansible and SaltStack are written in Python, and AWS CDK has first-class Python bindings. Most cloud provider CLIs (AWS, GCP, Azure) are Python-based and expose rich Python SDKs, making Python the natural choice for infrastructure automation.
Finance and Quant
Bloomberg, JPMorgan, and most hedge funds use Python for modeling, backtesting, and risk analysis. pandas, NumPy and the QuantLib Python bindings are the usual building blocks for that work.
Python vs. Other Languages
Python’s main trade-off is raw execution speed for developer speed. For the vast majority of real-world tasks — web APIs, data pipelines, automation — the bottleneck is I/O or an external service, not CPU, so Python’s interpreted overhead never shows up.
| Language | Strength | When to Pick Python Instead |
|---|---|---|
| JavaScript | Browser, Node.js | Server-side ML, data pipelines, scripting |
| Java | Enterprise, JVM ecosystem | Rapid prototyping, data science |
| Go | Performance, concurrency | Simpler codebases, ML/AI work |
| R | Statistical analysis | Production systems, general backend |
Career Opportunities
Python consistently ranks #1 or #2 on the TIOBE Index and Stack Overflow surveys. Strong Python skills open doors across multiple well-compensated engineering tracks, and the demand continues to grow as ML and automation become standard parts of every engineering organization.
- Data Engineer — build pipelines with Airflow, Spark, dbt
- ML Engineer — train, optimize, and serve models at scale
- Backend Developer — APIs, microservices, background workers
- DevOps/Platform Engineer — infrastructure automation, Kubernetes operators
- Security Engineer — penetration testing, exploit development, security tooling
Your First Python Program
A Python script is just a text file ending in .py. The if __name__ == "__main__": guard is a standard pattern that separates reusable module code from executable script code — it only runs when the file is invoked directly, not when it’s imported by another module.
# hello.py
def greet(name: str) -> str:
# Type hints document what the function expects and returns
return f"Hello, {name}! Welcome to Python."
if __name__ == "__main__":
# This block is skipped when the file is imported as a module
print(greet("World"))
$ python hello.py
Hello, World! Welcome to Python.
The greet function takes a name parameter, formats it into a greeting, and returns the string. print() then writes it to stdout. Swap "World" for any name and the output changes. Output in this lesson is from Python 3.13; the FastAPI example used FastAPI 0.142 and the pandas example pandas 3.0.
Practice
1. Change greet to accept a title parameter that defaults to "Dr." and prepend it to the name. Predict the output, then run it.
Solution
def greet(name: str, title: str = "Dr.") -> str:
return f"Hello, {title} {name}! Welcome to Python."
if __name__ == "__main__":
print(greet("Smith"))
print(greet("Smith", title="Prof."))
$ python hello.py
Hello, Dr. Smith! Welcome to Python.
Hello, Prof. Smith! Welcome to Python.
A default value is used only when the caller leaves the argument out; passing title= by keyword overrides it.
2. Add a farewell function and call both greet and farewell in the __main__ block.
Solution
def greet(name: str) -> str:
return f"Hello, {name}! Welcome to Python."
def farewell(name: str) -> str:
return f"Goodbye, {name}! Thanks for visiting."
if __name__ == "__main__":
print(greet("Alice"))
print(farewell("Alice"))
$ python hello.py
Hello, Alice! Welcome to Python.
Goodbye, Alice! Thanks for visiting.
Defining a function only creates it; nothing prints until the __main__ block calls it. The calls run top to bottom, so the order of the output follows the order of the calls, not the definitions.
3. Import hello.py from a second script. Does the print inside its if __name__ == "__main__": block run?
Solution
import pathlib
pathlib.Path("hello.py").write_text(
'def greet(name):\n'
' return f"Hello, {name}! Welcome to Python."\n'
'print("hello.py sees __name__ =", repr(__name__))\n'
'if __name__ == "__main__":\n'
' print(greet("World"))\n'
)
import hello # runs hello.py top to bottom, as a module
print(hello.greet("importer"))
$ python use_hello.py
hello.py sees __name__ = 'hello'
Hello, importer! Welcome to Python.
When imported, hello.py runs with __name__ set to "hello", not "__main__", so the guarded print is skipped while greet is still defined and usable. Run python hello.py directly and the guard is true instead.
What’s Next
The next tutorial covers installing Python, setting up a virtual environment, and configuring VS Code — the practical foundation before writing real code.