Python Cheat Sheet
Python Cheat Sheet
Python Cheatsheet
Contents
1. Syntax and whitespace
2. Comments
3. Numbers and operations
4. String manipulation
5. Lists, tuples, and dictionaries
6. JSON
7. Loops
8. File handling
9. Functions
10. Working with datetime
11. NumPy
12. Pandas
To run a cell, press Shift+Enter or click Run at the top of the page.
2. Comments
In Python, comments start with hash '#' and extend to the end of the line. '#' can be at the
begining of the line or after code.
1 of 14 22/03/2025, 14:49
PythonCheatSheet about:srcdoc
Operation Result
x%y Remainder of x / y
x ** y x to the power y
In [ ]: # Number examples
a = 5 + 8
print("Sum of int numbers: {} and number format is {}".format(a, type(a)))
b = 5 + 2.3
print ("Sum of int and {} and number format is {}".format(b, type(b)))
4. String manipulation
Python has rich features like other programming languages for string manipulation.
2 of 14 22/03/2025, 14:49
PythonCheatSheet about:srcdoc
# Use [] to access the character of the string. The first character is indicated by '0'.
print(test_word[0])
Lists
A list is created by placing all the items (elements) inside square brackets [ ] separated by
commas. A list can have any number of items, and they may be of different types (integer,
float, strings, etc.).
In [ ]: # A Python list is similar to an array. You can create an empty list too.
my_list = []
3 of 14 22/03/2025, 14:49
PythonCheatSheet about:srcdoc
Tuples
A tuple is similar to a list, but you use them with parentheses ( ) instead of square brackets.
The main difference is that a tuple is immutable, while a list is mutable.
In [ ]: my_tuple = (1, 2, 3, 4, 5)
my_tuple[1:4]
Dictionaries
A dictionary is also known as an associative array. A dictionary consists of a collection of key-
value pairs. Each key-value pair maps the key to its associated value.
6. JSON
JSON is text writen in JavaScript Object Notation. Python has a built-in package called json
that can be used to work with JSON data.
In [ ]: import json
4 of 14 22/03/2025, 14:49
PythonCheatSheet about:srcdoc
7. Loops
If, Else, ElIf loop: Python supports conditional statements like any other programming
language. Python relies on indentation (whitespace at the begining of the line) to define the
scope of the code.
In [ ]: a = 22
b = 33
c = 100
if a > b:
print("a is greater than b")
elif b > c:
print("b is greater than c")
else:
print("b is greater than a and c is greater than b")
print("="*10)
# Continue to next iteration if x is 2. Finally, print message once the condition is false.
x = 0
while x < 5:
x += 1
if x == 2:
continue
print(x)
else:
print("x is no longer less than 5")
For loop: A For loop is more like an iterator in Python. A For loop is used for iterating
over a sequence (list, tuple, dictionay, set, string, or range).
5 of 14 22/03/2025, 14:49
PythonCheatSheet about:srcdoc
print("\n")
print("="*10)
print("\n")
# Iterating range
for x in range(1, 10, 2):
print(x)
else:
print("task complete")
print("\n")
print("="*10)
print("\n")
8. File handling
The key function for working with files in Python is the open() function. The open()
function takes two parameters: filename and mode.
• "r" - Read
• "a" - Append
• "w" - Write
• "x" - Create
In addition, you can specify if the file should be handled in binary or text mode.
• "t" - Text
• "b" - Binary
6 of 14 22/03/2025, 14:49
PythonCheatSheet about:srcdoc
In [ ]: # Read file
file = open('test.txt', 'r')
print(file.read())
file.close()
print("\n")
print("="*10)
print("\n")
print("\n")
print("="*10)
print("\n")
In [ ]: # Update file
file = open('test2.txt', 'a')
file.write("\nThis is additional content in the new file.")
file.close()
In [ ]: # Delete file
import os
file_names = ["test.txt", "test2.txt"]
for item in file_names:
if os.path.exists(item):
os.remove(item)
print(f"File {item} removed successfully!")
else:
print(f"{item} file does not exist.")
7 of 14 22/03/2025, 14:49
PythonCheatSheet about:srcdoc
9. Functions
A function is a block of code that runs when it is called. You can pass data, or parameters,
into the function. In Python, a function is defined by def .
In [ ]: # Defining a function
def new_funct():
print("A simple function")
def param_funct(first_name):
print(f"Employee name is {first_name}.")
param_funct("Harry")
param_funct("Larry")
param_funct("Shally")
print("\n")
print("="*10)
print("\n")
x = lambda a, b: a*b/100
print(x(2,4))
8 of 14 22/03/2025, 14:49
PythonCheatSheet about:srcdoc
In [ ]: import datetime
x = datetime.datetime.now()
print(x)
print(x.year)
print(x.strftime("%A"))
print(x.strftime("%B"))
print(x.strftime("%d"))
print(x.strftime("%H:%M:%S %p"))
11. NumPy
NumPy is the fundamental package for scientific computing with Python. Among other
things, it contains:
9 of 14 22/03/2025, 14:49
PythonCheatSheet about:srcdoc
In [ ]: np.add(a,b) # Addition
In [ ]: np.subtract(a,b) # Substraction
In [ ]: np.divide(a,d) # Division
In [ ]: np.multiply(a,d) # Multiplication
Aggregate functions
In [ ]: # Create array
a = np.arange(15).reshape(3, 5) # Create array with range 0-14 in 3 by 5 dimension
b = np.zeros((3,5)) # Create array with zeroes
c = np.ones( (2,3,4), dtype=np.int16 ) # Createarray with ones and defining data types
d = np.ones((3,5))
10 of 14 22/03/2025, 14:49
PythonCheatSheet about:srcdoc
Array manipulation
In [ ]: # Create array
a = np.arange(15).reshape(3, 5) # Create array with range 0-14 in 3 by 5 dimension
b = np.zeros((3,5)) # Create array with zeroes
c = np.ones( (2,3,4), dtype=np.int16 ) # Createarray with ones and defining data types
d = np.ones((3,5))
Pandas
Pandas is an open source, BSD-licensed library providing high-performance, easy-to-use
data structures and data analysis tools for the Python programming language.
Pandas DataFrames are the most widely used in-memory representation of complex data
collections within Python.
11 of 14 22/03/2025, 14:49
PythonCheatSheet about:srcdoc
In [ ]: # Sample dataframe df
df = pd.DataFrame({'num_legs': [2, 4, np.nan, 0],
'num_wings': [2, 0, 0, 0],
'num_specimen_seen': [10, np.nan, 1, 8]},
index=['falcon', 'dog', 'spider', 'fish'])
df # Display dataframe df
In [ ]: # Another sample dataframe df1 - using NumPy array with datetime index and labeled column
df1 = pd.date_range('20130101', periods=6)
df1 = pd.DataFrame(np.random.randn(6, 4), index=df1, columns=list('ABCD'))
df1 # Display dataframe df1
Viewing data
In [ ]: df1 = pd.date_range('20130101', periods=6)
df1 = pd.DataFrame(np.random.randn(6, 4), index=df1, columns=list('ABCD'))
12 of 14 22/03/2025, 14:49
PythonCheatSheet about:srcdoc
In [ ]: df1[df1 > 0] # Select values from a DataFrame where a boolean condition is met
Missing data
Pandas primarily uses the value np.nan to represent missing data. It is not included in
computations by default.
File handling
In [ ]: df = pd.DataFrame({'num_legs': [2, 4, np.nan, 0],
'num_wings': [2, 0, 0, 0],
'num_specimen_seen': [10, np.nan, 1, 8]},
index=['falcon', 'dog', 'spider', 'fish'])
Plotting
In [ ]: # Install Matplotlib using pip
!pip install matplotlib
13 of 14 22/03/2025, 14:49
PythonCheatSheet about:srcdoc
In [ ]: ts = ts.cumsum()
ts.plot() # Plot graph
plt.show()
In [ ]: # On a DataFrame, the plot() method is convenient to plot all of the columns with labels
df4 = pd.DataFrame(np.random.randn(1000, 4), index=ts.index,columns=['A', 'B', 'C',
df4 = df4.cumsum()
df4.head()
In [ ]: df4.plot()
plt.show()
14 of 14 22/03/2025, 14:49