20. Glossary#

This glossary provides detailed explanations of each term, helping to clarify their meanings and roles within Python programming.

Boolean#

A boolean is a data type that represents one of two values: True or False. The bool type is commonly used in conditions and logical operations where a truth value is needed. In Python, booleans are a subclass of integers, with True equating to 1 and False equating to 0. This allows booleans to be used in arithmetic expressions as well as in control flow statements such as if, while, and for loops. Booleans can be the result of comparison operations (like ==, >, <) or logical operations (and, or, not), making them essential for decision-making processes in a program.

Block#

In Python, a block is a group of statements that are executed together and are defined by indentation rather than curly braces, which are used in some other programming languages. Each block starts with a colon (:) followed by an indented set of statements. This indentation indicates the scope of control structures such as loops, conditionals, and function definitions. For example, after an if statement or within a for loop, all the statements at the same indentation level form a block. This indentation-based scoping is essential for organizing code and managing its execution flow in Python.

Break#

In Python, the break statement is used to exit a loop prematurely, regardless of the loop’s original terminating condition. It is typically used within for or while loops to terminate the loop when a specific condition is met. When the break statement is executed, control flow is transferred to the statement immediately following the loop. This can be useful for ending infinite loops or stopping iteration when a desired result is achieved. The break statement only affects the loop in which it is placed; nested loops are not affected.

Built-in#

In Python, “built-in” refers to the functions, constants, and types that are automatically available in the language without needing to import any external modules. These built-in features are part of Python’s standard library and include functions like print, len, and range, types like int, str, and list, and constants such as True, False, and None. Built-in functions and types are optimized for performance and are fundamental tools that make Python easy and efficient to use for common programming tasks.

Call#

In Python, a “call” refers to the process of invoking or executing a function or method. When a function or method is called, the Python interpreter transfers control to that function, executes its code, and then returns control to the point where the function was called. During this process, arguments can be passed to the function to provide input values, and the function may return a result to the caller. A call to a function is made by writing the function’s name followed by parentheses, which may include the arguments if required.

Casting#

Casting in Python refers to the process of converting a value from one data type to another. This is commonly done using built-in functions such as int, float, str, and list. For example, converting a floating-point number to an integer truncates the decimal part and retains only the whole number. Similarly, converting an integer to a string allows for textual representation and manipulation. Casting is essential for ensuring that values are in the correct format for specific operations, such as when performing arithmetic calculations or formatting output.

Class#

A class in Python is a blueprint for creating objects. It defines attributes (data) and methods (functions) that the created objects (instances) will have. Classes enable object-oriented programming (OOP), allowing for encapsulation, inheritance, and polymorphism. They are used to model real-world entities by grouping related data and functions together. Each instance of a class can hold its own unique data, while methods can define behaviors applicable to all instances.

Complexity#

In computer science, complexity refers to the efficiency of an algorithm, typically measured in terms of time and space. Time complexity refers to the amount of time an algorithm takes to run as a function of the input size. Space complexity refers to the amount of memory used by the algorithm. Complexity is commonly expressed in Big \(O\) notation, such as \(O(n)\), \(O(log n)\), or \(O(n^2)\), where “n” represents the size of the input data.

Continue#

The continue statement is used within loops in Python to skip the current iteration and proceed directly to the next iteration. When encountered, the program flow jumps back to the loop’s condition evaluation without executing the remaining code in the loop body for that iteration. This allows developers to control the flow of loops more granularly by deciding to bypass specific code blocks under certain conditions.

Control Structures#

Control structures in programming are constructs that dictate the flow of execution of a program. They allow for decision-making, repetition, and branching within the code. In Python, control structures include conditionals, loops, and exception handling mechanisms. Conditionals, such as if, elif, and else statements, enable the program to execute specific blocks of code based on whether certain conditions are met. Loops, including for and while, facilitate repeated execution of a block of code until a condition is satisfied. Exception handling, managed by try, except, finally, and raise, allows the program to gracefully handle errors and other exceptional conditions that arise during execution. These structures are fundamental for implementing complex logic and managing the flow of a Python program.

Dictionnary#

A dictionary in Python is a mutable data structure that stores key-value pairs. It allows for fast access to data based on a unique key. Each key in a dictionary is associated with a corresponding value, and keys must be unique and hashable (such as strings, numbers, or tuples). Dictionaries are widely used for tasks requiring the fast retrieval, insertion, or deletion of data based on a key.

Enumerate#

The enumerate function in Python allows you to loop over an iterable (e.g., a list or tuple) while keeping track of both the index and the value of the items. It returns an enumerate object that yields pairs containing the index and the corresponding item from the iterable. This is useful when both the position of an item and its value are needed during iteration, improving readability and reducing the need for manual index tracking.

Error#

An error in Python occurs when the interpreter encounters something it cannot process or execute. Errors are typically of two types: syntax errors, which occur when the code does not conform to Python’s rules for valid statements, and exceptions, which are runtime errors that occur while the program is running, such as ZeroDivisionError or TypeError. Handling errors properly using mechanisms like try-except blocks is important to avoid program crashes and improve robustness.

Error Handling#

Error Handling in Python refers to the process of managing and responding to runtime errors or exceptions that occur during the execution of a program. This is achieved using constructs such as try, except, else, and finally. When an error occurs within a try block, the except block is executed, allowing the program to continue running rather than terminating abruptly. The else block, if present, runs if no exceptions are raised, and the finally block is used for cleanup actions that must be executed regardless of whether an exception occurred. Proper error handling improves program robustness and user experience by gracefully managing unexpected situations.

Exception#

An exception in Python is an error that occurs during program execution, interrupting the normal flow of instructions. Python uses exceptions to signal that something has gone wrong, like division by zero or accessing a non-existent file. Exceptions can be caught and handled using try, except, and finally blocks, which allow the program to handle errors gracefully without crashing.

Expression#

An expression in Python is a combination of variables, constants, operators, and function calls that evaluates to a value. Expressions can be simple, such as a single number or variable, or complex, involving multiple operations and nested expressions. Expressions can be recursive, meaning that they can contain other expressions within them. For instance, in the expression (2 + (3 * 4)), the sub-expression (3 * 4) is evaluated first, and its result is then used in the outer expression. This recursive nature allows expressions to be built hierarchically, with operations performed in a specific order determined by rules such as PEMDAS. This capability is fundamental in programming, enabling the creation of complex calculations and logical conditions through nested and combined expressions.

File Cursor#

A file cursor (or file pointer) in Python refers to the position within a file from where data is read or written. When a file is opened, the cursor starts at the beginning (position 0) and moves as the program reads from or writes to the file. Functions like seek allow manual repositioning of the file cursor to a specific point in the file.

Float#

A float in Python is a data type used to represent real numbers that include a decimal point. The float type is designed to handle numbers with fractional components, allowing for precise calculations with non-integer values. Internally, Python floats are implemented using double-precision (64-bit) floating-point numbers as per the IEEE 754 standard, which provides a good balance between range and precision. However, due to the way floating-point arithmetic works, some operations on floats can lead to small rounding errors. Python provides various operations for floats, including arithmetic operations, comparison operations, and functions from the math module for more complex mathematical calculations.

For Each#

The for each concept in Python refers to the for loop used to iterate over the elements of a sequence (e.g., a list, tuple, dictionary, or set) without needing to manage loop indices explicitly. The for loop assigns each item in the iterable directly to a variable, enabling operations on individual elements. This approach is distinct from index-based iteration and is a key feature in Python, simplifying iteration over collections.

Function#

A function in Python is a block of reusable code designed to perform a specific task. It allows you to group a set of statements together, which can be executed by calling the function’s name. Functions can take inputs, known as parameters, and return outputs. They help in breaking down complex problems into smaller, manageable pieces, enhance code readability, and facilitate code reuse. Functions are defined using the def keyword, followed by the function name and parentheses, which may include parameters. The block of code within the function is indented and executes each time the function is called.

F-string#

An f-string, or formatted string literal, is a feature introduced in Python 3.6 that allows for embedded expressions inside string literals, using curly braces {}. By prefixing a string with the letter f, you enable the inclusion of variables and expressions directly within the string, which are evaluated at runtime. This provides a concise and readable way to create strings that include dynamic content. f-strings offer improved performance and clarity over older string formatting methods such as the % operator or the str.format method.

Garbage Collector#

The garbage collector in Python is a memory management tool that automatically deallocates memory used by objects that are no longer in use. Python uses reference counting as its primary method for memory management and supplements it with cyclic garbage collection to detect and clean up objects involved in reference cycles. This helps prevent memory leaks and ensures efficient use of system resources.

Generator#

In Python, a generator is a type of iterable that allows you to iterate over a sequence of values without storing them all simultaneously in memory. Generators are defined using functions with the yield keyword. When a generator function is called, it returns a generator object but does not start execution immediately. Instead, execution begins when the next function is called on the generator object. Generators are useful for handling large data sets or streams of data where the complete data set does not need to be stored in memory at once. They provide a way to create iterators in a more memory-efficient manner.

Hash#

A hash is a fixed-size numeric representation (hash code) of data generated by a hash function. Hashes are used to uniquely identify data elements, especially in collections like hash tables or dictionaries. In Python, objects like strings and numbers are hashable, meaning they can be passed through a hash function to generate a unique identifier for efficient storage and retrieval.

Hash Table#

A hash table is a data structure that uses a hash function to map keys to their corresponding values. It allows for fast data retrieval because the hash function generates a unique index for each key, enabling direct access to its value. In Python, dictionaries are implemented as hash tables, ensuring constant-time complexity for lookups in average cases.

IDE (Integrated Development Environment)#

An Integrated Development Environment (IDE) is a software application that provides tools to write, debug, and run code. An IDE typically includes a code editor, compiler, debugger, and other features such as syntax highlighting, code completion, and version control integration. Popular Python IDEs include PyCharm, VS Code, and Spyder.

Import#

In Python, import is a statement used to include the definitions (such as functions, classes, and variables) from a module (see Module) or package into the current namespace (see Namespace). This allows for code reuse and modularity by enabling the programmer to access and utilize pre-written code stored in separate files or libraries. Modules can be standard libraries included with Python, third-party packages installed via package managers (see Package Manager) like pip, or custom modules created by the programmer. The import statement can be used in various ways, including importing an entire module, specific components from a module, or renaming imported components for convenience.

Immutable#

In programming, an immutable object is an object whose state cannot be modified after it is created. In Python, strings, tuples, and integers are examples of immutable types. This means that once an immutable object is instantiated, its content cannot be altered, which can help prevent unintended side effects and make the code easier to understand and debug. If any changes are needed, a new object must be created instead.

Integer#

An integer in Python is a data type used to represent whole numbers without a fractional or decimal component. In Python, integers are represented by the int type, which is an arbitrary-precision type, meaning that it can handle numbers of virtually any size, constrained only by the available memory. Unlike some other programming languages where integers have fixed sizes (e.g., 32-bit or 64-bit), Python’s int type dynamically allocates more memory as needed to accommodate larger values.

Keyword#

A keyword is a reserved word that has a special meaning and purpose in the language’s syntax. Keywords cannot be used as identifiers (names for variables, functions, or classes) because they are integral to the structure of Python code. Examples of Python keywords include if, else, for, while, def, and class. These keywords are used to define control flow, functions, and classes, and are essential for writing Python programs. Python’s list of keywords can be accessed via the keyword module using keyword.kwlist.

List#

A list in Python is an ordered, mutable collection of items that can hold elements of different types. Lists allow for various operations, such as appending, removing, or sorting elements. Since lists are mutable, they can be modified after creation. They are indexed, meaning that elements can be accessed by their position, starting with index 0 for the first item.

List Comprehension#

List comprehension in Python is a concise way to create lists by applying an expression to each item in an iterable, optionally filtering the elements using conditions. It provides a syntactically efficient alternative to using loops for constructing new lists. List comprehensions can significantly improve code readability by reducing the amount of code needed to achieve a similar result.

Object ID#

The object ID in Python is a unique identifier assigned to each object in memory during its lifetime. It can be obtained using the id() function, which returns an integer representing the memory address where the object is stored. The object ID helps Python track each object and ensures that different objects are distinguishable even if they contain identical data.

Path#

A path in programming refers to the location of a file or directory in the file system. There are two types of paths: absolute paths, which specify the full directory location from the root directory, and relative paths, which specify the location relative to the current working directory. Paths are crucial for file handling and system navigation in Python.

PEMDAS#

PEMDAS is an acronym that helps remember the order of operations in arithmetic and algebra. It stands for Parentheses, Exponents, Multiplication and Division (from left to right), and Addition and Subtraction (from left to right). When evaluating an expression, operations inside parentheses are done first, followed by exponents. Then, multiplication and division are performed from left to right, followed by addition and subtraction in the same left-to-right order. This order of operations ensures that calculations are performed consistently and correctly.

Queue#

A queue is a linear data structure that follows the First-In-First-Out (FIFO) principle. Elements are added to the back (enqueue) and removed from the front (dequeue). Queues are useful in scenarios where order of processing matters, such as task scheduling or handling requests. In Python, queues can be implemented using list or the deque module.

Namespace#

In Python, a namespace is a container that holds a collection of identifiers (names) and their corresponding objects (values). Each namespace ensures that names are unique and are mapped to specific objects. There are several types of namespaces in Python, including local, global, and built-in (see Built-in) namespaces. The local namespace refers to the current function or method’s scope, the global namespace pertains to the module-level scope, and the built-in namespace contains names pre-defined by Python’s standard library. Namespaces help in avoiding naming conflicts and allow for modular and organized code management.

Method#

A method is a function that is defined within a class and is associated with objects created from that class. Methods operate on the data contained within the object and can modify the object’s state. They can be classified as instance methods, class methods, or static methods depending on how they interact with the class or object. The first argument of instance methods is typically self, which refers to the instance on which the method is invoked.

Module#

A module in Python is a file containing Python code that defines functions, classes, and variables which can be reused across different programs. Modules help in organizing code into manageable sections. Each module is a separate namespace (seeNamespace), which means that variables and functions defined in one module do not conflict with those in another module. Modules are imported using the import statement, allowing code from one module to be used in another.

Mutable#

A mutable object in Python is an object whose state or contents can be changed after its creation. Common mutable types include lists, dictionaries, and sets. These objects can be modified in place, allowing their contents to be altered without creating a new object. In contrast, immutable objects (like strings and tuples) cannot be modified after they are created. Understanding the difference between mutable and immutable types is important for managing data and avoiding unintended side effects.

None#

In Python, None is a special constant that represents the absence of a value or a null value. It is a singleton object of its own datatype, NoneType, and is often used to signify that a variable or function has no value. For example, a function that does not explicitly return a value will return None by default. None is also used to initialize variables or to indicate that a variable has not been assigned a meaningful value yet. It is important to distinguish None from other types like zero (0), empty strings (""), or empty lists ([]), as None specifically represents “nothing” or “no value”.

Object#

An object is a fundamental building block in Python’s object-oriented programming paradigm. Every value in Python is an object, including functions, variables, and data structures. Objects are instances of classes, and they contain attributes (data) and methods (functions) that define their behavior. Python’s dynamic typing means that an object’s type is determined at runtime, and new object types can be created by defining classes.

Package Manager#

A package manager is a tool that automates the process of installing, upgrading, configuring, and removing software packages or libraries. In Python, the most commonly used package manager is pip, which allows users to easily install and manage Python libraries from the Python Package Index (PyPI). Package managers simplify the management of dependencies and ensure that the correct versions of libraries are used in a project.

Pass#

In Python, the pass statement is a null operation that serves as a placeholder in blocks of code where syntactically some code is required but no action is needed or intended. It allows you to write code that syntactically adheres to Python’s rules while leaving certain sections incomplete or intentionally empty. The pass statement is often used in function or class definitions where the implementation is yet to be determined, or in control structures like loops and conditionals where the logic is to be added later. It effectively does nothing and allows the program to continue running without raising an error.

Pseudo-random#

Pseudo-random refers to sequences of numbers that appear to be random but are generated by deterministic algorithms. In Python, pseudo-random numbers can be generated using the random module. These sequences are not truly random because they are produced by algorithms with a defined starting point, known as the seed. Despite their deterministic nature, pseudo-random numbers are typically sufficient for most applications, including simulations and games.

Regular Expression#

A regular expression (regex) is a sequence of characters that defines a search pattern, mainly for use in pattern matching with strings. In Python, regular expressions are handled by the re module, allowing for operations such as searching, splitting, or replacing parts of strings based on defined patterns. Regex patterns can range from simple sequences to highly complex structures, incorporating special characters like ^, $, \, and [] to specify various conditions. Regular expressions are widely used for text processing, such as input validation, parsing, and string manipulation.

Scope#

Scope in Python refers to the context in which a variable or function is accessible and can be used. It is closely related to the concept of namespaces, which are mappings from variable names to objects. Python uses different scopes to manage these namespaces:

  • Local Scope: Variables defined inside a function or block are in the local scope of that function or block. They are only accessible within the specific function or block where they are defined.

  • Global Scope: Variables defined at the top level of a module or script are in the global scope. These variables can be accessed from any function within the module.

  • Built-in Scope: This is the scope that contains built-in functions and exceptions provided by Python, accessible from any part of the program. Each scope represents a separate namespace, and Python uses these namespaces (see Namespace) to resolve variable names and manage their visibility. Understanding the scope and its associated namespaces is essential for managing variable access and avoiding name conflicts in your code.

Script#

A Python script is a file containing Python code, typically saved with a .py extension. It is essentially a program or a sequence of instructions written in Python that is executed by the Python interpreter. Python scripts can be used for a wide range of applications, from simple automation tasks and data analysis to complex web applications and game development.

In a broader context, a script is a type of computer program designed to be run without being compiled. Unlike compiled languages, which transform code into machine language before execution, scripts are interpreted line-by-line, which can make them easier to write and test. Scripts are often used for automating repetitive tasks, managing system operations, or performing batch processing.

Sequence#

A sequence in Python is a data type that represents an ordered collection of elements. Common sequence types include list, tuple, and string. Sequences support indexing, slicing, and iteration, allowing access to their elements in a specific order. They can also be concatenated and repeated. Sequences can be mutable or immutable (see Immutable), depending on the type.

Slicing#

Slicing is a feature in Python that allows you to extract a portion of a sequence type, such as a list, tuple, or str. It involves specifying a start index, an end index, and an optional step value to create a sub-sequence from the original sequence. The syntax for slicing is [start:stop:step], where start is the index of the first element to include, stop is the index of the first element to exclude, and step determines the stride between elements. Slicing is useful for accessing subsets of data and manipulating sequences in a concise manner.

Stack#

A stack is a linear data structure that follows the Last-In-First-Out (LIFO) principle. In a stack, elements are added to and removed from the top. It is often used for tasks that involve reversing, backtracking, or maintaining function calls in recursion. Python can implement a stack using lists or the deque module for more efficient operations.

Standard Librairies#

Standard libraries are a collection of modules and packages that come bundled with Python and provide a wide range of functionalities. These libraries include modules for handling file I/O, system operations, data manipulation, and more. Examples of standard libraries include os, sys, math, and datetime. They are maintained as part of the Python Standard Library and are available for use without needing to install additional packages.

String#

A string in Python is a data type used to represent sequences of characters. Strings are enclosed in single quotes (’…’), double quotes (”…”), or triple quotes (‘’’…’’’ or “””…”””) for multi-line text. The str type is immutable, meaning that once a string is created, it cannot be altered. Python provides a wide range of built-in methods for string manipulation, including concatenation, slicing, and formatting.

Tuple#

A tuple is an immutable (see Immutable) sequence (see Sequence) type in Python, used to store a collection of items. Unlike lists (List), tuples cannot be altered once created, which means you cannot add, remove, or modify elements after the tuple is instantiated. Tuples can hold elements of different types and are commonly used to group related data together. They are created by placing values in parentheses, separated by commas.

While#

In Python, the while loop is a control flow (see Control Structures) statement that repeatedly executes a block of code as long as a specified condition remains true. The while loop evaluates the condition before each iteration, and if the condition evaluates to True, the loop body is executed. This process continues until the condition evaluates to False. It is crucial to ensure that the condition will eventually become false to avoid creating an infinite loop. The while loop provides a mechanism for executing code repeatedly based on dynamic conditions, making it useful for scenarios where the number of iterations is not known beforehand.

Working Directory#

The working directory in Python refers to the folder where the program is currently operating. When opening files or saving outputs, Python uses the current working directory as the default location unless an absolute path is specified. The working directory can be changed programmatically using the os.chdir() function. The current working directory is retrieved using os.getcwd().

Zip#

The zip function in Python combines multiple iterables (e.g., lists, tuples) into a single iterable of tuples. Each tuple contains one element from each of the input iterables, grouped by their corresponding positions. If the input iterables are of unequal lengths, zip stops when the shortest iterable is exhausted. This function is useful for parallel iteration over multiple sequences, merging them based on their positional correspondence.