Beginners Guide: Overview, Features, and Learning Path
This page provides an overview of Python and guides you through the order in which to learn each feature. It covers what Python is, its key characteristics, and how code is executed, giving you a clear learning path.
What is Python
Python is a general-purpose programming language developed by Guido van Rossum in 1991. It was designed with readability and simplicity as the top priority, and is used in a wide range of fields including web applications, data analysis, machine learning, and automation scripts.
The name comes not from the snake but from the British comedy show "Monty Python."
Where Python fits in
Python follows the philosophy "There should be one — and preferably only one — obvious way to do it" (The Zen of Python). This encourages consistent coding styles, making code written by different developers easy to read and understand.
Python's Features — Strengths and Trade-offs
Indentation is part of the syntax
Most languages use {} to define blocks, but Python uses indentation. Incorrect indentation causes an error.
# Python block — expressed with indentation
def greet(name):
if name == "Goku":
print("Yo! I'm Goku!")
else:
print("Hello, " + name)
// Comparison: JavaScript block — expressed with {}
function greet(name) {
if (name === "Goku") {
console.log("Yo! I'm Goku!");
} else {
console.log("Hello, " + name);
}
}
Because consistent indentation is required, Python code tends to look similar no matter who writes it — a feature that contributes to readability.
Dynamic typing
Python is a dynamically typed language. You do not need to declare a type for a variable; the type is determined automatically based on the value assigned.
power_level = 9000 # treated as an integer power_level = "over 9000" # reassigning a string causes no error print(type(power_level)) # <class 'str'>
Since Python 3.5, you can also add type hints to variables and functions. Type hints are not enforced at runtime, but tools like mypy can use them for static type checking.
def add(a: int, b: int) -> int:
return a + b
Rich standard library
Python is often described as "Batteries Included." Without installing anything extra, you can handle file I/O, JSON processing, HTTP communication, regular expressions, date and time operations, and much more.
Strengths and trade-offs
| Aspect | Strength | Trade-off / Note |
|---|---|---|
| Ease of writing | Simple syntax; write code quickly | Indentation mistakes cause errors |
| Execution speed | Fast development cycle | Slower than C/C++/Go at runtime |
| Types | No type declarations needed | Type errors may surface only at runtime |
| Ecosystem | Rich libraries for ML and data analysis | Dependency management can get complex |
| Concurrency | asyncio enables non-blocking I/O | GIL (Global Interpreter Lock) limits true parallel execution |
| Distribution | Easy to share as a script | Requires a Python runtime on the target machine |
How Python Executes Code
Python is an interpreted language. Unlike compiled languages such as C that translate source code directly into machine code, the Python interpreter reads and executes source code line by line.
Internally, Python first compiles the source code into bytecode — an intermediate format. Bytecode is saved as .pyc files inside the __pycache__/ directory and reused on subsequent runs if the source has not changed.
Running a .py file
# sample.py
name = "Son Goku"
print("My name is " + name)
python sample.py My name is Son Goku
Interactive mode (REPL)
Python has an interactive mode where you can type and execute code one line at a time. It is called a REPL (Read-Eval-Print Loop) and is useful for quick experiments and verifying behavior.
python Python 3.11.0 (...) >>> name = "Vegeta" >>> print(name) Vegeta >>> 2 + 3 5
>>> is the prompt. To exit interactive mode, type exit() or press Ctrl + D.
Python versions
There are two major lineages: Python 2 and Python 3. Python 2 reached end of life in January 2020, so all current development uses Python 3. The two versions are not compatible — even basic syntax like the print statement differs.
| Python 2 | Python 3 | |
|---|---|---|
print "hello" (statement) | print("hello") (function) | |
| Integer division | 5 / 2 = 2 (truncated) | 5 / 2 = 2.5 (float) |
| Strings | ASCII by default | Unicode (UTF-8) by default |
| Support | Ended January 2020 | Current standard |
Variables and Types
Python variables require no type declaration. The type is determined by the value assigned.
name = "Son Goku" # str (string) power_level = 9000 # int (integer) height = 175.5 # float (floating-point number) is_saiyan = True # bool (boolean) partner = None # NoneType (no value)
Use the type() function to check the type of a value.
print(type(name)) # <class 'str'> print(type(power_level)) # <class 'int'> print(type(is_saiyan)) # <class 'bool'>
Type conversion
Use conversion functions to change a value to a different type.
num_str = "100" num_int = int(num_str) # string → integer num_float = float(num_str) # string → float back_str = str(num_int) # integer → string
For details on type conversion, see int() / float() / str() / bool().
Type hints (Python 3.5+)
You can annotate variables and functions with type information. Type hints are not enforced at runtime, but tools like mypy can use them for static type checking.
def power_up(fighter: str, amount: int) -> str:
return fighter + "'s power level rose by " + str(amount)
To check types at runtime, use isinstance(). For details, see isinstance() / type().
Lists, Tuples, Sets, and Dicts
Python has four major collection types.
| Type | Syntax | Characteristics |
|---|---|---|
| list | [1, 2, 3] | Ordered, mutable, allows duplicates |
| tuple | (1, 2, 3) | Ordered, immutable, allows duplicates |
| set | {1, 2, 3} | Unordered, mutable, no duplicates |
| dict | {"key": "value"} | Key-value pairs, mutable |
# list — supports adding and modifying elements
fighters = ["Son Goku", "Vegeta", "Piccolo"]
fighters.append("Krillin")
fighters[0] = "Gohan"
# tuple — immutable (good for fixed data like coordinates or RGB values)
position = (100, 200)
# set — duplicates are automatically removed
unique_races = {"Saiyan", "Namekian", "Human", "Saiyan"}
print(unique_races) # {'Human', 'Namekian', 'Saiyan'} (duplicate removed)
# dict — access values by key
character = {
"name": "Bulma",
"age": 16,
"team": "Capsule Corporation"
}
print(character["name"]) # Bulma
For list operations, see list.append() / extend() / insert(). For dict operations, see dict.get() / setdefault().
String Operations
Python's string type (str) comes with many built-in methods.
name = " Son Goku "
print(name.strip()) # "Son Goku" (remove surrounding whitespace)
print(name.upper()) # " SON GOKU " (uppercase)
print(name.lower()) # " son goku " (lowercase)
print(name.replace("Goku", "Gohan")) # " Son Gohan "
words = "Super,Saiyan,God"
parts = words.split(",") # ["Super", "Saiyan", "God"]
joined = "-".join(parts) # "Super-Saiyan-God"
f-strings — Python 3.6+
f-strings are the most readable way to embed variables in strings and are widely used in modern Python.
name = "Vegeta"
power = 18000
# f-string
message = f"{name}'s power level is {power}"
print(message) # Vegeta's power level is 18000
# expressions are allowed inside the braces
print(f"{name} doubled: {power * 2}") # Vegeta doubled: 36000
For details on individual string methods, see pages such as str.upper() / lower() / swapcase().
Functions (def and lambda)
Functions are defined with the def keyword.
def power_up(name, amount=1000):
return name + "'s power level rose by " + str(amount)
print(power_up("Son Goku")) # Son Goku's power level rose by 1000
print(power_up("Vegeta", 5000)) # Vegeta's power level rose by 5000
amount=1000 is a default argument. It can be omitted when calling the function.
Keyword arguments
def introduce(name, age, team):
print(f"{name}, age {age}, team: {team}")
# Specify arguments by name (order does not matter)
introduce(age=16, name="Bulma", team="Capsule Corporation")
lambda — anonymous functions
For small, single-expression functions, use lambda.
# Written with def
def double(x):
return x * 2
# Written with lambda
double = lambda x: x * 2
print(double(5)) # 10
# Typical use: key argument of sorted()
fighters = [("Piccolo", 3500), ("Son Goku", 9000), ("Krillin", 1770)]
sorted_fighters = sorted(fighters, key=lambda f: f[1])
print(sorted_fighters)
# [('Krillin', 1770), ('Piccolo', 3500), ('Son Goku', 9000)]
For details on lambda, see lambda.
Classes and Inheritance
Python supports object-oriented programming. Classes are defined with the class keyword.
class Fighter:
def __init__(self, name, power_level):
self.name = name
self.power_level = power_level
def power_up(self, amount):
self.power_level += amount
print(f"{self.name}'s power level rose by {amount}! -> {self.power_level}")
goku = Fighter("Son Goku", 416)
goku.power_up(9000) # Son Goku's power level rose by 9000! -> 9416
__init__ is the constructor (initializer) and is called automatically when an instance is created. self is a reference to the instance itself.
Inheritance
class SuperSaiyan(Fighter):
def __init__(self, name, power_level, multiplier):
super().__init__(name, power_level)
self.multiplier = multiplier
def transform(self):
self.power_level *= self.multiplier
print(f"{self.name} transformed into a Super Saiyan! Power level: {self.power_level}")
vegeta = SuperSaiyan("Vegeta", 3000000, 50)
vegeta.transform() # Vegeta transformed into a Super Saiyan! Power level: 150000000
super() lets you call methods from the parent class. For details, see class / __init__ / self and Inheritance / super().
File Operations
Use the open() function to read from and write to files. The with statement ensures the file is closed automatically.
# Write to a file
with open("fighters.txt", "w", encoding="utf-8") as f:
f.write("Son Goku\n")
f.write("Vegeta\n")
# Read from a file
with open("fighters.txt", "r", encoding="utf-8") as f:
for line in f:
print(line.strip()) # Son Goku / Vegeta
"w" is write mode (creates a new file or overwrites an existing one). "r" is read mode. Specifying encoding="utf-8" ensures non-ASCII characters are handled correctly.
For details on file operations, see open() / read() / write() and File reading and writing.
Exception Handling (try/except)
Use try/except to handle errors gracefully.
def divide(a, b):
try:
result = a / b
return result
except ZeroDivisionError:
print("Cannot divide by zero")
return None
except TypeError as e:
print(f"Type error: {e}")
return None
finally:
print("Processing complete")
print(divide(10, 2)) # 5.0 / Processing complete
print(divide(10, 0)) # Cannot divide by zero / Processing complete / None
The finally block always runs regardless of whether an exception occurred. It is commonly used to close files or release resources.
For creating custom exceptions, see raise / Custom exceptions. For the list of built-in exceptions, see Built-in exceptions.
List Comprehensions
List comprehensions let you generate a list in a single expression. They are idiomatic Python and widely used.
# Traditional approach
squares = []
for i in range(1, 6):
squares.append(i ** 2)
# [1, 4, 9, 16, 25]
# List comprehension
squares = [i ** 2 for i in range(1, 6)]
# [1, 4, 9, 16, 25]
# With a condition (even numbers only)
even_squares = [i ** 2 for i in range(1, 11) if i % 2 == 0]
# [4, 16, 36, 64, 100]
The same style works for dict and set comprehensions.
fighters = ["Son Goku", "Vegeta", "Piccolo", "Krillin"]
# Dict comprehension — name to character count mapping
name_lengths = {name: len(name) for name in fighters}
# {'Son Goku': 8, 'Vegeta': 6, 'Piccolo': 7, 'Krillin': 7}
For details on list comprehensions, see List comprehensions. For dict comprehensions, see Dict comprehensions.
Iterators and Generators
Python's for loop is built on the iterator protocol. An iterator is an object that can return its elements one at a time.
fighters = ["Son Goku", "Vegeta", "Piccolo"] it = iter(fighters) print(next(it)) # Son Goku print(next(it)) # Vegeta print(next(it)) # Piccolo # print(next(it)) → raises StopIteration
Generators — yield
Using yield, you can create a generator function that produces values one at a time. This avoids loading all values into memory at once, making generators useful for large data sets.
def power_sequence(start, count):
level = start
for _ in range(count):
yield level
level *= 2
for power in power_sequence(1000, 5):
print(power)
# 1000 / 2000 / 4000 / 8000 / 16000
For details on generators, see yield / Generators.
Async Programming (asyncio)
Since Python 3.5, the async/await syntax enables non-blocking asynchronous programming. It is most effective for I/O-bound tasks such as HTTP requests and database access.
import asyncio
async def fetch_power_level(fighter):
print(f"Fetching power level for {fighter}...")
await asyncio.sleep(1) # Simulates I/O wait
return 9000
async def main():
# Run multiple coroutines concurrently
results = await asyncio.gather(
fetch_power_level("Son Goku"),
fetch_power_level("Vegeta"),
fetch_power_level("Piccolo"),
)
print(results) # [9000, 9000, 9000]
asyncio.run(main())
A function defined with async def becomes a coroutine. await suspends the coroutine until the awaited result is ready, allowing other tasks to run in the meantime. asyncio.gather() runs multiple coroutines concurrently.
For details on async programming, see asyncio / async / await.
Common Errors and How to Fix Them
IndentationError
Raised when indentation is inconsistent. Mixing tabs and spaces is a common cause.
# NG: mismatched indentation
def greet(name):
print("Hello")
print(name) # IndentationError: unexpected indent
# OK: consistent indentation (4 spaces is the standard)
def greet(name):
print("Hello")
print(name)
NameError — variable or function not found
Raised when you reference a name that has not been defined. Spelling mistakes are a common cause.
print(fighter_name) # NameError: name 'fighter_name' is not defined # → Check the spelling / ensure the variable is assigned before use
TypeError — incompatible types
Raised when an operation is performed on incompatible types.
power = 9000 message = "Power level: " + power # TypeError: can only concatenate str (not "int") to str
# Convert to string before concatenating
message = "Power level: " + str(power)
# or use an f-string
message = f"Power level: {power}"
IndexError — list index out of range
Raised when you access an index that does not exist in the list.
fighters = ["Son Goku", "Vegeta"] print(fighters[5]) # IndexError: list index out of range # → Check the length with len(fighters) before accessing
KeyError — key not found in dict
Raised when you try to access a key that does not exist using []. Use get() or check for the key's existence first.
character = {"name": "Bulma", "age": 16}
print(character["team"]) # KeyError: 'team'
# Solution 1: use get() (returns None if the key is missing)
print(character.get("team")) # None
print(character.get("team", "N/A")) # N/A (specify a default value)
# Solution 2: check for key existence with in
if "team" in character:
print(character["team"])
Recommended Learning Order
Now that you have a high-level picture of Python, the table below suggests an efficient order to work through the pages in this dictionary.
| Step | Topic | Pages |
|---|---|---|
| 1 | Setup and basics | [Setup] Python Development Environment ↓ Creating and Running .py Files |
| 2 | Basic types and output | print() / input() / repr() ↓ int() / float() / str() / bool() ↓ len() / type() / id() |
| 3 | Collections | list.append() / extend() / insert() ↓ list / tuple / set ↓ dict.get() / setdefault() |
| 4 | String operations | str.format() / f-strings ↓ str.split() / join() ↓ str.replace() / translate() |
| 5 | Functions and higher-order functions | lambda ↓ map() / filter() / sorted() ↓ range() / enumerate() / zip() |
| 6 | Classes and OOP | class / __init__ / self ↓ Inheritance / super() ↓ @property / @classmethod / @staticmethod |
| 7 | Exceptions and file handling | try / except / finally ↓ raise / Custom exceptions ↓ open() / read() / write() |
| 8 | Pythonic style | List comprehensions ↓ yield / Generators ↓ Decorators |
| 9 | Async and parallel processing | asyncio / async / await ↓ threading ↓ multiprocessing |
Summary
Python = a general-purpose scripting language that prioritizes readability and productivity
Core concepts
- Indentation is syntax (blocks are expressed with indentation, not
{}) - Dynamic typing — no type declarations required
- "There should be one obvious way to do it" (The Zen of Python)
Basic types
int— integerfloat— floating-point numberstr— string (embed variables with f-strings)bool— boolean (True/False)None— no value
Collection types
list— ordered, mutabletuple— ordered, immutableset— no duplicates, unordereddict— key-value pairs
Pythonic style
- List comprehensions —
[x * 2 for x in items if x > 0] - Generators — produce values one at a time with
yield - Decorators — extend functions with
@functools.lru_cacheand similar
Running code
python script.py— run a script filepython— start interactive mode (REPL) to test one line at a time
What you gain with Python
- Write code quickly with simple, readable syntax
- Access a rich ecosystem of machine learning and data analysis libraries (NumPy, pandas, TensorFlow, etc.)
- Accomplish a wide range of tasks with the standard library alone, without extra packages
- Write code that others can understand easily, thanks to enforced indentation and consistent style
Things to keep in mind
- Runtime speed is slower than C/C++/Go/Rust. For performance-critical sections, the common approach is to delegate to C-backed libraries like NumPy
- Because of dynamic typing, combining type hints with
mypyimproves safety in large codebases - The GIL (Global Interpreter Lock) in CPython limits true parallel thread execution. For I/O-bound concurrency, use
asyncio; for CPU (Central Processing Unit — the processor that executes computations)-bound parallelism, usemultiprocessing - Using virtual environments (
venv) to manage packages per project is the standard practice
If you find any errors or copyright issues, please contact us.