Python Cheat Sheet
Python is a programming language that is interpreted object-oriented and high-level. It has semantics making it ideal for Rapid Application Development and, as a scripting or glue language to connect components. Python’s built-in data structures and dynamic typing make it highly appealing. Its syntax is simple and easy to learn emphasizing readability and reducing program maintenance costs.
Download a Printable Python Cheat Sheet PDF
Check out our video on Python Interview Questions for free and learn essential tips to ace your next interview!
Python Operators
Operators in Python perform operations on values and variables using standard symbols for logic and math.
Arithmetic Operators in Python
Python arithmetic operators are used to perform mathematical operations on numeric values.
Operators |
Function |
Example |
Addition(+) |
Adds two or more values |
10 + 3 = 13 |
Subtraction(-) |
Subtract two or more values |
10 – 3 = 7 |
Multiplication(*) |
Multiply two or more values |
10 * 3 = 30 |
Division(/) |
Divides two or more values |
10 / 3 = 3.333… |
Modulus(%) |
Finds the remainder |
10 % 3 = 1 |
Exponentiation(**) |
Used to raise the number to the power of a number |
10 ** 3 = 1000 |
Floor division(//) |
Gives the floor value |
10 // 3 = 3 |
Comparison Operators in Python
Python comparison operators are used to compare the values of two operands and return True or False based on whether the condition is met.
Operators |
Function |
Example |
Equal to (==) |
Check whether the values are equal |
x == y |
Not Equal to(!=) |
Check whether the values are not equal |
x != y |
Less Than |
Check whether the values are less than the other value |
x < y |
Greater Than |
Check whether the values are greater than the other value |
x > y |
Less than or equal to |
Check whether the values are less than or equal to the other value |
x <= y |
Greater than or equal to |
Check whether the values are greater than or equal to the other value |
x >= y |
Assignment Operators in Python
The assignment operator in Python is used to assign values to variables.
Operators |
Function |
Example |
Equal to(=) |
Assign a value to the variable |
x = 3 |
Addition Assignment Operator (+=) |
Subtracts the value and then assign it to the variable |
x += 3 (x = x + 3) |
Subtraction Assignment Operator (-=) |
Subtract the value and then assign it to the variable |
x -= 3 (x = x – 3) |
Multiplication Assignment Operator (*=) |
Multiply the value and then assign it to the variable |
x *= 3 (x = x * 3) |
Division Assignment Operator (/=) |
Divide the value and then assign it to the variable |
x /= 3 (x = x / 3) |
Modulus Assignment Operator (%=) |
Find the remainder and then assign it to the variable |
x %= 3 (x = x % 3) |
Logical Operators in Python
Python logical operators help us to perform logic operations on nodes, groups, or numbers.
Operators |
Function |
Example |
and |
Checks for one or more conditions together |
x=True, y=False
x and y returns False |
or |
Checks for only one condition |
x=True, y=False
x or y returns True |
not |
Reverse the output of the boolean value |
not x returns False |
Identity Operators in Python
Python identity operators are used to compare the memory location of two objects.
x = [“apple”, “banana”]
y = [“apple”, “banana”]
Operators |
Function |
Example |
is |
Checks if the value is available, if present returns True |
x is y returns True |
Is not |
Check if the value is not present, if not then return True |
x is not y returns False |
Membership Operators in Python
Python membership operators are used to test whether a value or variable exists in a sequence (string, list, tuples, sets, dictionary) or not.
x = [“apple”, “banana”]
Operators |
Function |
Example |
in |
Check if the substring is available, if yes then return True |
“banana” in x |
not in |
Checks if the substring is not available, if yes then returns True else False |
“orange” not in x |
Bitwise Operators in Python
Bitwise operators in Python are used to perform bitwise operations on integers.
x = 10 # Binary: 1010
y = 4 # Binary: 0100
Operators |
Function |
Example |
Bitwise AND(&) |
Performs bitwise and operation on the values |
x & y returns 0 |
Bitwise OR(|) |
Performs bitwise or operation on the values |
x | y returns 14 |
Bitwise XOR(^) |
Performs bitwise xor operation on the values |
x ^ y returns 14 |
Bitwise NOT(~) |
Performs bitwise not operation on the values |
x ~ y returns -11 |
Left Shift(<<) |
Performs left shift on the given value |
x << 1 returns 20 |
Right Shift(>>) |
Performs right shift on the given value |
x >> 1 returns 1 |
Data Types in Python
Data types denote the classification of data items, indicating the operations feasible on individual data.
Integer Data Type
An integer in Python is a whole number, positive or negative, without decimals, of unlimited length.
x = 10
y = 20
print(type(x)) # Output: int
Float Data Type
The float data type in Python is used to represent real numbers with both an integer and fractional component.
x = 4.2
y = 10.5
print(type(x)) # Output: float
Boolean Data Type
The Boolean data type in Python is one of the built-in data types. It represents one of two values: True or False.
x = True
y = False
print(type(x)) # Output: bool
Complex Data Type
The complex data type in Python consists of two values, the first one is the real part and the second one is the imaginary part of the complex number.
x = 2 + 3i
print(type(x)) # Output: complex
String data type
A string is a sequence of characters enclosed in single quotes or double quotes.
1. Define a string
my_string = "Hello, World!"
my_string = ‘Hello, World!’
2. Indexing in a string
The process of accessing the element in a sequence using their position in the sequence is called Indexing
print(my_string[0]) # Output: H
print(my_string[7]) # Output: W
print(my_string[-1]) # Output: !
3. Length of a string
Len function returns the length of an object
print(len(my_string)) # Output: 13
4. String Concatenation
Joining more than one string together
string1 = "Hello"
string2 = "Intellipaat"
result = string1 + ", " + string2 + "!"
print(result) # Output: Hello, Intellipaat!
5. String Methods
Method |
Function |
Example |
replace() |
Replace the desired word with a new word. |
my_str = “Hello Intellipaat”)
my_str.replace(“Hello”, “Hi”)
# Output: “Hi Intellipaat” |
split() |
Splits the words into items of a list where each word is one item. |
x = my_str.split()
# Output: [“Hi”, “Intellipaat”] |
join() |
Joins the words based on a delimiter |
” “.join(x)
# Output: “Hi Intellipaat” |
lower() |
Converts all the text into lowercase |
name = “INTELLIPAAT”
x = name.lower()
# Output: “intellipaat” |
upper() |
Converts all the text into an uppercase |
name = “intellipaat”
x = name.lower()
# Output: “iINTELLIPAAT” |
strip() |
Removes the extra whitespace from the front |
name = ” INTELLIPAAT”
x = name.lower()
# Output: “INTELLIPAAT” |
find() |
Searches for a substring in the main string |
txt = “Hello, welcome to my Intellipaat.”
x = txt.find(“welcome”)
# Output: 7 |
6. String Slicing
Slicing is the extraction of a part of a string, list, or tuple
s = "Python"
print(s[2:5]) # Output: tho
print(s[:4]) # Output: Pyth
print(s[3:])
7. Escape Characters
An escape character is a backslash \ followed by the character you want to insert in the string.
print("This is a \"quote\" inside a string.") # Output: This is a "quote" inside a string.
print("This is a \nnew line.") # Output: This is a # new line.
8. String Formatting
# Old Style Formatting
name = "Alice"
age = 30
# Using placeholders %s (string) and %d (integer) within the string,
# followed by the % operator and a tuple containing the values to substitute.
print("Name: %s, Age: %d" % (name, age))
# str.format() Method
name = "Rohit"
age = 25
# Using `{}` as a placeholder within the string, followed by the `.format()` method
# and passing the values to substitute as arguments to the method.
print("Name: {}, Age: {}".format(name, age))
# Formatted String Literals (f-strings) (Python 3.6+)
name = "Ashish"
age = 35
# Using f-string notation with `{}` placeholders directly within the string,
# and using the variables directly within the curly braces.
print(f"Name: {name}, Age: {age}")
# `Template Strings`
from string import Template
name = "David"
age = 40
# Creating a Template object with placeholders as $variable,
# and using the `substitute()` method to replace placeholders with values.
template = Template("Name: $name, Age: $age")
print(template.substitute(name=name, age=age))
Lists in Python
A list is a data structure in Python that is a mutable, or changeable, ordered sequence of elements.
1. Define a List
my_list = [1, 2, 3, 4, 5]
2. Accessing Elements in a List
print(my_list[0]) # Output: 1
print(my_list[2]) # Output: 3
print(my_list[-1]) # Output: 5
3. Length of a List
Len function returns the length of an object
print(len(my_list)) # Output: 5
4. List Slicing
Slicing is the extraction of a part of a string, list, or tuple
my_list = [1, 2, 3, 4, 5]
print(my_list[1:3]) # Output: [2, 3]
print(my_list[:3]) # Output: [1, 2, 3]
print(my_list[3:]) # Output: [4, 5]
5. List Methods
my_list = [1,2,3,4,5]
Method |
Function |
Example |
append() |
Inserts an element at the end of the list. |
my_list = [1,2,3,4,5]
my_list.append(6)
# Output: [1,2,3,4,5,6] |
insert() |
Insert an element at a particular index in the list. |
my_list.insert(2,10)
# Output: [1,2,10,3,4,5,6] |
pop() |
Removes the last element in the list |
my_list.pop()
# Output: [1,2,10,3,4,5] |
sort() |
Sorts the list in ascending or descending order. |
my_list.sort()
# Output: [1,2,3,4,5,10] |
reverse() |
Reverses the order of the elements of the list |
my_list.reverse()
# Output: [10,5,4,3,2,1] |
6. Checking the Membership operator in the list
Allows you to check the presence or absence of a substring within a given string
print(4 in my_list) # Output: True
print(6 in my_list) # Output: False
7. List Comprehensions
Writing the operation performed on the data within a line or few
squares = [x**2 for x in range(5)]
print(squares) # Output: [0, 1, 4, 9, 16]
8. Nested Lists
List inside a list is called Nested List
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(matrix[1][2]) # Output: 6
9. Copying Lists
Creating a copy of the original list so that the changes do not occur in the original
original_list = [1, 2, 3]
copied_list = original_list.copy()
Dictionary
A dictionary in Python is a collection of key-value pairs. Each key is associated with a value, and you can access the value by using the key.
1. Creating a dictionary
my_dict = {"key1": "value1", "key2": "value2", "key3": "value3"}
2. Accessing values in a dictionary
print(my_dict["key1"]) # Output: value1
print(my_dict["key2"]) # Output: value2
3. Length of a dictionary
print(len(my_dict)) # Output: 3
4. Dictionary Methods
Adding or updating key-value pairs
dict1["key4"] = "value4" # Add new key-value pair
print(dict1) # Output: {'key1': 'value1', 'key2': 'value2', 'key3': 'value3', 'key4': 'value4'}
dict1["key1"] = "new_value" # Update existing value
print(dict1) # Output: {'key1': 'new_value', 'key2': 'value2', 'key3': 'value3', 'key4': 'value4'}
Removing key-value pairs
del dict1["key3"] # Delete a key-value pair
print(dict1) # Output: {'key1': 'new_value', 'key2': 'value2', 'key4': 'value4'}
dict1.pop("key2") # Remove and return the value associated with the key
print(dict1) # Output: {'key1': 'new_value', 'key4': 'value4'}
Clearing a dictionary
dict1.clear() # Remove all items in the dictionary
print(dict1) # Output: {}
5. Dictionary Iteration
Iterating over keys
for key in my_dict:
print(key) # Output: key1
# key4
Iterating over values
for value in my_dict.values():
print(value) # Output: new_value
# value4
Iterating over key-value pairs
for key, value in my_dict.items():
print(key, value) # Output: key1 new_value
# key4 value4
6. Dictionary Comprehensions
squares = {x: x**2 for x in range(5)}
print(squares) # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
7. Nested Dictionaries
nested_dict = {"key1": {"nested_key1": "nested_value1"}, "key2": {"nested_key2": "nested_value2"}}
print(nested_dict["key1"]["nested_key1"]) # Output: nested_value1
Tuple in Python
In Python, a tuple is an unchangeable ordered collection of elements, defined with parentheses and separated by commas.
1. Creating a Tuple:
my_tuple = (1, 2, 3, 4, 5)
2. Accessing Elements in tuple:
first_element = my_tuple[0] # Accessing the first element
last_element = my_tuple[-1] # Accessing the last element
3. Length of a Tuple:
length = len(my_tuple) # Returns the number of elements in the tuple
4. Iterating Over a Tuple:
for item in my_tuple:
print(item)
5. Tuple Concatenation:
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
concatenated_tuple = tuple1 + tuple2 # Results in (1, 2, 3, 4, 5, 6)
6. Tuple Repetition:
repeated_tuple = (1, 2) * 3 # Results in (1, 2, 1, 2, 1, 2)
7. Checking if an Element Exists in a tuple:
if 3 in my_tuple:
print("3 is present in the tuple")
8. Tuple Methods:
count = my_tuple.count(3) # Returns the number of occurrences of the element 3 in the tuple
9. Finding the Index of an Element in tuple:
index = my_tuple.index(3) # Returns the index of the first occurrence of the element 3 in the tuple
10. Immutability:
# Attempting to modify a tuple will result in an error
# my_tuple[0] = 10 # This will raise an error
11. Unpacking Tuples:
x, y, z = my_tuple # Unpacking into variables
first, *middle, last = my_tuple # Unpacking with asterisk operator
Sets in Python
In Python, a set is a mutable unordered collection of unique elements, defined using curly braces {} and separated by commas.
1. Creating a Set
my_set = {1, 2, 3, 4, 5} # Set with normal elements
my_set = {[1,2,3,4,5]} # Set with a list as an element
2. Adding an element in Set
my_set.add(4) # This will add 4 to the set at a random place
# Output: {1,2,3,4}
3. Checking the length of the Set
len(my_set) # len will return the total length of the set
# Output: 5
4. Set Methods
Method |
Explanation |
Example |
add() |
Adds an element to the set |
my_set.add(10) |
pop() |
Removes an element from the set |
my_set.pop() |
remove() |
Removes a specific element from the set |
my_set.remove(10) |
update() |
Add multiple elements to the set |
my_set.update([7,8,9]) |
clear() |
Removes all the elements of the set |
my_set.clear() |
union |
Gives only the unique elements from the sets |
my_set.union(my_set1) |
intersection |
Gives the common elements from the sets |
my_set.intersection(my_set1) |
5. Set Comprehensions
x = {0,1,2,3,4}
squares = {x**2 for x in range(5)} # Performs the operation on the set elements
# Output: {0, 1, 4, 9, 16}
6. Frozen Set
Immutable sets are called Frozen Sets. Once created elements cannot be added or removed. It can be used as a key in the dictionary.
Creating the Frozenset
frozen_set = frozenset([1, 2, 3, 4, 5])
Operations on frozen sets
print(1 in frozen_set)
# Output: True
print(len(frozen_set))
# Output: 5
Flow Control Statements in Python
Flow control statements in Python are used to control the flow of execution of a program. They allow you to make decisions about which code to execute and when to execute it.
Conditional Statements in Python
In Python, a conditional statement allows for decision-making based on certain conditions.
If Statement
x = 10
if x > 5:
# Checks for the condition to be True or False
print("x is greater than 5")
# If True then this line of code gets executed
# Output: x is greater than 5
If-else statement
x = 4
if x > 5: # Checks for the condition
print("x is greater than 5") # Runs if the condition is True
else:
print("x is less than or equal to 5") # Runs if the condition is False
# Output: x is less than or equal to 5
If-elif-else statement
x = 3
if x > 5: # Checks for the first condition
print("x is greater than 5") # Runs if the first condition is True
elif x == 5: # Checks for the second condition when the first condition becomes False
print("x is equal to 5") # Runs if the condition is True
else:
print("x is less than 5") # Runs if both the condition becomes False
# Output: x is less than 5
Nested if Statements
If inside an if statement is called nested if
x = 10
if x > 5: # Check for the condition that goes inside the block
if x ; 15: # Again checks for the condition, if True moves inside the if block
print("x is between 5 and 15") # Runs if the condition is True
else:
print("x is greater than or equal to 15") # Runs if the condition is False
else:
print("x is less than or equal to 5") # Runs if the condition is False
# Output: x is between 5 and 15
Ternary Operator
The ternary operator in Python is a concise way to write conditional expressions in a single line.
x = 10
result = “x is greater than 5” if x > 5 else “x is less than or equal to 5” # CombinedIf-else
print(result)
Logical Operators with Conditional Statements
AND Operator
x = 10
y = 6
if x > 5 and y > 5: # Checks for both the condition
print("Both x and y are greater than 5")
# Executes only if both the condition is true
# Output: Both x and y are greater than 5
OR Operator
x =2
y = 6
if x > 5 or y > 5: # Checks for both the condition
print("Either x or y is greater than 5")
# Executes even if one of the conditions is True
# Output: Either x or y is greater than 5
NOT Operator
x = 5
y = 6
if not x == y: # Checks for the condition
print("x is not equal to y")
# Runs if the condition is True
# Output: x is not equal to y
break Statement
The break statement immediately exits the loop and continues with the code following the loop as soon as it meets the break
i = 0
while i < 5:
if i == 3:
break # The loop will exit
i++
# Output: m 0,1,2
continue Statement
The continue statement immediately skips to the next iteration as soon as the condition is satisfied
i = 0
while i < 5:
if i == 3:
continue # The loop will exit
i++
# Output:m 0,1,2,4
For Loop in Python
A for loop in Python is a programming construct that allows us to execute a block of code repeatedly until a certain condition is met.
Syntax:
for <variable> in <sequence>:
<code block>
Iterating Over a Range using for loop
for i in range(5): # Executes the below line of code 5 times
print(i)
# Output: 0,1,2,3,4
Iterating Over a Sequence of lists using for loop
my_list = [1, 2, 3, 4, 5]
for item in my_list:
print(item)
Nested for Loop
for i in range(3):
for j in range(2):
print(i, j)
While Loop in Python
A while loop in Python is a programming construct that allows us to execute a block of code repeatedly, as long as a certain condition is met.
i = 0
while i < 5: # Loop executes as long as i is less than 5
print(i) # Output: 0, 1, 2, 3, 4
i += 1 # Increment i to eventually terminate the loop
Python Random Module
In Python, the random module is a built-in module that allows us to generate random elements.
Syntax:
import random
seed() is used to initialize the random number generator.
import random
# Generate a sequence of random numbers with the same seed
random.seed(42)
print(random.random()) # Output: 0.6394267984578837
print(random.random()) # Output: 0.025010755222666936
# Reinitialize the random number generator with the same seed
random.seed(42)
print(random.random()) # Output: 0.6394267984578837 (same as previous)
print(random.random()) # Output: 0.025010755222666936 (same as previous)
# Generate a different sequence with a different seed
random.seed(123)
print(random.random()) # Output: 0.052363598850944326 (different from previous)
print(random.random()) # Output: 0.08718667752263232 (different from previous)
The randint() method returns an integer number from the selected specified range.
Syntax:
random.randint(start: int, stop: int)
import random
# Generate a random integer between -100 and 100
random_number = random.randint(-100, 100)
print("Random number between -100 and 100:", random_number)
# Generate a random integer between 1 and 6 (inclusive), simulating a six-sided die roll
die_roll = random.randint(1, 6)
print("Die roll result:", die_roll)
The choice method returns a randomly selected element from an iterable, like a list, set, or str:
import random
# List of different names
names = ['Sophia', 'Liam', 'Olivia', 'Noah']
# Randomly choose a name from the list
random_name = random.choice(names)
print("Randomly selected name:", random_name)
The shuffle method takes in an iterable and shuffles it:
import random
# List of numbers
numbers = [1, 2, 3, 4, 5]
# Shuffle the list in place
random.shuffle(numbers)
# Print the shuffled list
print("Shuffled list:", numbers)
sample returns a list with a random selection from an iterable. The number of elements returned is equal to the k parameter:
Syntax:
random.sample(iterable, k: int)
import random
# Population of letters
letters = ['a', 'b', 'c', 'd', 'e']
# Select a sample of 3 unique letters from the population
sampled_letters = random.sample(letters, 3)
# Print the sampled letters
print("Sampled letters:", sampled_letters)
The random method returns a random floating point number between 0.0 and 1.0:
import random
# Generate a random floating-point number between 0 and 1
random_number = random.random()
# Print the random number
print("Random number:", random_number)
The uniform method is similar to randint, but returns a floating point number:
import random
# Generate a random floating-point number between 3.0 and 7.0
random_number = random.uniform(3.0, 7.0)
# Print the random number
print("Random number:", random_number)
Functions in Python
A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function.
In Python, a function is defined using the def keyword:
Syntax:
def function_name(parameters):
"""function_docstring"""
# function body
return result
Example:
def greet(name):
print("Hello, " + name)
Built-in Functions
Function |
Explanation |
Example |
print() |
Prints objects to the text stream file or other file-like objects |
print(“Hello, Intellipaat”) |
len() |
This will return the length of the object |
my_list = [1, 2, 3, 4, 5]
print(len(my_list)) # Output: 5 |
input() |
Used to take user input |
x = input(“Enter any number:”)
print(x)
# If the user enters 10 then the output will be 10 |
type() |
Returns the type of an object |
x = 5
print(type(x)) # Output: <class ‘int’> |
range() |
Generates a sequence of numbers |
numbers = list(range(5))
print(numbers) # Output: [0, 1, 2, 3, 4] |
sum() |
Returns the sum of a sequence of numbers |
numbers = [1, 2, 3, 4, 5]
print(sum(numbers)) # Output: 15 |
abs() |
Returns the absolute value of a number |
x = -5
print(abs(x)) # Output: 5 |
sorted() |
Returns a new sorted list from the elements of any iterable |
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
print(sorted(numbers)) # Output: [1, 1, 2, 3, 4, 5, 6, 9] |
max() |
Returns the maximum value of the sequence |
numbers = [1, 2, 3, 4, 5]
print(max(numbers)) # Output: 5 |
Parameters and Arguments:
Parameters: Parameters refer to the variables defined during the creation of a function, used to receive input values when the function is called
Arguments are the values passed into a function when it is called, corresponding to the parameters defined in the function’s definition.
def greet(name, message): # Creation of function with def keyword
print(message + ", " + name)
greet(message="Good morning", name="Intellipaat")
# Calling the function and passing the argumentambiance
Returning Values from Functions:
We can return values from a function using the return statement.
def minus(x, y):
return x - y
result = minus(3, 5)
Local and Global Scope:
Local Scope:
- Variables defined within a function are considered to be in the local scope of that function.
- These variables can only be accessed within the function where they are defined.
def my_function():
x = 10 # Local variable
print("Inside function:", x)
my_function()
# Trying to access the local variable outside the function will raise an error
# print("Outside function:", x) # This will raise NameError
Global Scope:
- Variables defined outside of any function or in the global scope are considered global variables.
- Global variables can be accessed and modified from anywhere in the code, including inside functions.
y = 20 # Global variable
def my_function():
print("Inside function accessing global variable:", y)
my_function()
Function modifying global variables using the global keyword:
z = 30 # Global variable
def modify_global_variable():
global z
z += 5 # Modifying the global variable
print("Before modification:", z)
modify_global_variable()
print("After modification:", z)
Default Parameters:
Default values can be assigned to parameters in a function, ensuring that if no argument is provided for a parameter during a function call, the default value will be used.
def greet(name="Intellipaat"):
print("Hello, " + Intellipaat)
greet() # Output: Hello, World
greet("Ankit")# Output: Hello, Ankit
Arbitrary Number of Arguments:
We can define functions that accept an arbitrary number of arguments using *args or **kwargs.
*args:
def sum_all(*args):
total = 0
for num in args:
total += num
return total
print(sum_all(1, 2, 3, 4)) # Output: 10
Kwargs:
def display_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
# Calling the function with keyword arguments
display_info(name="Alice", age=30, city="New York")
Lambda Functions (Anonymous Functions):
Small, anonymous functions defined using the lambda keyword are called the Lambda Function.
square = lambda x: x * 2
print(square(5)) # Output: 10
Recursive Functions:
A function calling a function is called the Recursive Function. They are useful for solving problems that can be broken down into smaller and similar subproblems.
def factorial(a):
if a == 0:
return 1
else:
return a * factorial(a-1) # The function is called again
print(factorial(5)) # Output: 120
Regex in Python:
Regex, or Regular Expression is a pattern-matching language used to search, manipulate, and validate text data efficiently and flexibly.
Normal Characters:
import re
pattern = r'apple'
text = 'I like apples'
match = re.search(pattern, text)
if match:
print('Found:', match.group()) # Output: Found: apple
Character Classes:
[ ]: Matches any single character within the brackets.
import re
pattern = r'[aeiou]'
text = 'I like apples'
match = re.search(pattern, text)
if match:
print('Found:', match.group())
# Output: Found: i
Quantifiers:
*: Matches zero or more occurrences of the preceding character or group.
import re
pattern = r'ap*le'
text = 'I like apple'
match = re.search(pattern, text)
if match:
print('Found:', match.group()) # Output: Found: apple
Anchors:
^: Matches the start of the string
import re
pattern = r'^I'
text = 'I like apples'
match = re.search(pattern, text)
if match:
print('Found:', match.group()) # Output: Found: I
Groups and Capturing:
( ): Groups multiple tokens together.
import re
pattern = r'(app)les'
text = 'I like apples'
match = re.search(pattern, text)
if match:
print('Found:', match.group(1)) # Output: Found: app
Predefined Character Classes:
\d: Matches any digit character.
Modifiers:
i: Case-insensitive matching.
import re
pattern = r'apple'
text = 'I like Apples'
match = re.search(pattern, text, re.IGNORECASE)
if match:
print('Found:', match.group()) # Output: Found: Apples
Object-Oriented Programming (OOPs) in Python
Object-oriented programming (OOP) is a programming paradigm based on the concept of objects, which encapsulate data and methods. It promotes code organization, reusability, and abstraction.
Class:
A class in Python is a blueprint for creating objects. It defines the attributes and methods common to all objects of that type.
Syntax:
class MyClass:
pass
Object Creation:
An object in Python is an instance of a class, encapsulating both data (attributes) and behavior (methods).
obj1 = MyClass()
obj2 = MyClass()
Instance Variables and Initialization.
Instance variables in Python are variables that are defined within the methods of a class and belong to a specific instance of that class. They are unique to each object created from the class and hold data that is specific to that instance.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
Accessing Instance Variables
person1 = Person("Rohit", 30)
person2 = Person("Ram", 25)
print(person1.name) # Output: Rohit
print(person2.age) # Output: 25
Methods:
Actions that can be performed by the object in the class are called Methods.
class Dog:
def bark(self):
print(“Woof!”)
dog = Dog()
dog.bark() # Output: Woof!
Inheritance:
Inheritance in Python is a mechanism where a new class inherits properties and behaviors from an existing class, allowing for code reuse and creating a hierarchical relationship between classes.
Animal:
def speak(self):
pass
class Dog(Animal):
def speak(self):
print("Woof!")
dog = Dog()
dog.speak()
# Output: Woof!
Encapsulation:
Encapsulation in Python refers to the bundling of data and methods within a class, hiding the internal state of an object from outside access and modification.
class Car:
def __init__(self):
self.__max_speed = 200
def drive(self):
print(f"Driving at max speed: {self.__max_speed}")
car = Car()
car.drive() # Output: Driving at max speed: 200
Polymorphism:
Polymorphism in Python refers to the ability of different objects to respond to the same method call in different ways.
class Animal:
def speak(self):
pass
class Dog(Animal):
def speak(self):
print("Woof!")
class Cat(Animal):
def speak(self):
print("Meow!")
animals = [Dog(), Cat()]
for animal in animals:
animal.speak()
# Outputs: Woof! Meow!
Class and Static Methods:
A class method in Python is a method that belongs to the class rather than an instance. It is decorated with the @classmethod decorator and takes the class itself (cls) as the first argument instead of the instance.
A static method in Python is a method bound to the class rather than the object instance. It does not require access to object or class state and is defined using the @staticmethod decorator.
class Math:
@classmethod
def add(cls, x, y):
return x + y
class Utility:
@staticmethod
def greet(name):
return f"Hello, {name}!"
sum_result = Math.add(3, 5)
greeting = Utility.greet("Virat")
Class Attributes:
Class attributes in Python are variables defined within a class that are shared by all instances of that class. They are accessed using the class name rather than instance variables.
class Circle:
pi = 3.14
def __init__(self, radius):
self.radius = radius
def area(self):
return Circle.pi * self.radius ** 2
print(Circle.pi) # Output: 3.14
circle = Circle(5)
print(circle.area()) # Output: 78.5
Dataclasses in Python:
Dataclasses in Python provide a simple way to create classes primarily used for storing data. They automatically generate special methods like __init__(), __repr__(), __eq__(), and more, based on class variables, reducing boilerplate code.
To create a dataclass, use the “dataclass” decorator from the dataclasses module. Define class attributes within the class.
Dataclasses generate methods are `__init__`, `__repr__`, `__eq__`, and `__hash__`.
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
p = Point(3, 4)
print(p) # Output: Point(x=3, y=4)
-
Default Values and Type Hints:
An assignment in the attribute declaration gives default values.
from dataclasses import dataclass
@dataclass
class Rectangle:
width: int = 0
height: int = 0
r = Rectangle(width=5)
print(r) # Output: Rectangle(width=5, height=0)
A process for creating immutable sets that shields them from errors and unintended alterations.
from dataclasses import dataclass
@dataclass(frozen=True)
class Point:
x: int
y: int
p = Point(3, 4)
p.x = 5 # This will raise a TypeError since p is immutable
Dataclasses support inheritance, and you can add additional methods in a dataclass.
from dataclasses import dataclass
@dataclass
class Person:
name: str
age: int
def greet(self):
return f"Hello, my name is {self.name} and I am {self.age} years old."
p = Person("Rohit", 30)
print(p.greet()) # Output: Hello, my name is Rohit and I am 30 years old.
JSON and YAML
JSON
JSON is based on JavaScript syntax and is widely used for transmitting data between a server and a web application.
import json
-
Encode Python Object to JSON
json_data = json.dumps(python_object)
-
Decode JSON to Python Object
python_object = json.loads(json_data)
with open('file.json', 'r') as file:
python_object = json.load(file)
with open('file.json', 'w') as file:
json.dump(python_object, file)
YAML
YAML, on the other hand, aims to be human-readable and is often used for configuration files and data serialization.
import pyyaml
-
Encode a Python Object to YAML
yaml_data = yaml.dump(python_object)
-
Decode YAML to a Python Object
python_object = yaml.load(yaml_data, Loader=yaml.Loader)
with open('file.yaml', 'r') as file:
python_object = yaml.load(file, Loader=yaml.Loader)
with open('file.yaml', 'w') as file:
yaml.dump(python_object, file)
yaml.dump(python_object, file, default_flow_style=False)
Files and Directory Path in Python
Files in Python represent a collection of data stored on a storage device, while directory paths specify the location of files or directories within a file system. Can be used to read and write a file
Working with Files
file = open('filename.txt', 'r') # Open for reading
file = open('filename.txt', 'w') # Open for writing (truncate existing)
file = open('filename.txt', 'a') # Open for writing (append to end)
file.close() # Closes the file
content = file.read() # Reads entire file
content = file.read(size) # Reads specified number of bytes
content = file.readline() # Reads one line
content = file.readlines() # Reads all lines into a list
file.write('text') # Writes text to file
file.writelines(['line1', 'line2']) # Writes a list of lines to file
for line in file:
print(line)
'r': Read (default mode)
'w': Write (truncate existing)
'a': Append (write to end)
'b': Binary mode (e.g., 'rb' for reading binary)
'+': Read/write mode (e.g., 'r+' for reading and writing)
Working with Directories
To work with directories, you will need to import the module called os.
import os
import os
contents = os.listdir('path') # Lists directory contents
os.makedirs('path/to/directory') # Creates directories recursively
os.rename('old_name', 'new_name') # Renames a file or directory
os.replace('old_name', 'new_name') # Same as rename, but overwrites if new_name already exists
os.rename('path/to/old_location', 'path/to/new_location') # Moves a file or directory
os.remove('filename.txt')
# Removes a file
os.rmdir('path/to/empty_directory')
# Removes an empty directory
os.removedirs('path/to/empty_directories')
# Removes empty directories recursively
os.path.exists('path') # Checks if path exists
os.path.isfile('filename.txt') # Checks if path is a file
os.path.isdir('path/to/directory') # Checks if path is a directory
Exception Handling in Python
Exception handling in Python refers to the process of managing and responding to errors or exceptional situations that occur during the execution of a program. It involves using try, except, and finally blocks to handle exceptions gracefully and prevent program crashes.
try: Encloses the code where exceptions may occur.
except: Catches and handles exceptions raised in the try block.
else: Executes if no exceptions occur in the try block.
finally: Executes regardless of whether exceptions occur.
-
Handling Specific Exceptions:
try:
# Code that may raise an exception
except ValueError:
# Handle ValueError
except ZeroDivisionError:
# Handle ZeroDivisionError
except Exception as e:
# Handle any other exception
print("An error occurred:", e)
-
Catching Multiple Exceptions:
try:
# Code that may raise an exception
except (ValueError, ZeroDivisionError) as e:
# Handle ValueError or ZeroDivisionError
print("An error occurred:", e)
try:
# Code that may raise an exception
except:
# Handle any exception (not recommended for clean code)
raise ValueError("Invalid value")
class CustomError(Exception):
pass
raise CustomError("Custom error message")
try:
# Code that may raise an exception
except:
# Handle exception
else:
# Execute if no exception occurs
print("No exceptions occurred")
try:
# Code that may raise an exception
except:
# Handle exception
finally:
# Execute regardless of exceptions
print("Finally block executed")
try:
# Code that may raise an exception
except Exception as e:
print("Type:", type(e))
print("Message:", str(e))
-
Handling Exceptions in List Comprehensions:
result = [value / 0 for value in range(5) if value != 0 except ZeroDivisionError]
import logging
try:
# Code that may raise an exception
except Exception as e:
logging.exception("An error occurred:")
Decorators in Python
Decoratrs in Python are functions that modify the behavior of other functions or methods. They allow you to add functionality to existing code without modifying its structure.
Syntax:
def decorator(func):
def wrapper(*args, **kwargs):
# Add extra functionality here
return func(*args, **kwargs)
return wrapper
@decorator
def function():
pass
-
Example: Logging Decorator
def log(func):
def wrapper(*args, **kwargs):
print(f"Calling function {func.__name__} with arguments {args}, {kwargs}")
return func(*args, **kwargs)
return wrapper
@log
def add(a, b):
return a + b
result = add(2, 3)
# Output: Calling function add with arguments (2, 3), {}
def repeat(n):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(n):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@repeat(3)
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
# Output: Hello, Alice!
# Hello, Alice!
# Hello, Alice!
@staticmethod: Declares a static method in a class.
@classmethod: Declares a class method in a class.
@property: Defines a property in a class.
@decorator1
@decorator2
def function():
pass
class Decorator:
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
# Add extra functionality here
return self.func(*args, **kwargs)
@Decorator
def function():
pass
Use Cases:
- Logging: Log function calls and arguments.
- Authorization: Check user permissions before executing a function.
- Caching: Store the results of function calls for future use.
- Validation: Validate function arguments before execution.
Debugging in Python
Debugging in Python refers to the process of identifying and resolving errors or defects in a program, ensuring it behaves as intended.
To debug the code import pdb and use pdb.set_trace() to set breakpoints in your code.
After importing use these commands
n (next), c (continue), s (step), q (quit), l (list), p (print), h (help), etc.
import pdb # importing the library
def some_function():
x = 5
pdb.set_trace() # using the set_trace() function
print("Value of x:", x)
some_function()
Import the taceback module to print detailed information at the time of execution
import traceback #importing traceback library
try:
x = 1 / 0
except ZeroDivisionError:
traceback.print_exc() # using traceback
Context Manager in Python
A context manager in Python is a tool for managing resources, providing a convenient way to handle setup and cleanup actions within a specific context using the with statement.
Syntax:
with context_manager() as alias:
# Code block
Automatically calls __enter__() method before block execution and __exit__() method after.
Handles resource cleanup and exception handling automatically.
Implementing Context Managers:
from contextlib import contextmanager
@contextmanager
def my_context_manager():
# Code executed before entering the block
yield resource
# Code executed after exiting the block
class MyContextManager:
def __enter__(self):
# Code executed before entering the block
return resource
def __exit__(self, exc_type, exc_value, traceback):
# Code executed after exiting the block
with outer_context() as oc:
with inner_context() as ic:
# Code block
Built-in Context Managers:
with open('file.txt', 'r') as f:
# Code to read from file
import threading
lock = threading.Lock()
with lock:
# Code block protected by the lock
import sqlite3
with sqlite3.connect('database.db') as conn:
# Code block accessing database
Setup.py in Python
A setup.py file in Python contains metadata for a package, including its name, version, author, and dependencies. It’s used for package installation and distribution.
Required Imports:
from setuptools import setup, find_packages
Metadata:
- name: Name of the package.
- version: The version number of the package.
- author: Author’s name.
- author_email: Author’s email address.
- description: Short description of the package.
- long_description: Detailed description of the package (usually from a README file).
- url: URL for the project homepage or repository.
- license: License for the package.
Example setup.py:
setup(
name='my_package',
version='0.1',
author='intellipaat',
author_email='[email protected]',
description='A Python package',
long_description=open('README.md').read(),
long_description_content_type='text/markdown',
url='https://github.com/example/my_package',
license='MIT',
packages=find_packages(),
install_requires=[
'dependency1',
'dependency2',
],
)
Additional Options:
- packages: List of packages to include in the distribution.
- install_requires: List of dependencies required for the package.
- entry_points: Specify executable scripts or console scripts.
- classifiers: List of trove classifiers for categorizing the package.
- keywords: List of keywords describing the package.
- package_data: Additional data files to include in the package.
- include_package_data: Flag indicating whether to include package data files.
- extras_require: Define additional dependencies for extra features.
Building and Distributing:
- Build: Run python setup.py build to build the package.
- Install: Run python setup.py install to install the package.
- Distribution: Run python setup.py sdist to create a source distribution.
- Upload: Use twine or setuptools to upload the distribution to PyPI.
Example MANIFEST.in:
include README.md
include LICENSE
recursive-include my_package/data *.json
Main: Top-Level Script in Python
The main function in Python is not inherently special like in some other programming languages, but it’s a convention often used to denote the entry point of a script or program.
def main():
# Your main code logic here
print("Hello, world!")
if __name__ == "__main__":
main()
def main(): This defines a function named main. This is where you’ll put the main logic of your script.
if __name__ == “__main__”: This condition checks if the script is being run directly by the Python interpreter. If it is, it executes the code block beneath it.
main(): This line calls the main function when the script is executed directly.
DateTime in Python
DateTime in Python refers to a module that provides classes for manipulating dates and times.
-
Importing the datetime library
import datetime # Used to import the library
-
Creating a datetime object
my_date = datetime.datetime(year, month, day, hour, minute, second)
current_datetime = datetime.datetime.now() # Gives current date and time
-
Formatting a datetime object
formatted_date = my_date.strftime(format_string)
-
Parsing a string to datetime
parsed_date = datetime.datetime.strptime(date_string, format_string)
new_date = my_date + datetime.timedelta(days=5)
-
Accessing components of a datetime object
year = my_date.year
month = my_date.month
day = my_date.day
hour = my_date.hour
minute = my_date.minute
second = my_date.second
-
Comparing datetime objects
if date1 > date2:
# logic goes here
-
Converting a timestamp to a datetime object
timestamp = datetime.datetime.fromtimestamp(timestamp)
Zipfile
ZipFile in Python is a module that allows manipulation of ZIP archives.
import zipfile # Allows you to use the zipfile module
with zipfile.ZipFile('file.zip', 'r') as zip_ref:
zip_ref.extractall('destination_directory') # extractall will extract the contents of zip file
with zipfile.ZipFile('file.zip', 'w') as zip_ref:
zip_ref.write('file.txt', 'file_in_zip.txt') # write() will allow you to write in the file in
# inside zip file
-
Adding files to an existing ZIP file
with zipfile.ZipFile('file.zip', 'a') as zip_ref:
zip_ref.write('new_file.txt', 'new_file_in_zip.txt') # Adding a new file in the zip
-
Extracting a single file from a ZIP archive
with zipfile.ZipFile('file.zip', 'r') as zip_ref:
zip_ref.extract('file_inside_zip.txt', 'destination_folder') # Extract the file at specified location
-
Listing contents of a ZIP file
with zipfile.ZipFile('file.zip', 'r') as zip_ref:
file_list = zip_ref.namelist() # Assigns all the files to the file_list variable
print(file_list)
-
Checking if a file exists in a ZIP archive
with zipfile.ZipFile('file.zip', 'r') as zip_ref:
if 'file_inside_zip.txt' in zip_ref.namelist():
print('File exists in ZIP archive.')
else:
print('File does not exist in ZIP archive.')
Itertools
Itertools is a Python module providing functions to create iterators for efficient looping, combining, and manipulating data.
import itertools # imports the module for use
count_iterator = itertools.count(start=0, step=1) # From where to start and step count
cycle_iterator = itertools.cycle([1, 2, 3]) # Range
repeat_iterator = itertools.repeat('Hello', times=3) # How many times to repeat
-
Combining multiple iterables
iter1 = [1, 2, 3]
iter2 = ['a', 'b', 'c']
combined_iter = itertools.chain(iter1, iter2) # Combines two iterator into one using chain()
-
Permutations and Combinations
permutations = itertools.permutations(iterable, r)
combinations = itertools.combinations(iterable, r)
-
Iterating over multiple iterables simultaneously
zipped_iter = itertools.zip_longest(iter1, iter2, fillvalue=None)
-
Flattening a list of iterables
flattened_list = itertools.chain.from_iterable(iterables)
Shelves
A “shelf” works like a permanent dictionary. Unlike “dbm” databases, shelves can store all sorts of Python things as values, not just keys, while still acting like a dictionary.
import shelve # Helps to import and use the shelve module
with shelve.open('filename') as shelf:
# Access shelf contents inside this block
with shelve.open('my_data') as shelf:
shelf['key'] = value
-
Retrieving data from a shelf
with shelve.open('my_data') as shelf:
value = shelf['key']
-
Deleting data from a shelf
with shelve.open('my_data') as shelf:
del shelf['key']
-
Checking if a key exists in a shelf
with shelve.open('my_data') as shelf:
if 'key' in shelf:
# code to perform any operation
-
Iterating over keys in a shelf
with shelve.open('my_data') as shelf:
for key in shelf.keys():
# perform operation with each key
shelf.close()
FAQs
What is a cheat sheet in Python?
A Python cheat sheet is a quick reference guide summarizing key syntax, commands, and concepts. It helps developers recall information easily while coding, serving as a handy tool for efficiency.
How to learn Python for beginners?
The best way for beginners to learn Python is to start with the fundamentals like variables, data types, conditionals, and loops. Practice with interactive tutorials and small projects.
What is a cheat sheet in programming?
A programming cheat sheet condenses essential programming elements like syntax, functions, and commands into a concise, accessible format. It assists programmers in recalling important data quickly during development tasks.
How do you make a cheat sheet?
Crafting a cheat sheet involves organizing key information logically, using bullet points, tables, or diagrams. Condense concepts into easily digestible sections, ensuring clarity and relevance for quick reference.