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
Watch the Python Interview Questions tutorial:
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 |
Learn Python from basics to advance. Enroll in Python course in Bangalore!
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
Take your Python programming skills to the next level with Python NumPy!
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
Have a look at our blog on Python modules and frameworks to learn more!
Functions
A function is a block of code that only runs when it is called. We can pass data (or parameters) into a function, and after executing the function, it will return the data as a result.
def new_function():
print(“Hello World”)
new_function()
Lambda Function
A lambda function is a small anonymous function. It can take any number of arguments but can only have one expression.
lambda a,b: a+b
lambda a,b: a*b
Generic Operations
In Python, we have a huge list of Python built-in functions. Some of them are mentioned as follows:
- range(5): 0,1,2,3,4
- S=input(“Enter:”)
- Len(a): Gives item count in a
- min(a): Gives minimum value in a
- max(a): Gives maximum value in a
- sum(a): Adds up items of an iterable and returns sum
- sorted(a): Sorted list copy of a
- importing modules: import random
File Operations:
In Python, we have several functions for creating, reading, updating, and deleting files. The ‘open()’ function takes two parameters that are filename and mode.
There are four different methods (or modes) for opening a file, which are mentioned below:
There are four different modes for opening a file:
- “r” (Read): This is the default mode. It opens a file for reading, and if the file does not exist, it raises an error.
- “a” (Append): This mode opens a file for appending data. If the file does not exist, it creates a new file.
- “w” (Write): This mode opens a file for writing data. If the file does not exist, it creates a new file. If the file already exists, it truncates the file and overwrites its contents.
- “x” (Create): This mode creates a new file. If the file already exists, it raises an error.
To open a file, you can use the ‘open()’ function and assign the returned file object to a variable.
For example:
f = open("File Name", "opening mode")
Here, “File Name” should be replaced with the actual name of the file you want to open, and “opening mode” should be replaced with the desired mode, such as “r” for read, “w” for write, “a” for append, or “r+” for both read and write operations.
Try and Except Blocks
The try block allows us to test a block of code for errors. The except block allows us to handle the error. Refer to the example mentioned below:
try:
[Statement body block]
raise Exception()
except Exception as e:
[Error processing block]
Oops Concepts
Python is an object-oriented programming language. In Python, almost everything is an object with its own properties and methods. Here, a class is like an object constructor or “blueprint” for creating objects.
- Inheritance: A process of using details from a new class without modifying the existing class.
- Polymorphism: A concept of using common operations in different ways for different data inputs.
- Encapsulation: Hiding the private details of a class from other objects.
An Example of a Class/Object
Class: class Pen:
pass
object:obj=Pen()
Comments
Single line comments in Python start with the hash character, ‘#,’ and multiline comments should be used with “““triple quotes”””
# Single Line Comment
"""
Multi-line comment
"""
With this, we come to the end of the Python Basics Cheat Sheet. To get in-depth knowledge, try Data Science with Python, which comes with 24*7 support to guide you throughout your learning period. Intellipaat’s Python Course will let you master the concepts of the widely-used and powerful programming language, Python. You will gain hands-on experience working with various Python packages like SciPy, NumPy, Python MatPlotLib, Lambda functions, and more. You will work on hands-on projects in the domain of Python and apply it to the various domains of big data, data science, and machine learning.
A lot of questions can be raised about this topic.
Check out the list of Python Coding Interview Questions created by the experts.