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.
Table of Contents
Download a Printable Python Cheat Sheet PDF
Python OperatorsOperators in Python perform operations on values and variables using standard symbols for logic and math.
1. Arithmetic Operators in PythonPython 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 2. Comparison Operators in PythonPython 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 3. Assignment Operators in PythonThe 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) 4. Logical Operators in PythonPython 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=Falsex and y returns False
or Checks for only one condition x=True, y=Falsex or y returns True
not Reverse the output of the boolean value not x returns False 5. Identity Operators in PythonPython 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 6. Membership Operators in PythonPython 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 7. Bitwise Operators in PythonBitwise 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 PythonData types denote the classification of data items, indicating the operations feasible on individual data.
1. Integer Data TypeAn integer in Python is a whole number, positive or negative, without decimals, of unlimited length.
x = 10 y = 20 print(type(x)) # Output: int
Set Yourself Apart in Data Analysis
Analyze Better with Data Analysis Skills
2. Float Data TypeThe 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: float3. 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: bool4. 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: complex5. String data type
A string is a sequence of characters enclosed in single quotes or double quotes.
5.1. Define a stringmy_string = "Hello, World!" my_string = ‘Hello, World!’5.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: !5.3. Length of a string
Len function returns the length of an object print(len(my_string)) # Output: 135.4. String Concatenation
Joining more than one string together
string1 = "Hello" string2 = "Intellipaat" result = string1 + ", " + string2 + "!" print(result) # Output: Hello, Intellipaat!5.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
5.6. String SlicingSlicing 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:])5.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.
Take Your Data Analysis Skills to the Next Level
Gain Insights with Our Data Analysis Training
5.8. String Formatting5.8.1. 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))
5.8.2. 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))
5.8.3. 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}")
5.8.4. 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))6. Lists in Python
A list is a data structure in Python that is a mutable, or changeable, ordered sequence of elements.
6.1. Define a Listmy_list = [1, 2, 3, 4, 5]6.2. Accessing Elements in a List
print(my_list[0]) # Output: 1 print(my_list[2]) # Output: 3 print(my_list[-1]) # Output: 56.3. Length of a List
Len function returns the length of an object
print(len(my_list)) # Output: 56.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]6.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.6. Checking the Membership operator in the listAllows 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: False6.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]
Become a Trusted Name in the Data Analysis Industry
Launch Your Data Analysis Career with Us
6.8. Nested ListsList inside a list is called Nested List
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print(matrix[1][2]) # Output: 66.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()7. 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.
7.1. Creating a dictionarymy_dict = {"key1": "value1", "key2": "value2", "key3": "value3"}7.2. Accessing values in a dictionary
print(my_dict["key1"]) # Output: value1 print(my_dict["key2"]) # Output: value27.3. Length of a dictionary
print(len(my_dict)) # Output: 37.4. Dictionary Methods
7.4.1. 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'}
7.4.2. 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'}
7.4.3. Clearing a dictionary
dict1.clear() # Remove all items in the dictionary print(dict1) # Output: {}7.5. Dictionary Iteration
7.5.1. Iterating over keys
for key in my_dict: print(key) # Output: key1 #key4
7.5.2. Iterating over values
for value in my_dict.values(): print(value) # Output: new_value # value4
7.5.3. Iterating over key-value pairs
for key, value in my_dict.items(): print(key, value) # Output: key1 new_value # key4 value47.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.7. Nested Dictionaries
nested_dict = {"key1": {"nested_key1": "nested_value1"}, "key2": {"nested_key2": "nested_value2"}} print(nested_dict["key1"]["nested_key1"]) # Output: nested_value18. Tuple in Python
In Python, a tuple is an unchangeable ordered collection of elements, defined with parentheses and separated by commas.
8.1. Creating a Tuple:my_tuple = (1, 2, 3, 4, 5)8.2. Accessing Elements in tuple:
first_element = my_tuple[0] # Accessing the first element last_element = my_tuple[-1] # Accessing the last element8.3. Length of a Tuple:
length = len(my_tuple) # Returns the number of elements in the tuple8.4. Iterating Over a Tuple:
for item in my_tuple: print(item)8.5. Tuple Concatenation:
tuple1 = (1, 2, 3) tuple2 = (4, 5, 6) concatenated_tuple = tuple1 + tuple2 # Results in (1, 2, 3, 4, 5, 6)8.6. Tuple Repetition:
repeated_tuple = (1, 2) * 3 # Results in (1, 2, 1, 2, 1, 2)8.7. Checking if an Element Exists in a tuple:
if 3 in my_tuple: print("3 is present in the tuple")8.8. Tuple Methods:
count = my_tuple.count(3) # Returns the number of occurrences of the element 3 in the tuple8.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 tuple8.10. Immutability:
# Attempting to modify a tuple will result in an error # my_tuple[0] = 10 # This will raise an error8.11. Unpacking Tuples:
x, y, z = my_tuple # Unpacking into variables first, *middle, last = my_tuple # Unpacking with asterisk operator9. Sets in Python
In Python, a set is a mutable unordered collection of unique elements, defined using curly braces {} and separated by commas.
9.1. Creating a Setmy_set = {1, 2, 3, 4, 5} # Set with normal elements my_set = {[1,2,3,4,5]} # Set with a list as an element9.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}9.3. Checking the length of the Set
len(my_set) # len will return the total length of the set # Output: 59.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) 9.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}9.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.
9.6.1. Creating the Frozensetfrozen_set = frozenset([1, 2, 3, 4, 5])9.6.2. Operations on frozen sets
print(1 in frozen_set) # Output: True print(len(frozen_set)) # Output: 5Flow 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.
1. Conditional Statements in PythonIn Python, a conditional statement allows for decision-making based on certain conditions.
1.1. If Statementx = 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 51.2. 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 51.3. 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 51.4. 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 152. 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)
3. Logical Operators with Conditional Statements 3.1. AND Operatorx = 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 53.2. 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 53.3. 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 y3.4. 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,23.5. 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,44. 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.
4.1. Syntax:for <variable> in <sequence>: <code block>4.2. 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,44.3. Iterating Over a Sequence of lists using for loop
my_list = [1, 2, 3, 4, 5] for item in my_list: print(item)4.4. Nested for Loop
for i in range(3): for j in range(2): print(i, j)5. 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 loopPython Random Module
In Python, the random module is a built-in module that allows us to generate random elements.
1. Syntaximport random2. seed() method
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)3. randint() method
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)4. choice() method
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)5. shuffle() method
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)6. sample() method
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)7. random() method
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)8. uniform() method
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”) only() 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 = 5print(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 = -5print(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 argumentambianceReturning 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:
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 NameErrorGlobal Scope:
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, AnkitArbitrary 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: 10Kwargs:
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: 10Recursive 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, 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: appleCharacter 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: iQuantifiers:
*: 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: appleAnchors:
^: 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: IGroups 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: appPredefined 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: ApplesObject-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: passObject Creation:
An object in Python is an instance of a class, encapsulating both data (attributes) and behavior (methods).
obj1 = MyClass()
obj2 = MyClass()
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 = ageAccessing Instance Variables
person1 = Person("Rohit", 30) person2 = Person("Ram", 25) print(person1.name) # Output: Rohit print(person2.age) # Output: 25Methods:
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 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: 200Polymorphism:
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.5Dataclasses 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)
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 data class.
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
json_data = json.dumps(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
yaml_data = yaml.dump(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 Filesfile = 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 the
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 directoryException 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.
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)
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))
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
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
Learn what the __call__() method does in Python and how to use it through this blog.
Use Cases: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 tracebackContext 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 blockBuilt-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 databaseSetup.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: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:
include README.md include LICENSE recursive-include my_package/data *.jsonMain: 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 PythonDateTime in Python refers to a module that provides classes for manipulating dates and times.
import datetime # Used to import the library
my_date = datetime.datetime(year, month, day, hour, minute, second)
current_datetime = datetime.datetime.now() # Gives current date and time
formatted_date = my_date.strftime(format_string)
parsed_date = datetime.datetime.strptime(date_string, format_string)
new_date = my_date + datetime.timedelta(days=5)
year = my_date.year month = my_date.month day = my_date.day hour = my_date.hour minute = my_date.minute second = my_date.second
if date1 > date2: # logic goes here
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
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
with zipfile.ZipFile('file.zip', 'r') as zip_ref: zip_ref.extract('file_inside_zip.txt', 'destination_folder') # Extract the file at specified location
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)
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
iter1 = [1, 2, 3] iter2 = ['a', 'b', 'c'] combined_iter = itertools.chain(iter1, iter2) # Combines two iterator into one using chain()
permutations = itertools.permutations(iterable, r) combinations = itertools.combinations(iterable, r)
zipped_iter = itertools.zip_longest(iter1, iter2, fillvalue=None)
flattened_list = itertools.chain.from_iterable(iterables)
Get 100% Hike!
Master Most in Demand Skills Now!
ShelvesA “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
with shelve.open('my_data') as shelf: value = shelf['key']
with shelve.open('my_data') as shelf: del shelf['key']
with shelve.open('my_data') as shelf: if 'key' in shelf: # code to perform any operation
with shelve.open('my_data') as shelf: for key in shelf.keys(): # perform operation with each key
shelf.close()Conclusion
Speed up your Python learning with our other Python cheat sheets – your go-to guide for everything Python.
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.
Please Refer The Free Python Interview Question and for learning data science Refer this Data Science Program.
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.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4