Variables
Variables are used to store data values.
Data Types
Python has several built-in data types, including:
Variables Variables are used to store data values. Data Types Python has several built-in data types, including: |
|
|
|
Casting Data types can be explicitly converted using casting: |
|
Slicing Slicing is used to extract a portion of a string or list. |
|
|
|
Examples |
|
|
|
If-Else Conditional statements are used to execute different code blocks based on conditions. |
|
|
|
Examples |
|
One-Line If Statement |
|
For Loop Iterates over a sequence (list, tuple, string) or other iterable objects. |
|
While Loop Executes a block of code as long as a condition is true. |
|
Examples |
|
|
|
Break and Continue
|
|
|
|
Functions Functions are blocks of reusable code. |
|
|
|
Examples |
|
|
|
Lambda Functions Anonymous functions defined using the |
|
File Operations
|
|
|
|
Examples |
|
Using Automatically closes the file after the block is executed. |
|
Basic Operations Python supports standard arithmetic operations: |
|
|
|
Examples |
|
Plus-Equals (+=) A shorthand operator that combines addition and assignment. |
|
|
|
Examples |
It also works with other arithmetic operations:
|
f-Strings A convenient way to embed expressions inside string literals for formatting. |
|
|
|
Examples |
|
Formatting Options |
|
Definition: Immutable sequence of characters. Creation:
Common Operations:
|
Examples:
|
Integers (int) |
Whole numbers, positive or negative, without decimals.
|
Floating-Point Numbers (float) |
Numbers with a decimal point.
|
Complex Numbers (complex) |
Numbers with a real and imaginary part (j).
|
Operators: |
|
Examples:
|
|
|
|
Definition: |
Represents truth values: |
Boolean Operators: |
|
Truthiness: |
Most values are |
Comparison Operators: |
|
Examples:
|
|
|
|
Definition: Ordered, mutable (changeable) sequence of items. Creation:
Common Operations:
|
Examples:
|
Definition: |
Ordered, immutable (unchangeable) sequence of items. |
Creation: |
|
Common Operations: |
|
Immutability: |
Tuples cannot be modified after creation. You can’t add, remove, or change elements. |
Examples:
|
|
|
|
Definition: Unordered collection of unique items. Creation:
Common Operations:
|
Set Operations:
|
Examples:
|
Definition: |
Unordered collection of key-value pairs. Keys must be unique and immutable. |
Creation: |
|
Common Operations: |
|
Examples:
|
|
|
|
Definition: Converting a value from one data type to another. Functions:
|
Examples:
|
What is a Heap? |
A heap is a tree-based data structure that satisfies the heap property: In a min-heap, the value of each node is greater than or equal to the value of its parent, with the minimum-value element at the root. In a max-heap, the value of each node is less than or equal to the value of its parent, with the maximum-value element at the root. |
|
Python’s
|
|
Transforms a list into a heap, in-place, in linear time.
|
|
Pushes the
|
|
Pops and returns the smallest item from the
|
|
Pushes
|
|
Pops and returns the smallest item from the
|
Example: Creating and using a min-heap |
|
Finding the |
|
Max-Heap Implementation |
Python’s
|
Heap (using |
|
|
O(n) |
|
O(log n) |
|
O(log n) |
|
O(log n) |
|
O(log n) |
Stack (using |
|
|
O(1) (amortized) |
|
O(1) |
Queue (using |
|
|
O(1) |
|
O(1) |
What is a Queue? |
A queue is a linear data structure that follows the First-In, First-Out (FIFO) principle. The first element added to the queue is the first element to be removed. |
Implementation with |
Python’s
|
Enqueue (append) |
Adds an element to the rear of the queue.
|
Dequeue (popleft) |
Removes and returns the front element from the queue. If the queue is empty, it raises an
|
Peek (front) |
Returns the front element of the queue without removing it. Check for emptiness before peeking.
|
isEmpty |
Checks if the queue is empty.
|
Size |
Returns the number of elements in the queue.
|
Example: Using a queue |
|
Applications |
Queues are used in many algorithms and scenarios, such as:
|
|
The
|
|
The
|
|
Places
|
|
Removes and returns an item from the queue. If
|
|
Indicates that a formerly enqueued task is complete. Used by queue consumers. For each
|
|
Blocks until all items in the queue have been gotten and processed. The count of unfinished tasks goes up whenever an item is added to the queue. The count goes down whenever a consumer thread calls
|
Example: Using |
|
Why use |
|
Alternatives to |
While |
What is a Stack? |
A stack is a linear data structure that follows the Last-In, First-Out (LIFO) principle. The last element added to the stack is the first element to be removed. |
Implementation with Lists |
Python lists can be easily used as stacks. The
|
Push (append) |
Adds an element to the top of the stack.
|
Pop |
Removes and returns the top element from the stack. If the stack is empty, it raises an
|
Peek (top) |
Returns the top element of the stack without removing it. It’s a good practice to check if the stack is empty before peeking.
|
isEmpty |
Checks if the stack is empty.
|
Size |
Returns the number of elements in the stack.
|
Example: Using a stack |
|
Applications |
Stacks are used in many algorithms, such as:
|
Using |
For optimized stack operations, particularly in multi-threaded environments, use
|
Heaps:
|
Stacks:
|
Queues:
|
Real-world examples
|
|
Creates a list from an iterable.
|
|
Creates a tuple from an iterable.
|
|
Returns the length (number of items) of an object.
|
|
Access elements by index (0-based).
|
|
Extract a sub-sequence.
|
|
Check if an element is present.
|
|
Concatenate sequences.
|
Iterating over each character in a string:
|
Using
|
Looping through a string in reverse:
|
|
Extracts a portion of the string from
|
|
Extracts from
|
|
Extracts from the beginning to
|
|
Extracts a portion with a specified step.
|
Negative Indices |
Indices can be negative, starting from the end (-1).
|
|
Returns the number of characters in the string.
|
|
Repeats the string
|
|
Checks if
|
|
Checks if
|
|
Concatenates two strings.
|
|
Joins elements of an iterable into a string.
|
|
String interpolation using f-strings (Python 3.6+).
|
Using
|
Formatting with named placeholders:
|
Using f-strings (Python 3.6+):
|
|
Reads a line from input, converts it to a string, and returns it.
|
The
|
Joining with different separators:
|
Joining characters of a string (less common):
|
|
Checks if the string ends with the specified
|
|
Checks if the string ends with the specified
|
Checking with a tuple of suffixes: |
You can pass a tuple of suffixes to check if the string ends with any of them.
|
F-strings (formatted string literals) are a powerful and convenient way to embed expressions inside string literals for formatting. Introduced in Python 3.6, they provide a concise and readable syntax. They are faster than both |
To create an f-string, prefix the string with the letter Expressions inside the string are enclosed in curly braces Example:
|
Variable substitution |
|
Evaluating expressions |
|
Calling functions |
|
|
Right alignment
|
|
Left alignment
|
|
Center alignment
|
|
Forces the padding to be placed after the sign but before the digits.
|
Fill character |
Uses the specified character to fill the remaining space.
|
|
Integer type
|
|
Float type
|
|
String type
|
|
Binary type
|
|
Octal type
|
|
Hexadecimal type (lowercase)
|
|
Hexadecimal type (uppercase)
|
|
Scientific notation (lowercase)
|
|
Scientific notation (uppercase)
|
Precision for floats |
|
Thousands separator |
|
Percentage formatting |
|
Date formatting |
|
|
Indicates that a sign should be used for both positive as well as negative numbers.
|
|
Indicates that a space should be used for positive numbers and a minus sign for negative numbers.
|
|
Indicates that only negative numbers should have a sign (default behavior).
|
To include a literal curly brace in an f-string, double it: Example:
|
Backslashes cannot be directly included inside the expression part of f-strings. However, you can use a variable to hold the backslash or use other escaping methods. Example:
|
F-strings are evaluated at runtime, so they don’t support comments inside the expression part. F-strings cannot be used directly to specify the format string in methods like They are most suitable for simple and readable string formatting tasks. |
Lists are ordered, mutable collections of items. Creating an empty list:
Creating a list with initial values:
|
Lists can contain mixed data types:
|
Nested Lists:
|
Using
|
List Comprehensions:
|
|
Adds an item to the end of the list.
|
|
Extends the list by appending elements from an iterable.
|
|
Inserts an item at a given position.
|
Slicing allows you to extract portions of a list.
|
Examples:
|
|
Removes the first occurrence of a value.
|
|
Removes and returns the item at index. If index is not specified, removes and returns the last item.
|
|
Deletes an item at a specific index or a slice of the list.
|
|
Removes all items from the list.
|
Elements in a list are accessed using their index. Indexing starts at 0.
|
Negative Indexing: Access elements from the end of the list.
|
Using the
|
Using
|
|
Sorts the list in place (modifies the original list).
|
|
Returns a new sorted list (does not modify the original list).
|
|
Reverses the list in place.
|
|
Returns an iterator that accesses the given sequence in the reverse order.
|
|
Using the
|
The
|
Example:
|
Here, the condition |
The indentation is crucial in Python. It defines the scope of the code block associated with the |
Conditions can involve any comparison operators:
|
The
|
Example:
|
In this case, since |
The
|
Example:
|
Here, the conditions are checked in order. If |
You can have multiple |
Python allows you to write simple
|
Example:
|
This is equivalent to:
|
One-line |
You can nest
|
Example:
|
Nesting can make code harder to read, so use it judiciously and consider alternative approaches like logical operators ( |
Logical operators (
|
Examples:
|
Using logical operators can simplify complex nested |
In Python, certain values are considered “truthy” (evaluate to Falsy Values:
Truthy Values:
|
Example:
|
You can directly use variables in |
The basic Syntax:
Example:
|
Iterating through a string:
|
Iterating through a tuple:
|
For loop with conditional statement:
|
Using
|
To access both the item and its index, use the Syntax:
Example:
|
Starting the index from a different number (e.g., 1):
|
Using enumerate with a conditional statement:
|
The Syntax:
Example:
|
While loop with
|
Using
|
Using
|
The Example:
|
Break nested loop:
|
The Example:
|
Continue nested loop:
|
The Syntax:
Example:
|
Using
|
Using
|
Iterating in reverse:
|
The Syntax:
Example:
|
Zip with different length lists:
|
The Syntax:
Example:
|
For/else example with break:
|
A function is a block of code that performs a specific task. It’s reusable and makes code more organized. Syntax:
|
Example:
|
Key Components:
|
The Syntax:
|
If no expression is provided,
|
Returning a Value:
|
Positional arguments are passed to a function based on their order. The order matters! Example:
|
If the arguments are not provided in the correct order, the result might be unexpected:
|
Keyword arguments are passed to a function with the parameter name explicitly specified. Order doesn’t matter! Syntax:
|
Example:
|
You can mix positional and keyword arguments, but positional arguments must come first.
|
Python functions can return multiple values as a tuple. Example:
|
The returned values are packed into a tuple. You can then unpack the tuple into separate variables. |
You can specify default values for function parameters. If the caller doesn’t provide a value for that parameter, the default is used. Syntax:
|
Example:
|
Default values are evaluated only once, at the point of function definition. Be careful when using mutable default arguments (like lists or dictionaries).
To avoid this, use
|
Lambda expressions are small, anonymous functions defined using the Syntax:
|
Example:
|
Lambda functions are often used with functions like
|
The scope of a variable refers to the region of the code where the variable is accessible.
Example:
|
To modify a global variable from within a function, you need to use the
|
The most basic way to access code from another module is to do a simple import statement.
This imports the module as a whole, and you need to use the module name to access its contents. |
Accessing functions/attributes after importing a module.
|
Importing with an alias (renaming the module).
This allows you to use a shorter or more descriptive name for the module in your code.
|
Importing a submodule
|
You can import specific functions or attributes from a module using the
This imports only the specified item, making it directly accessible without needing to use the module name. |
Importing multiple items from a module.
This can make your code more concise when you only need a few specific items from a module.
|
Importing an item with an alias.
This is useful for avoiding naming conflicts or using a more descriptive name for the imported item.
|
You can import all names from a module’s symbol table using the
Warning: This is generally discouraged as it can lead to naming conflicts and make your code harder to understand. |
Example of importing all from a module (use with caution!).
It is recommended to explicitly import the names you need to avoid potential issues. |
When you import a module, Python searches for it in a specific order:
|
You can view the module search path using the
This will print a list of directories where Python looks for modules. |
Modifying the module search path (use with caution!).
This allows you to import modules from custom locations, but should be done carefully to avoid conflicts. |
|
Returns a list of valid attributes for that object.
|
|
Every Python module has a special attribute called
|
|
Display the documentation for a function.
|
A package is a way of organizing related modules into a directory hierarchy. Each package directory contains a special file,
|
Importing from a package.
Or:
|
Using
Then:
|
A class is a blueprint for creating objects (instances). It defines attributes (data) and methods (behavior).
|
Example:
|
The
|
Key points about |
Methods are functions defined within a class that operate on the object’s data.
|
Key points about methods:
|
Class variables are variables that are shared by all instances of a class.
|
Key points about class variables:
|
The
|
Key points about
|
The
|
Key points about
|
You can create your own exception classes by inheriting from the built-in
|
Key points about user-defined exceptions:
|
Polymorphism means “many forms”. In object-oriented programming, it refers to the ability of a single interface to represent different types.
|
Key points about polymorphism:
|
Overriding is the ability of a subclass to provide a specific implementation of a method that is already defined in its superclass.
|
Key points about overriding:
|
Inheritance is a mechanism by which a new class (subclass) can be created from an existing class (superclass), inheriting its attributes and methods.
|
Key points about inheritance:
|
|
Opens a file. Common Modes:
|
Example (Read): |
|
Example (Write): |
|
|
Reads at most |
|
Reads a single line from the file (including the newline character). |
|
Reads all lines from the file and returns them as a list of strings. |
Example (Read lines): |
|
|
Writes the contents of |
|
Writes a list of strings to the file. |
Example (Write lines): |
|
|
Closes the file. It is important to close files to free up system resources and ensure that all data is written to disk. |
|
Using the |
Example (with statement): |
|
|
Returns |
|
Returns the file opening mode. |
|
Returns the name of the file. |
|
Deletes the file specified by |
Example: |
|
|
Checks if the file specified by |
Example: |
|
|
Deletes the directory specified by
|
Example (Empty Directory): |
|
Example (Non-Empty Directory): |
|
|
Use |
Example: |
|
Single-line comments start with
|
Multi-line comments (docstrings) are enclosed in triple quotes (
|
Docstrings are used to document functions, classes, modules, and methods.
|
Accessing docstrings: Use
|
Comments should be clear and concise, explaining the purpose of the code. |
Generators are functions that use the |
Instead of returning all values at once, generators produce them one at a time, saving memory. |
Example:
|
Generator expressions are a concise way to create generators using a syntax similar to list comprehensions.
|
Generators are iterable, meaning you can use them in |
The
|
You can convert a generator to a list using the |
Example:
|
Converting a generator to a list requires storing all elements in memory, so be mindful of memory usage for large generators. |
Alternative: Process the generator’s output iteratively instead of converting it to a list if memory is a concern. |
Combining
|
Use
|
You can handle multiple exception types in a single
|
The
|
The
|
Raise exceptions using the
|
List comprehensions provide a concise way to create lists based on existing iterables. |
Syntax: |
Example: Creating a list of squares.
|
Example: Filtering even numbers.
|
List comprehensions can also be used with nested loops.
|
List comprehensions are more readable and often faster than traditional loops for creating lists. |
Lambda functions are anonymous, small, and inline functions defined using the |
Syntax: |
Example: A lambda function that adds two numbers.
|
Lambda functions are often used with functions like |
Example: Using
|
Example: Using
|
Lambda functions can only contain a single expression and cannot include statements or annotations. |