Introduction To Python
Python is a high‑level, interpreted programming language that emphasizes readability and simplicity. In the context of an introductory course, mastering the fundamental vocabulary is essential for building confidence and progressing to more…
Python is a high‑level, interpreted programming language that emphasizes readability and simplicity. In the context of an introductory course, mastering the fundamental vocabulary is essential for building confidence and progressing to more advanced topics. The following explanation covers the most important terms, their definitions, typical usage, practical examples, and short challenges that reinforce learning. Each key concept is highlighted with bold tags, while occasional italic emphasis draws attention to subtle distinctions.
Interpreter – The software component that reads Python code and executes it line by line. Unlike a compiler, which translates source code into a standalone binary, the interpreter performs translation at runtime. When you type python script.Py at a command prompt, the interpreter launches, parses the file, and runs the statements.
Script – A plain‑text file containing a sequence of Python statements. Scripts typically have the extension .Py. They can be executed directly by the interpreter or imported as modules.
REPL – Stands for “Read‑Eval‑Print Loop.” It is an interactive environment where you type a single expression, press Enter, and instantly see the result. The standard REPL is launched by typing python without arguments. Many developers use enhanced REPLs such as IPython for richer introspection.
IDE – Integrated Development Environment. An IDE combines a source‑code editor, debugger, and other tools in one application. Popular Python IDEs include PyCharm, Visual Studio Code, and Spyder. While an IDE is not required to write Python, it can accelerate learning by providing syntax highlighting, auto‑completion, and integrated terminals.
Variable – A name that references a value stored in memory. Python variables are created the first time they appear on the left side of an assignment. Example:
```python Counter = 0 Message = "Hello, world!" ```
In the first line, counter references an integer object with value zero; in the second line, message references a string object.
Data type – The classification of a value that determines the operations applicable to it. Core built‑in data types include int, float, str, bool, list, tuple, dict, and set.
int – Represents whole numbers, positive or negative, without a fractional part. Python integers have unlimited precision, limited only by available memory. Example:
```python Age = 27 Big_number = 12345678901234567890 ```
float – Represents real numbers using a binary floating‑point format. Floats can store decimal fractions but are subject to rounding errors. Example:
```python Price = 19.99 Ratio = 1.0 / 3.0 # yields 0.3333333333333333 ```
bool – Boolean type with only two possible values: True or False. Booleans are often the result of comparison operators or logical expressions. Example:
```python Is_active = True Is_expired = False ```
str – Short for “string,” a sequence of Unicode characters. Strings are immutable; once created, their content cannot be changed in place. Common operations include concatenation, slicing, and formatting. Example:
```python Greeting = "Hello" Name = "Alice" Full_message = greeting + ", " + name + "!" ```
list – An ordered, mutable collection of items. Lists are defined with square brackets and can contain heterogeneous elements. Example:
```python Numbers = [1, 2, 3, 4, 5] Mixed = [42, "answer", 3.14, True] ```
tuple – An ordered, immutable collection. Defined with parentheses (or just commas). Tuples are often used for fixed‑size records. Example:
```python Point = (10, 20) Record = ("Bob", 30, "Engineer") ```
dict – A mapping from keys to values, implemented as a hash table. Keys must be immutable (e.G., Strings, numbers, tuples). Example:
```python Person = {"name": "Carol", "age": 28, "City": "Paris"} ```
set – An unordered collection of unique elements. Defined with curly braces or the set() constructor. Example:
```python Primes = {2, 3, 5, 7, 11} ```
Indexing – Accessing an element of a sequence by its position. Indices start at zero. Example:
```python Letters = ["a", "b", "c"] First = letters[0] # "a" last = letters[-1] # "c" ```
Slicing – Extracting a sub‑range from a sequence using the start:Stop:Step syntax. Example:
```python Alphabet = "abcdefghijklmnopqrstuvwxyz" Segment = alphabet[2:8] # "cdefgh" Every_third = alphabet[::3] # "adgjmpsvy" ```
Concatenation – Joining two sequences of the same type. For strings, use the + operator; for lists, the same operator works. Example:
```python Full_name = "John" + " " + "Doe" Combined = [1, 2] + [3, 4] ```
Formatting – Inserting values into a string template. Python offers several mechanisms: The percent operator, the str.Format() method, and f‑strings. The most modern approach uses f‑strings, introduced in Python 3.6. Example:
```python Price = 9.99 Msg = f"The total is ${price:.2F}" ```
Escape sequence – A backslash (\) followed by a character that represents a special meaning, such as newline \n or tab \t. Example:
```python Multiline = "Line1\nLine2\nLine3" ```
Comment – Text ignored by the interpreter, used to explain code. Single‑line comments start with #. Multi‑line comments are usually written as docstrings (triple‑quoted strings) placed at the beginning of a module, class, or function. Example:
```python # Compute the sum of two numbers Def add(a, b): """Return the arithmetic sum of a and b.""" Return a + b ```
Docstring – A string literal that appears as the first statement in a module, class, or function. Docstrings are accessible via the .__Doc__ attribute and are used by documentation tools.
Module – A file containing Python definitions and statements that can be imported elsewhere. Modules promote code reuse and organization. Example:
```python # file: utils.py Def square(x): Return x * x ```
Then in another file:
```python Import utils Result = utils.Square(5) ```
Package – A directory containing multiple modules and an optional __init__.Py file that defines the package’s namespace. Packages enable hierarchical organization of large codebases.
Import – The statement that brings a module or specific attributes into the current namespace. Variants include import module, from module import name, and import module as alias. Example:
```python Import math From math import sqrt, pi Import numpy as np ```
Function – A reusable block of code that performs a specific task and can return a value. Functions are defined with the def keyword. Example:
```python Def greet(name): """Return a personalized greeting.""" Return f"Hello, {name}!" ```
Parameter – The variable listed in a function’s definition. In the greet example, name is a parameter.
Argument – The actual value supplied to a function when it is called. In greet("Bob"), the string "Bob" is an argument.
Return – The statement that sends a value back to the caller. A function without an explicit return returns None.
Lambda – An anonymous, inline function defined with the lambda keyword. It can have any number of parameters but only a single expression. Example:
```python Square = lambda x: X * x Print(square(4)) # 16 ```
Recursion – A function calling itself to solve a problem by breaking it into smaller sub‑problems. Proper base cases are essential to prevent infinite loops. Example (factorial):
```python Def factorial(n): If n == 0: Return 1 Return n * factorial(n - 1) ```
Iteration – Repeating a block of code for each element in a collection. In Python, iteration is typically performed with for loops, which abstract away the underlying indexing. Example:
```python For fruit in ["apple", "banana", "cherry"]: Print(fruit) ```
Loop – A control structure that repeats execution. Python provides for and while loops.
while – Executes as long as a condition remains true. Example:
```python Count = 5 While count > 0: Print(count) Count -= 1 ```
break – Terminates the nearest enclosing loop prematurely.
continue – Skips the remainder of the current loop iteration and proceeds to the next one.
pass – A null statement used as a placeholder where syntactically a statement is required but no action is needed.
Exception – An error condition raised during program execution. Exceptions can be caught and handled using try/except blocks.
try – Starts a block of code that may raise an exception.
except – Catches specific exception types and provides a handler.
finally – Executes after the try block, regardless of whether an exception occurred, typically used for cleanup.
raise – Manually triggers an exception. Example:
```python If value < 0: Raise ValueError("Negative value not allowed") ```
Class – A blueprint for creating objects (instances) that encapsulate data and behavior. Defined with the class keyword. Example:
```python Class Person: Def __init__(self, name, age): Self.Name = name Self.Age = age
Def introduce(self): Return f"My name is {self.Name} and I am {self.Age} years old." ```
Object – An instance of a class, containing its own attribute values.
Attribute – A variable that belongs to an object (or class). In the Person example, name and age are attributes.
Method – A function defined inside a class that operates on the object’s attributes.
self – The first parameter of instance methods, referring to the object itself. It is passed automatically by Python.
__init__ – The initializer method that runs when a new object is created. It sets up initial attribute values.
Inheritance – A mechanism where a new class (subclass) derives from an existing class (superclass), inheriting its attributes and methods. Example:
```python Class Employee(Person): Def __init__(self, name, age, employee_id): Super().__Init__(name, age) Self.Employee_id = employee_id ```
Polymorphism – The ability of different classes to be used interchangeably through a common interface, often by overriding methods.
Encapsulation – The practice of bundling data (attributes) and methods that operate on the data within a single unit (class), restricting direct access from outside.
Namespace – A mapping from names to objects. Python maintains separate namespaces for built‑ins, global variables, and local variables within functions.
Scope – The region of a program where a name is valid. The main scopes are local, enclosing, global, and built‑in.
global – A statement that declares a variable inside a function to refer to the module‑level variable, allowing assignment.
nonlocal – Declares that a variable lives in the nearest enclosing (but not global) scope, enabling modification.
Built‑in – Functions and types that are always available without import, such as len(), range(), print(), list(), and dict().
Standard library – A collection of modules that ship with Python, providing utilities for file I/O, networking, data serialization, and more. Examples include os, sys, json, csv, and datetime.
Third‑party library – External packages distributed via the Python Package Index (PyPI) that extend functionality. They are installed with pip.
pip – The package installer for Python. Common commands: pip install package_name, pip uninstall package_name, and pip list.
Virtual environment – An isolated Python environment that contains its own interpreter, libraries, and scripts, allowing projects to have independent dependencies. Created with python -m venv env_name.
List comprehension – A concise way to generate lists by iterating over an iterable and optionally applying a filter. Example:
```python Squares = [x * x for x in range(10)] # [0, 1, 4, ..., 81] evens = [n for n in range(20) if n % 2 == 0] # even numbers ```
Generator – A function that yields values one at a time, producing an iterator without storing the entire sequence in memory. Defined using the yield keyword. Example:
```python Def countdown(n): While n > 0: Yield n N -= 1 ```
Iterator – An object that implements the __iter__() and __next__() methods, producing a sequence of values on demand.
next – Retrieves the next value from an iterator, raising StopIteration when exhausted.
__iter__ – Magic method that returns the iterator object itself.
__next__ – Magic method that returns the next value from the iterator.
Decorator – A higher‑order function that takes another function and extends its behavior without explicitly modifying it. Implemented with the @decorator_name syntax. Example:
```python Def logger(func): Def wrapper(*args, **kwargs): Print(f"Calling {func.__Name__}") Result = func(*args, **kwargs) Print(f"{func.__Name__} returned {result}") Return result Return wrapper
@Logger Def add(a, b): Return a + b ```
property – A built‑in decorator that turns a method into a managed attribute, allowing controlled access. Example:
```python Class Circle: Def __init__(self, radius): Self._Radius = radius
@Property Def area(self): Return 3.14159 * Self._Radius ** 2 ```
staticmethod – A method that does not receive an implicit first argument (neither self nor cls). Declared with @staticmethod.
classmethod – A method that receives the class itself as the first argument (cls), allowing it to modify class‑level state. Declared with @classmethod.
Operator – Symbols that perform operations on values, such as +, -, *, /, //, %, **, and logical operators and, or, not.
Operator overloading – The ability to define custom behavior for standard operators on user‑defined classes by implementing special methods like __add__, __sub__, and __len__.
Magic methods – Also called “dunder” methods (double underscore), they give classes special capabilities. Common examples include __init__, __repr__, __str__, __len__, __getitem__, and __setitem__.
__repr__ – Returns an “official” string representation of an object, useful for debugging.
__str__ – Returns a “nice” string representation for end‑users, used by print().
__len__ – Returns the length of a container, enabling the use of len().
__getitem__ – Allows indexing and slicing syntax for custom objects.
File I/O – Operations that read from or write to files on disk. The built‑in open() function opens a file and returns a file object. Example:
```python With open("data.Txt", "r") as f: Content = f.Read() ```
The with statement ensures the file is properly closed, even if an error occurs.
Reading – Common methods: read() (entire file), readline() (single line), and readlines() (list of lines).
Writing – Use write() or writelines() on a file opened in "w" (write) or "a" (append) mode.
csv – Comma‑separated values format. Python’s csv module provides csv.Reader and csv.Writer for handling tabular data. Example:
```python Import csv With open("people.Csv", "w", newline="") as f: Writer = csv.Writer(f) Writer.Writerow(["Name", "Age"]) Writer.Writerow(["Dave", 34]) ```
json – JavaScript Object Notation, a lightweight data‑interchange format. The json module offers json.Dump() and json.Load(). Example:
```python Import json Data = {"name": "Eve", "scores": [85, 92, 78]} With open("data.Json", "w") as f: Json.Dump(data, f, indent=2) ```
pickle – A binary serialization format for Python objects. Use pickle.Dump() and pickle.Load() to persist complex objects.
```python Import pickle Obj = {"key": "Value"} With open("obj.Pkl", "wb") as f: Pickle.Dump(obj, f) ```
Debugging – The process of locating and fixing errors. Common techniques include inserting print() statements, using the pdb module (Python debugger), or leveraging IDE breakpoints.
assert – A statement that checks a condition and raises an AssertionError if false. Useful for sanity checks during development. Example:
```python Def divide(a, b): Assert b != 0, "Denominator must not be zero" Return a / b ```
Logging – A systematic way to record events, errors, and informational messages. The logging module provides flexible configuration. Example:
```python Import logging Logging.BasicConfig(level=logging.INFO) Logging.Info("Program started") ```
Type hinting – Optional annotations that specify expected data types for variables, function parameters, and return values. Introduced in PEP 484 and widely used for static analysis. Example:
```python Def greet(name: Str) -> str: Return f"Hello, {name}" ```
PEP 8 – The official style guide for Python code, covering naming conventions, indentation (four spaces), line length (79 characters), and more. Following PEP 8 improves readability and collaboration.
Docstring conventions – Standard formats include the Google style, NumPy style, and reStructuredText (reST). Consistent docstrings enable tools like Sphinx to generate documentation automatically.
Mutable vs immutable – Mutable objects can be changed after creation (e.G., list, dict, set), while immutable objects cannot (e.G., int, float, str, tuple). Understanding this distinction helps avoid unintended side effects.
Reference counting – Python’s memory management technique where each object keeps a count of references pointing to it. When the count drops to zero, the object is reclaimed.
Garbage collection – An additional mechanism that detects and cleans up cyclic references that reference counting alone cannot resolve.
Context manager – An object that defines __enter__ and __exit__ methods, enabling the with statement to manage resources automatically. Files, locks, and database connections are typical examples.
Threading – The threading module provides high‑level support for creating and managing threads. Due to the Global Interpreter Lock (GIL), CPU‑bound Python code often does not gain performance from threads, but I/O‑bound tasks can benefit.
Multiprocessing – The multiprocessing module circumvents the GIL by spawning separate Python interpreter processes, allowing true parallelism on multi‑core CPUs.
Asyncio – A library for writing concurrent code using the async/await syntax. It is especially useful for network I/O and high‑throughput servers. Example:
```python Import asyncio
Async def hello(): Await asyncio.Sleep(1) Print("Hello, async world!")
Asyncio.Run(hello()) ```
Regular expression – A powerful tool for pattern matching within strings, using the re module. Example:
```python Import re Match = re.Search(r"\d{3}-\d{2}-\d{4}", "My SSN is 123-45-6789") If match: Print("Found:", Match.Group()) ```
Unit test – A test that verifies a small piece of code (usually a function) works as expected. The unittest module provides a framework for defining test cases, setup, and teardown. Example:
```python Import unittest
Def add(a, b): Return a + b
Class TestMath(unittest.TestCase): Def test_add(self): Self.AssertEqual(add(2, 3), 5)
If __name__ == "__main__": Unittest.Main() ```
Assertion – In testing, an assertion checks that a condition holds. If it fails, the test reports an error.
Mock – A technique for replacing parts of the system under test with controlled stand‑ins, useful for isolating behavior. The unittest.Mock module provides utilities for this purpose.
Virtualenv vs venv – Both create isolated environments, but virtualenv is a third‑party tool that works with older Python versions, while venv is built into Python 3.3+.
Package manager – Tools like pipenv, poetry, and conda help manage dependencies, lockfiles, and virtual environments in a more reproducible way.
PEP 20 – Also known as “The Zen of Python,” accessible via import this. It provides guiding principles such as “Simple is better than complex” and “Readability counts.”
Namespace package – A package that can span multiple directories, enabling large projects to be split across several source trees without a single __init__.Py.
Dynamic typing – Python determines the type of a variable at runtime, allowing the same name to reference objects of different types throughout execution.
Static typing – Using type hints and external type checkers (e.G., mypy) to enforce type constraints before runtime, improving reliability in large codebases.
Garbage‑collector thresholds – The gc module provides functions to inspect and control garbage collection, useful for performance tuning in memory‑intensive applications.
Bytecode – The low‑level, platform‑independent representation of Python code that the interpreter executes. The compile() function can generate bytecode objects.
Compiled extension – Modules written in C or C++ and compiled into shared libraries (e.G., .Pyd on Windows). They can be imported like regular Python modules, offering performance gains.
GIL – The Global Interpreter Lock ensures that only one thread executes Python bytecode at a time, simplifying memory management but limiting multi‑threaded CPU performance.
Metaclass – A class of a class; it defines how classes behave. The default metaclass is type. Custom metaclasses can modify class creation, useful for frameworks and ORM libraries.
Descriptor – An object that defines any of the methods __get__, __set__, or __delete__. Descriptors are the underlying mechanism for properties, methods, and static methods.
Module search path – The list of directories Python examines to locate modules, stored in sys.Path. Modifying sys.Path at runtime can affect import behavior.
Package __init__.Py – A file that can be empty or contain initialization code for a package. Its presence signals to Python that the directory should be treated as a package.
Egg vs wheel – Distribution formats for Python packages. Wheel (.Whl) is the modern standard, while egg is legacy.
Namespace collision – Occurs when two modules share the same name, leading to ambiguous imports. Using absolute imports or renaming modules mitigates this risk.
Shebang – The first line of a script on Unix‑like systems, starting with #!, indicating which interpreter should execute the file (e.g., #!/usr/bin/env python3).
Encoding – Determines how text characters are represented as bytes. Python source files default to UTF‑8; explicit encoding declarations can be added with a comment, e.G., # -*- coding: utf-8 -*-.
Unicode – A universal character set that accommodates virtually all written languages. Python’s str type stores Unicode code points, while bytes holds raw binary data.
bytes – An immutable sequence of bytes. Useful for binary I/O, network protocols, and cryptographic operations. Example:
```python Data = b"Hello" Hex_repr = data.Hex() # '48656c6c6f' ```
bytearray – A mutable counterpart to bytes.
Memoryview – Provides a view of a memory buffer without copying, useful for efficient data processing.
Hashable – Objects that have a stable hash value and can be used as dictionary keys or set elements. Immutable built‑ins (e.G., int, str, tuple) are hashable.
Iterator protocol – The contract that an object must implement __iter__ returning itself and __next__ returning the next item or raising StopIteration.
Generator expression – Similar to list comprehensions but uses parentheses and produces a generator object. Example:
```python Sum_of_squares = sum(x * x for x in range(10)) ```
Lazy evaluation – Deferring computation until the result is needed. Generators and iterator tools embody this concept, reducing memory consumption.
Decorator syntax sugar – The @decorator line is syntactic sugar for applying a higher‑order function to another function.
Context manager protocol – Requires __enter__ (executed at the start of the with block) and __exit__ (executed at the end).
__call__ – A magic method that makes an instance callable like a function.
__getitem__ – Enables indexing and slicing for custom container types.
__setitem__ – Allows assignment to specific indices of a container.
__delitem__ – Supports deletion of items via del container[index].
__contains__ – Implements membership testing (e.G., in operator).
__len__ – Returns the size of a container, enabling len().
__iter__ – Returns an iterator for a container.
__next__ – Retrieves the next item from an iterator.
__repr__ – Provides an unambiguous string representation, often usable to recreate the object.
__str__ – Provides a readable, user‑friendly string representation.
__eq__ – Defines equality comparison using the == operator.
__lt__, __le__, __gt__, __ge__ – Define ordering comparisons.
__hash__ – Returns an integer hash value; required for hashable objects.
__bool__ – Determines the truth value of an object in boolean contexts.
__init_subclass__ – A hook called when a class is subclassed, useful for enforcing constraints on subclasses.
__slots__ – An attribute that restricts instance attributes to a fixed set, reducing memory overhead.
Exception hierarchy – All built‑in exceptions inherit from BaseException. The most common branch is Exception, under which specific errors like ValueError, TypeError, and KeyError reside.
KeyboardInterrupt – Raised when the user presses Ctrl‑C.
SystemExit – Raised by the sys.Exit() function; can be caught to perform cleanup before termination.
ImportError – Occurs when an import statement fails to locate the requested module.
ModuleNotFoundError – A subclass of ImportError introduced in Python 3.6, More specific to missing modules.
AttributeError – Raised when an attribute reference or assignment fails.
TypeError – Raised when an operation is applied to an object of inappropriate type.
ValueError – Raised when a function receives an argument of correct type but inappropriate value.
IndexError – Raised when a sequence subscript is out of range.
NameError – Raised when an identifier is not found in the local or global namespace.
Key takeaways
- The following explanation covers the most important terms, their definitions, typical usage, practical examples, and short challenges that reinforce learning.
- Unlike a compiler, which translates source code into a standalone binary, the interpreter performs translation at runtime.
- Script – A plain‑text file containing a sequence of Python statements.
- ” It is an interactive environment where you type a single expression, press Enter, and instantly see the result.
- While an IDE is not required to write Python, it can accelerate learning by providing syntax highlighting, auto‑completion, and integrated terminals.
- Python variables are created the first time they appear on the left side of an assignment.
- ```python Counter = 0 Message = "Hello, world!