Python Glossary
Essential Python terms and concepts explained with examples
📚 Python Terminology
Understanding Python terminology is crucial for effective communication and learning. This glossary covers essential terms, concepts, and jargon used in Python programming with clear explanations and practical examples.
# Key Python concepts in action
def greet(name): # Function definition
"""Docstring""" # Documentation string
return f"Hello, {name}!" # f-string, return statement
message = greet("Alice") # Function call, assignment
print(message) # Built-in function
Term Categories
Basic Terms
Fundamental concepts
Variable, Function
Class, Object
Module, Package
Data Structures
Ways to organize data
List, Dictionary
Tuple, Set
Array, Stack
Programming Concepts
Core programming ideas
Iteration, Recursion
Scope, Namespace
Inheritance, Polymorphism
Advanced Terms
Complex concepts
Decorator, Generator
Context Manager
Metaclass, Descriptor
🔤 A-F Terms
🔹 Argument
A value passed to a function when calling it.
def greet(name): # 'name' is a parameter
return f"Hello, {name}!"
greet("Alice") # "Alice" is an argument
🔹 Attribute
A property or method belonging to an object.
text = "hello"
print(text.upper()) # 'upper' is an attribute (method)
print(len(text)) # 'len' accesses length attribute
🔹 Boolean
A data type with only two values: True or False.
is_active = True
is_deleted = False
result = 5 > 3 # Boolean result: True
🔹 Class
A blueprint for creating objects with shared attributes and methods.
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
return f"{self.name} barks!"
my_dog = Dog("Buddy") # Create object from class
🔹 Dictionary
A collection of key-value pairs, unordered and mutable.
person = {"name": "Alice", "age": 25}
print(person["name"]) # Access by key
person["city"] = "NYC" # Add new key-value pair
🔹 Exception
An error that occurs during program execution.
try:
result = 10 / 0 # Raises ZeroDivisionError
except ZeroDivisionError:
print("Cannot divide by zero!")
🔹 Function
A reusable block of code that performs a specific task.
def add_numbers(a, b):
"""Add two numbers and return result"""
return a + b
result = add_numbers(5, 3) # Call function
🔤 G-M Terms
🔹 Generator
A function that yields values one at a time, saving memory.
def count_up_to(n):
i = 1
while i <= n:
yield i # Yield instead of return
i += 1
for num in count_up_to(3):
print(num) # Prints 1, 2, 3
🔹 Immutable
Objects that cannot be changed after creation.
# Immutable types
text = "hello"
numbers = (1, 2, 3) # Tuple
# text[0] = "H" # Error! Strings are immutable
🔹 Inheritance
A class can inherit attributes and methods from another class.
class Animal:
def speak(self):
pass
class Dog(Animal): # Dog inherits from Animal
def speak(self):
return "Woof!"
dog = Dog()
print(dog.speak()) # "Woof!"
🔹 Iteration
The process of repeating a block of code.
# For loop iteration
for i in range(3):
print(i)
# While loop iteration
count = 0
while count < 3:
print(count)
count += 1
🔹 List
An ordered, mutable collection of items.
fruits = ["apple", "banana", "cherry"]
fruits.append("date") # Add item
print(fruits[0]) # Access by index
fruits[1] = "blueberry" # Modify item
🔹 Method
A function that belongs to an object or class.
text = "hello world"
result = text.upper() # upper() is a string method
print(result) # "HELLO WORLD"
# Custom method
class Calculator:
def add(self, a, b): # Method
return a + b
🔹 Module
A file containing Python code that can be imported.
import math # Import entire module
print(math.pi)
from datetime import datetime # Import specific item
now = datetime.now()
🔹 Mutable
Objects that can be changed after creation.
# Mutable types
numbers = [1, 2, 3] # List
numbers.append(4) # Can modify
numbers[0] = 10 # Can change items
person = {"name": "Alice"} # Dictionary
person["age"] = 25 # Can add/modify
🔤 N-S Terms
🔹 Namespace
A container that holds names (variables, functions) and their values.
x = 10 # Global namespace
def my_function():
x = 20 # Local namespace
print(f"Local x: {x}")
my_function() # Prints "Local x: 20"
print(f"Global x: {x}") # Prints "Global x: 10"
🔹 Object
An instance of a class with its own data and methods.
class Car:
def __init__(self, brand):
self.brand = brand
my_car = Car("Toyota") # my_car is an object
print(my_car.brand) # Access object's data
🔹 Parameter
A variable in a function definition that receives an argument.
def greet(name, age): # name and age are parameters
return f"Hello {name}, you are {age} years old"
greet("Alice", 25) # "Alice" and 25 are arguments
🔹 Polymorphism
Different classes can have methods with the same name.
class Dog:
def speak(self):
return "Woof!"
class Cat:
def speak(self):
return "Meow!"
animals = [Dog(), Cat()]
for animal in animals:
print(animal.speak()) # Same method, different behavior
🔹 Recursion
A function calling itself to solve a problem.
def factorial(n):
if n <= 1:
return 1
else:
return n * factorial(n - 1) # Function calls itself
print(factorial(5)) # 120
🔹 Scope
The region where a variable can be accessed.
x = "global" # Global scope
def outer():
x = "outer" # Enclosing scope
def inner():
x = "inner" # Local scope
print(x)
inner() # Prints "inner"
print(x) # Prints "outer"
outer()
print(x) # Prints "global"
🔹 Set
An unordered collection of unique items.
numbers = {1, 2, 3, 3, 4} # Duplicates removed
print(numbers) # {1, 2, 3, 4}
numbers.add(5) # Add item
print(3 in numbers) # Check membership: True
🔹 String
A sequence of characters, immutable in Python.
text = "Hello, World!"
print(text[0]) # 'H' - access by index
print(text.lower()) # "hello, world!" - method call
print(len(text)) # 13 - length
🔤 T-Z Terms
🔹 Tuple
An ordered, immutable collection of items.
coordinates = (10, 20) # Create tuple
x, y = coordinates # Unpack tuple
print(f"X: {x}, Y: {y}")
# Tuples are immutable
# coordinates[0] = 15 # Error!
🔹 Variable
A name that refers to a value stored in memory.
name = "Alice" # String variable
age = 25 # Integer variable
height = 5.6 # Float variable
is_student = True # Boolean variable
🔹 Decorator
A function that modifies or extends another function's behavior.
def my_decorator(func):
def wrapper():
print("Before function")
func()
print("After function")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello() # Prints all three messages
🔹 Lambda
A small anonymous function defined with the lambda keyword.
square = lambda x: x ** 2
print(square(5)) # 25
# Often used with map, filter
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
print(squared) # [1, 4, 9, 16, 25]
🔹 List Comprehension
A concise way to create lists using a single line of code.
# Traditional way
squares = []
for x in range(5):
squares.append(x ** 2)
# List comprehension
squares = [x ** 2 for x in range(5)]
print(squares) # [0, 1, 4, 9, 16]
# With condition
evens = [x for x in range(10) if x % 2 == 0]
print(evens) # [0, 2, 4, 6, 8]
🔹 Iterator
An object that can be iterated (looped) over.
# Lists are iterable
numbers = [1, 2, 3]
for num in numbers: # numbers is iterable
print(num)
# Create iterator
my_iter = iter(numbers)
print(next(my_iter)) # 1
print(next(my_iter)) # 2
🔹 Context Manager
An object that defines what happens in a 'with' statement.
# File handling with context manager
with open("data.txt", "w") as file:
file.write("Hello, World!")
# File automatically closed
# Custom context manager
class MyContext:
def __enter__(self):
print("Entering context")
return self
def __exit__(self, *args):
print("Exiting context")
with MyContext():
print("Inside context")
🔹 Docstring
A string literal used to document functions, classes, or modules.
def calculate_area(radius):
"""
Calculate the area of a circle.
Args:
radius (float): The radius of the circle
Returns:
float: The area of the circle
"""
return 3.14159 * radius ** 2
print(calculate_area.__doc__) # Print docstring
🎯 Quick Reference
Common Python terms at a glance
📊 Data Types:
Immutable: int, float, str, tuple, frozenset
Mutable: list, dict, set
🔧 Function Types:
Built-in: print(), len(), type(), range()
User-defined: Created with 'def' keyword
Lambda: Anonymous functions
Methods: Functions belonging to objects
🏗️ OOP Concepts:
Class: Blueprint for objects
Object: Instance of a class
Inheritance: Class inherits from another
Polymorphism: Same interface, different behavior
🔄 Control Flow:
Conditional: if, elif, else
Loops: for, while
Control: break, continue, pass
# Quick examples of key concepts
# Variables and data types
name = "Alice" # String
age = 25 # Integer
scores = [85, 90, 78] # List
info = {"name": name, "age": age} # Dictionary
# Functions
def greet(person):
return f"Hello, {person}!"
# Classes and objects
class Student:
def __init__(self, name):
self.name = name
def study(self):
return f"{self.name} is studying"
student = Student("Bob")
print(student.study())
# Control flow
for score in scores:
if score >= 80:
print(f"Great score: {score}")
else:
print(f"Good effort: {score}")
# Exception handling
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
# List comprehension
squares = [x**2 for x in range(5)]
print(squares) # [0, 1, 4, 9, 16]