Python Reference
Introduction
Python is a popular and easy-to-learn programming language, making it a great choice for
beginners.
Core Concepts
Programming Basics
Programming: The process of using programming languages to communicate with a
computer.
.py: The file extension for Python scripts.
Modules: Pre-written code that can be used in your programs.
pip: Python's package manager, used to install modules (e.g., pip install flask).
Comments: Explanatory notes in code.
Single-line comments start with #.
Multi-line comments use triple quotes (""" or ''').
Variables and Data Types
Variable: A named memory location.
Data Type: The type of data a variable can store.
Integer (int): Whole numbers (e.g., 1, 2, 3).
Floating-point number (float): Decimal numbers (e.g., 3.14, 2.71).
String (str): Textual data (e.g., "Hello", "Python").
Boolean (bool): True or False.
None: Represents the absence of a value.
Variable Naming Rules:
Can contain letters, numbers, and underscores.
Must start with a letter or underscore.
Cannot start with a number.
Cannot contain whitespace or special characters.
Operators:
Arithmetic Operators: +, -, *, /
Assignment Operators: =, +=, -=
Comparison Operators: ==, !=, >, <, >=, <= (return Boolean values)
Logical Operators: and, or, not (work with Boolean values)
Type Function: type(variable) returns the data type of a variable.
Type Casting: Converting one data type to another (int(), float(), str()).
Input Function: input() takes input from the user. Input is always a string, so type casting may
be needed.
Strings
A string is a sequence of characters.
Strings can be written in single quotes, double quotes, or triple quotes.
Indexing: Accessing characters by their position (starting from 0).
Slicing: Extracting a portion of a string.
string[start:end] (includes start, excludes end).
Negative Indexing: Counting from the end of the string (starting from -1).
Skip Value: string[start:end:skip] (selects every skip character).
Strings are immutable, meaning they cannot be changed after creation.
String Slicing Example
Let's say we have the string a = "HelloWorld".
a[1:7:3]
This means start at index 1, go up to (but don't include) index 7, and take every 3rd character.
1. a[1:7] resolves to "elloWo".
2. Taking every 3rd character gives us "eW".
Therefore, a[1:7:3] evaluates to "eW".
String Functions
len(str): Returns the length of the string.
str.endswith(suffix): Checks if the string ends with the given suffix (case-sensitive).
str.startswith(prefix): Checks if the string starts with the given prefix (case-sensitive).
str.capitalize(): Capitalizes the first character of the string.
str.find(substring): Returns the index of the first occurrence of the substring, or -1 if not
found.
str.replace(old, new): Replaces all occurrences of old with new.
Escape Sequences
\n: Newline
\t: Tab
\": Double quote
\': Single quote
\\: Backslash
f-strings
f"Hello {name}": Allows variable insertion directly into strings.
Lists
Ordered, mutable collections of items.
List Methods
list.append(item): Adds an item to the end of the list.
list.insert(index, item): Inserts an item at a specific index.
list.pop(index): Removes and returns the item at the specified index.
list.sort(): Sorts the list in place.
list.reverse(): Reverses the list in place.
list.remove(value): Removes the first occurrence of the specified value.
Tuples
Ordered, immutable collections of items.
Created with parentheses: (1, 2, 3).
Single-element tuple: (1,).
Tuple Methods
tuple.count(value): Returns the number of times a value appears in the tuple.
tuple.index(value): Returns the index of the first occurrence of a value.
Dictionaries
Unordered collections of key-value pairs. Keys must be unique.
Created with curly braces: {"name": "Harry", "marks": 100}.
Dictionary Methods
dict.items(): Returns a view of key-value pairs.
dict.keys(): Returns a view of keys.
dict.values(): Returns a view of values.
dict.update(other_dict): Updates the dictionary with key-value pairs from another dictionary.
Existing keys are overwritten, new keys are added.
dict.get(key, default): Returns the value for the given key if it exists, otherwise returns default
(or None). Using dict[key] raises an error if the key doesn't exist.
Sets
Unordered collections of unique, immutable elements.
Created with curly braces or set(): {1, 2, 3}, set().
Empty set: set(). {} creates an empty dictionary.
Set Methods
set.add(item): Adds an item to the set.
set.remove(item): Removes an item (raises an error if not found).
set.union(other_set): Returns a new set with all elements from both sets.
set.intersection(other_set): Returns a new set with common elements.
set.issubset(other_set): Checks if all elements of the set are present in another set.
Conditionals
if condition:: Executes code block if the condition is true.
else:: Executes code block if the if condition is false.
elif condition:: Checks another condition if the previous if or elif conditions were false.
Indentation: Code blocks within if, else, and elif are defined by indentation (typically 4
spaces).
Functions
A block of organized, reusable code that performs a specific task.
Function Syntax
def function_name(parameter1, parameter2,...):
# Function body (code to be executed)
return [expression] #Optional return statement
def: Keyword to define a function.
function_name: Identifier for the function (follows variable naming rules).
parameters: Optional input values the function receives (comma-separated).
:: Marks the beginning of the function body.
return: Optional statement to send a value back to the caller.
Function Call
function_name(argument1, argument2,...)
arguments: Values passed to the function corresponding to its parameters.
Types of Functions
Built-in Functions: Predefined functions available in Python (e.g., len(), range(), print()).
User-Defined Functions: Functions created by the programmer.
Arguments and Parameters
Parameters: Variables listed inside the function definition's parentheses.
Arguments: Actual values passed to the function when it's called.
Return Statement
return: Exits the function and optionally returns a value.
If no return statement is present, the function returns None.
Control Flow Statements
break: Terminates the loop immediately.
continue: Skips the current iteration of the loop and proceeds to the next iteration.
pass: A null statement. Does nothing.
For Loops with Else
The else block after a for loop executes if the loop completes normally (i.e., without
encountering a break statement).
for item in iterable:
# Loop body
else:
# Executes if loop completes without a 'break'
Object-Oriented Programming (OOP)
Core Concepts
Class: A template or "blueprint" for creating objects. Defines attributes (data) and methods
(actions).
Object: An instance of a class.
Class Attribute: A variable shared by all instances of the class. Defined directly within the
class.
Instance Attribute: A variable specific to each object. Defined within the methods of the class
(usually in the constructor __init__).
Method: A function defined within a class.
self: A reference to the current object within a method.
Basic Syntax
Defining a Class:
class MyClass:
class_attribute = value
def __init__(self, instance_attribute):
self.instance_attribute = instance_attribute
def my_method(self):
print(self.instance_attribute)
Creating an Object:
my_object = MyClass(attribute_value)
Accessing Attributes:
print(my_object.class_attribute)
print(my_object.instance_attribute)
Calling Methods:
my_object.my_method()
OOP Concepts
Static Method:
Defined using the @staticmethod decorator.
Does not require the self argument.
Useful for functions related to the class but not to a specific object.
__init__ Constructor:
A special method (dunder method) that runs automatically when an object is created.
Takes the self argument.
Used to initialize the object's attributes.
Dunder Methods:
Special methods that start and end with double underscores (__).
Used for object creation, string representation, length calculation, etc.
Examples: __init__, __str__, __len__.
Inheritance:
Allows a class (child class) to inherit attributes and methods from another class (parent
class).
The parent class is also called the base class.
New methods and attributes can be added to the child class.
Types: Single, multiple, multi-level.
Super Method:
Used to access methods and attributes of the parent class from the child class.
Useful for calling the constructor: super().__init__().
Class Method:
Defined using the @classmethod decorator.
Takes the cls argument (refers to the class).
Used to access and modify class attributes.
Property Decorators:
Used to control attribute access.
@property: Allows a method to be accessed like an attribute.
@<attribute>.setter: Allows customizing how an attribute's value is set.
Operator Overloading:
Allows customizing the behavior of operators (+, -, *, /) for class objects.
Done using dunder methods (e.g., __add__, __mul__).
Exception Handling:
Allows handling errors using try...except...finally blocks.
try: Code block where an error might occur.
except: Code block to handle specific errors.
finally: Code block that always executes, whether an error occurs or not.
raise: Used to generate a custom error.
Other Important Concepts:
Walrus Operator :=: Allows assignment and expression in one step.
Type Hinting: Specifying variable and function types for clearer and error-free code.
Match Case: Similar to a switch statement, executes different code blocks based on a
value.
List Comprehension: A concise way to create lists in one line.
Enumerate: Accesses both the index and value of a list simultaneously.
if __name__ == "__main__":: Determines if a script is running directly or imported as a
module.
Global Keyword: Accesses and modifies global variables inside a function.
Advanced Concepts
Virtual Environments (venv)
Purpose: Isolates project dependencies to avoid conflicts.
Commands:
pip install virtualenv: Installs the virtualenv package.
virtualenv <env_name>: Creates a new environment.
. <env_name>/Scripts/activate.ps1: Activates the environment (PowerShell).
deactivate: Deactivates the environment.
pip install <package>==<version>: Installs a specific package version.
pip freeze > requirements.txt: Saves installed packages to a file.
pip install -r requirements.txt: Installs packages from a file.
Lambda Functions
Definition: Anonymous, small, single-expression functions.
Syntax: lambda arguments: expression
Example: square = lambda x: x * x
Join Method
Purpose: Concatenates strings in an iterable with a specified separator.
Syntax: <separator>.join(<iterable>)
Example: "::".join(["Harry", "Rohan", "Shubham"])
Format Method
Purpose: Inserts values into a string at specified positions.
Syntax: "<string>".format(arg1, arg2, ...)
Example: "{} is a good {}".format("Harry", "boy")
Indexing: Use {0}, {1}, etc., to specify argument order.
Map, Filter, Reduce
Map: Applies a function to each item in an iterable.
map(function, iterable)
Filter: Creates a new iterable with items that satisfy a condition.
filter(function, iterable)
Reduce: Applies a function cumulatively to the items of an iterable, reducing it to a single
value.
from functools import reduce
reduce(function, iterable)