Python Made Easy
Cheat Sheet
About This Cheat Sheet
This cheat sheet includes key topics covered in my Python Made Easy Tutorial for Beginners
on YouTube. It summarizes the core Python language constructs—the essential building blocks
you need to start coding with confidence. Please note that this cheat sheet (and the video tutorial)
provides a concise overview, not an exhaustive guide. If you want to dive deeper and master
everything Python has to offer, check out my Complete Python Made Easy Programming
Course, where we explore advanced concepts, practical
projects, and real-worldapplications in detail.
Why This Cheat Sheet?
This cheatsheet provides a structured and concise summary of fundamental Python concepts.
It is designed to support learners by offering:
A quick overview of key topics from the Python Made Easy series.
A handy revision tool for assignments, coding practice, and interviews.
A bridge between beginnertutorials and professional-level Python programming.
📊 Python Libraries for Data Science
🔹 1. NumPy(NumericalPython) 🔹 6. scikit-learn
Used for numerical computation and handling multi-dimensional arrays.
Used for machine learning and predictive modeling.
Key Features:
Fast mathematical operations on large datasets Key Features:
Supports linear algebra, Fourier transforms, and random numbers Classification, regression, clustering, dimensionality reduction
🔹 2. pandas Model evaluation and data preprocessing
Used for data manipulation and analysis using DataFrames (like Excel tables).
Key Features:
🔹 7. TensorFlow / Keras / PyTorch
Load, clean, transform, and analyze data easily Used for deep learning and neural networks.
Read/write data from CSV, Excel, SQL, JSON, etc.
Key Features:
🔹 3. Matplotlib
Used for data visualization — creating static, animated, or interactive plots. Build and train deep learning models
Key Features: GPU acceleration for large datasets
Line charts, bar graphs, histograms, pie charts, scatter plots
🔹 4. Seaborn 🔹 8. Statsmodels
Built on top of Matplotlib — used for beautiful, statistical visualizations. Used for statistical analysis and econometrics.
Key Features: Key Features:
Heatmaps, pairplots, distribution plots
Hypothesis testing, regression models, time-series analysis
Easy integration with pandas DataFrames
🔹 5. SciPy 🔹 9. Plotly
Used for scientific and technical computing. Used for interactive visualizations (great for dashboards).
Key Features:
🔹 10. NLTK / spaCy
Linear algebra, optimization, signal processing, integration
Used for Natural Language Processing (NLP) — text mining and analysis.
Works closely with NumPy
🐍 Applications of Python
Python is one of the most versatile and widely used programming languages in the world. Its
simplicity, readability, and vast library support make it ideal for beginners as well as professionals.
🔹1. Web Development 📘 Example: Automatically renaming files or
Python is used to build dynamic and scalable web collecting website data.
applications. 🔹 5. Software Development
Popular frameworks: Python is used to build desktop and cross-platform
Django – for high-performance, full-featured webapplications.
apps Libraries:
Flask – lightweight and flexible for smaller tkinter, PyQt, Kivy
projects 📘 Example: Developing GUI-based tools and business
FastAPI – modern and fast for APIs and backend applications.
services 🔹 6. Networking and Cybersecurity
📘 Example: Building websites like Instagram and Python supports network programming and security
Pinterest. analysis.
🔹 2. Data Science and Analytics Libraries:
Python is the leading language for data analysis and socket, paramiko, scapy
visualization. 📘 Example: Writing scripts to test network
Libraries used: vulnerabilities.
pandas, numpy – for data manipulation 🔹 7. Game Development
matplotlib, seaborn – for data visualization Python can also be used for building simple 2D or 3D
scikit-learn – for statistical modeling and games.
machine learning Library:
📘 Example: Analyzing sales data or predicting pygame
customer behavior. 📘 Example: Creating educational or prototype games.
🔹 3. Machine Learning and Artificial 🔹 8. Scientific and Numerical Computing
Intelligence Used heavily in research and simulation.
Python provides extensive libraries for AI and ML Libraries:
development.
numpy, scipy, sympy
Libraries used: 📘 Example: Mathematical modeling, simulations, and
tensorflow, keras, pytorch – for deep learning symbolic computations.
scikit-learn – for predictive modeling 🔹 9. Internet
Python of Things
runs on devices like(IoT)
Raspberry Pi for IoT
📘 Example: Image recognition, voice assistants, and
projects.
chatbots. 📘 Example: Home automation, sensors, and robotics.
🔹 4. Automation and Scripting 🔹 10. Education and Research
Python is ideal for automating repetitive tasks. Python is widely taught in schools, colleges, and
Common uses: universities due to its readability and versatility.
File handling and organization 📘 Example: Teaching programming fundamentals
Web scraping and algorithm design.
Email and report automation
About Dr. Mehar Chand
He is a distinguished Professor of Mathematics at Baba Farid College of
Engineering and Technology, Bathinda, India and the Founder & President of
MathTech Thinking Foundation (MTTF), Fazilka, a Section 8 Company non-profit
dedicated to promoting STEM education, interdisciplinary research, and
innovation. With more than 15 years of teaching and research experience, he has
become a recognized academic leader, researcher, and mentor.
His research expertise spans Fractional Calculus, Special and Hypergeometric Functions,
Mathematical Modeling, Computational Mathematics, Numerical Methods, Optimization Techniques,
and Cryptography, along with emerging fields like Artificial Neural Networks (ANN), Machine Learning
(ML), Deep Learning (DL), and Mathematical Physics. He has authored 70+ SCI/SCIE/SCOPUS-indexed
papers and 5 book chapters (Springer), and delivered 150+ invited/keynote talks at national and
international platforms.
Dr. Chand has supervised four Ph.D. scholars, organized 100+ national workshops, 2 DST-sponsored
internships, and several FDPs, webinars, and training programs, while also serving on multiple
academic and research boards. Through MTTF, he actively fosters global collaborations, youth
empowerment, and inclusive innovation in STEM.
With a strong blend of academic excellence, research contributions, and institutional leadership, Dr.
Chand continues to inspire students, researchers, and educators across disciplines worldwide.
My Dream for the Next Generation
My dream for the next generation is to see young minds grow as innovators, thinkers, and
responsible global citizens who use knowledge and technology to serve humanity. I envision a world
where education inspires creativity, curiosity, and compassion, empowering students to explore
new ideas and transform challenges into opportunities. Through the integration of Science,
Mathematics, and Technology, I wish to nurture a generation that is not only skilled and
intelligent but also ethical, empathetic, and environmentally conscious. My goal is to build
learning communities where youth are encouraged to think beyond boundaries, collaborate across
disciplines, and contribute to a sustainable and inclusive future. The next generation should be
equipped not just with information, but with wisdom, innovation, and a deep sense of purpose—to
make the world a better place for all.
Dr. Mehar Chand
Python_Made_Easy_CheatSheet
October 11, 2025
1 Variables
We use variables to temporarily store data in computer’s memory.
[1]: price = 10 # price is an integer (a whole number without a decimal point)
rating = 4.9 # rating is a float (a number with a decimal point)
↪
course_name
characters)= 'Python for Beginners' # course_name is a string (a sequence of ␣
↪False.
is_published=True#is_publishedisaboolean.BooleanvaluescanbeTrueor ␣
[3]: print(type(price))
<class 'int'>
[4]: print(type(rating))
<class 'float'>
[5]: print(type(course_name))
<class 'str'>
[ ]: print(type(is_published))
2 Comments
We use comments to include notes within our code. Effective comments describe the reasoning and
intent behind the code, rather than restating what it does — that should already be clear from the
code itself. Comments can serve as reminders for you or other developers, clarifying assumptions
and explaining why certain coding decisions were made.
[9]: # This is a comment and it won’t get executed.
# Our comments can be multiple lines.
# Addition
3+7
[9]: 10
1
3 ReceivingInput
We can receive input from the user by calling the input() function.
[10]: birth_year = int(input('Birth year: '))
Birth year: 1991
The input() function always provides the user’s input as a string. Therefore, we convert it into an
integer by using the built-in int() function.
4 Strings
Strings can be created using either single quotes (’ ’) or double quotes (” “). For multi-line strings,
we enclose the text within triple quotes (””” ”””). Individual characters from a string can be
accessed using square brackets ([]).
[11]: course = 'Python for Beginners'
[12]: course[0] # returns the first character
[12]: 'P'
[13]: course[1] # returns the second character
[13]: 'y'
[14]: course[-1] # returns the first character from the end
[14]: 's'
[15]: course[-2] # returns the second character from the end
[15]: 'r'
We can slice a string using a similar notation:
[16]: course[1:5]
[16]: 'ytho'
The above expression returns all the characters starting from the index position of 1 to 5 (but
excluding 5). The result will be ytho
• If we leave out the start index, 0 will be assumed.
• If we leave out the end index, the length of the string will be assumed.
We can use formatted strings to dynamically insert values into our strings:
[33]: name = 'Mehar Chand'
2
[34]: message = f'Hi, my name is {name}'
print(message)
Hi, my name is Mehar Chand
[35]: message.upper() # to convert to uppercase
[35]: 'HI, MY NAME IS MEHAR CHAND'
[36]: message.lower() # to convert to lowercase
[36]: 'hi, my name is mehar chand'
[37]: message.title() #to capitalizethefirst letterofeveryword
[37]: 'Hi, My Name Is Mehar Chand'
↪
[38]: message.find('m')
not found) # returns the index of the first occurrence of p (or -1 if ␣
[38]: 4
[42]: message.replace('d', 'i')
[42]: 'Hi, my name is Mehar Chani'
To check if a string contains a character (or a sequence of characters), we use the in operator:
[45]: contains = 'Python' in course
contains
[45]: True
5 ArithmeticOperations
[47]: 5+8 # Addition
[47]: 13
[48]: 8-4 # Subtraction
[48]: 4
[49]: 8*4 # Multiplication
[49]: 32
[50]: 8/5 # Return float
3
[50]: 1.6
[51]: 9//4 # Return Integer
[51]: 2
[52]: 2**3 # exponentiation - 2 ** 3 = 3 to the power of 2
[52]: 8
Augmented assignment operator:
[65]: x=2
#x= x+ 10
[66]: x += 10
print(x)
12
6 Operatorprecedence:
1. parenthesis
2. exponentiation
3. multiplication / division
4. addition / subtraction
7 If Statements
[72]: is_hot = False
is_cold = False
if is_hot:
print("hot day")
elif is_cold:
print("cold day")
else:
print("beautiful day")
beautiful day
4
8 Logical operators:
[73]: # AND operator
has_high_income = True has_good_credit
= True
if has_high_income and has_good_credit:
print("Eligible for loan")
Eligible for loan
[74]: # OR operator
has_criminal_record = False
if has_high_income or has_criminal_record:
print("May or may not be eligible based on other factors")
May or may not be eligible based on other factors
[77]: # NOT operator
is_active = False
if not is_active:
print("User is inactive")
User is inactive
9 Comparisonoperators
a>b
a >= b (greater than or equal to)
a<b
a<=b
a == b (equals)
a != b (not equals)
10 Whileloops
[1]: i = 1
while i < 5:
print(i)
i += 1
1
2
5
34
11
for
Forloops
[14]: i in range(1, 5):
print(i)
1
2
3
4
[15]: for i in range(5):
print(i)
0
1
2
3
4
[17]: for i in range(1, 5):
print(i)
1
2
3
4
[18]: for i in range(1, 5, 2):
print(i)
13
1
2
Lists
[51]: numbers = [1, 2, 3, 4, 5]
print(numbers)
[1, 2, 3, 4, 5]
[39]: numbers[0] # returns the first item
[39]: 1
[40]: numbers[1] # returns the second item
6
[40]: 2
[41]: numbers[-1] # returns the first item from the end
[41]: 5
[42]: numbers[-2] # returns the second item from the end
[42]: 4
[43]: numbers.append(6) # adds 6 to the end
print(numbers)
[1, 2, 3, 4, 5, 6]
[44]: numbers.insert(0, 6) # adds 6 at index position of 0
[45]: numbers.remove(6) # removes 6
[46]: numbers.pop() # removes the last item
[46]: 6
[48]: numbers.clear() # # removes all the items
numbers
[48]: []
[52]: numbers.index(5) # returns the index of first occurrence of 5
[52]: 4
[54]: numbers.sort() # sorts the list
numbers
[54]: [1, 2, 3, 4, 5]
[57]: numbers.reverse() # reverses the list
numbers
[57]: [5, 4, 3, 2, 1]
[58]: numbers.copy() # returns a copy of the list
[58]: [5, 4, 3, 2, 1]
7
13 Tuples
A tuple is an ordered, immutable (unchangeable) collection used to store multiple items in a single
variable. Tuples are similar to lists, but once created, their elements cannot be modified, added, or
removed.
[60]: coordinates = (1, 2, 3)
coordinates
[60]: (1, 2, 3)
We can unpack a list or a tuple into separate variables:
x, y, z = coordinates
[61]: # Using parentheses
coordinates = (10, 20, 30)
# A tuple can also contain mixed data types
info = ("Alice", 25, True)
[62]: info
[62]: ('Alice', 25, True)
[65]: # Accessing Tuple Elements
coordinates = (10, 20, 30)
print(coordinates[0]) #Output: 10
print(coordinates[-1]) #Output: 30
10
30
↪
[66]: # Tuple Unpacking:We can assign each value of a tuple to separate variables in
asingleline ␣
x,y,z=coordinates
print(x, y, z) # Output: 10 20 30
10 20 30
14 Dictionaries
A dictionary is an unordered collection of data in key–value pairs. Each key in a dictionary must
be unique and is used to access its corresponding value
[89]: # Example 1: Basic dictionary
student = {
"name": "John",
"age": 21,
"course": "Biology",
8
"is_enrolled": True
}
[82]: # Accessing Dictionary Values
print(student["name"]) #Output: John
print(student.get("age")) #Output: 21
print(student.get("grade","N/A")) #Returns "N/A"ifkeynotfound
John
21
N/A
[83]: # Adding or Updating Entries
student["age"]= 22 # Updateexistingkey
student["email"] = "[email protected]" # Add new key-value pair
[84]: print(student.get("age"))
22
[85]: print(student.get("email"))
[email protected]
[86]: # Removing Entries
student.pop("course") #Removesthe key 'course'
student
[86]: {'name': 'John', 'age': 22, 'is_enrolled': True, 'email': '[email protected]'}
[87]: student.clear() #Removesall itemsfromthedictionary
student
[87]: {}
[92]: # Looping Through a Dictionary
student = {
"name": "John",
"age": 21,
"course": "Biology",
"is_enrolled": True
}
for key in student:
[93]:
print(key, ":", student[key])
name : John
age : 21
course : Biology
is_enrolled : True
9
[94]: for key, value in student.items():
print(f"{key} → {value}")
name → John
age → 21
course → Biology
is_enrolled → True
15 Functions
We use functions to divide our code into smaller, manageable sections. These sections are easier
to read, understand, and maintain. In case of errors, debugging becomes simpler since we can
focus on a specific part of the code. Additionally, functions promote reusability, allowing the same
code to be used in multiple places.
Defining a Function
[101]: def greet():
print("Hello, welcome to Python!")
[102]: # To call (execute) the function:
greet() #Output: Hello, welcometo Python!
Hello, welcome to Python!
Parameters are placeholders for the data we can pass to functions. Arguments are the
actual values we pass
We have two types of arguments:
* Positional arguments: their position (order) matters * Keyword arguments: position doesn’t
matter - we prefix them with the parameter name.
[125]: def greet_user(name):
print(f"Hello, {name}!")
[104]: greet_user("Mehar Chand") # Output: Hello, Mehar Chand!
Hello, Mehar Chand!
Function with Multiple Parameters
[105]: def add_numbers(a, b):
print(a + b)
[106]: add_numbers(5, 3) # Output: 8
8
Returning a Value: Functions can return results using the return keyword
10
[107]: def square(number):
return number * number
[108]: result = square(4)
print(result) # Output: 16
16
Positional vs Keyword Arguments
[109]: # Positional arguments: order matters
def display_info(name, age):
print(f"{name} is {age} years old.")
[111]: display_info("John", 25)
John is 25 years old.
[112]: # Keyword arguments: order doesn’t matter
display_info(age=25, name="John")
John is 25 years old.
[113]: # Default Parameters: we can assign default values to parameters.
def greet_user(name="Guest"):
print(f"Welcome, {name}!")
greet_user() # Output: Welcome,Guest!
greet_user("Aparna") # Output: Welcome,Aparna!
Welcome, Guest!
Welcome, Aparna!
[116]: # Arbitrary Arguments: If we don’t know how many arguments will be passed
def add_all(*numbers):
return sum(numbers)
[117]: print(add_all(2, 3, 4, 5)) # Output: 14
14
Our functions can return values. If we don’t use the return statement, by default
None is returned. None is an object that represents the absence of a value.
[128]: def square(number):
return number * number
result = square(2)
[129]:
print(result) # prints 4
11
16 Exceptions
Exceptions are errors that crash our programs. They often happen because of bad input or pro-
gramming errors. It’s our job to anticipate and handle these exceptions to prevent our programs
from cashing.
[137]: try:
age = int(input('Age: '))
income = 20000
risk = income / age
print(age)
except ValueError:
print('Not a valid number')
except ZeroDivisionError:
print('Age cannot be 0')
Age: 0
Age cannot be 0
17 Classes
We use classes to define new data types that group together data (attributes) and functions (meth-
ods) into a single unit. A class acts as a blueprint for creating objects that share similar charac-
teristics and behaviors.
[138]: # Defining a class
class Person:
# Constructor method to initialize attributes
def __init__(self, name, age):
self.name = name # attribute
self.age=age
attribute #
# Method (function inside a class)
def greet(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
[139]: # Creating objects (instances) of the class
person1 = Person("Aparna", 30)
person2 = Person("Sonia", 28)
[140]: # Calling the method
person1.greet() #Output: Hello, mynameisAparnaandIam30yearsold.
person2.greet() #Output: Hello, mynameisSoniaandIam28yearsold.
Hello, my name is Aparna and I am 30 years old.
Hello, my name is Sonia and I am 28 years old.
12
18 Inheritance in Python
Inheritance is a feature that allows one class (called the child or derived class) to inherit the
properties and methods of another class (called the parent or base class). It helps to avoid code
duplication and promotes reusability by allowing shared functionality to be defined only once in the
base class.
[141]: # Base class
class Animal:
def walk(self):
print("This animal can walk.")
# Derived class
class Dog(Animal):
def bark(self):
print("The dog barks.")
[142]: # Creating an object of the derived class
dog1 = Dog()
dog1.walk() #Inherited from Animal
dog1.bark() #Definedin Dog
This animal can walk.
The dog barks.
19 Modules
A module is a file with some Python code. We use modules to break up our program into multiple
files. This way, our code will be better organized. We won’t have one gigantic file with a million lines
of code in it! There are 2 ways to import modules: we can import the entire module, or specific
objects in a module.
1. Import the entire module – this gives access to all the functions, classes, and
variables defined in the module.
[145]: import math
print(math.sqrt(16)) # Using sqrt function from math module
4.0
2. Import specific objects from a module – this imports only the required functions,
classes, or variables.
[146]: from math importsqrt
print(sqrt(16)) # Directly using sqrt without module prefix
4.0
13
20 Packages
A package is a directory that contains a special file called _init_.py. This file can be empty, but
its presence tells Python that the directory should be treated as a package.
A package can contain:
• One or more modules (Python files with code)
• Sub-packages (nested directories with their own _init_.py)
21 PythonStandardLibrary
Python comes with a huge library of modules for performing common tasks such as sending emails,
working with date/time, generating random values, etc.
[158]: # Random Module
import random
[160]: random.random() # returns a float between 0 to 1
[160]: 0.9770351565934237
[161]: random.randint(1, 6) # returns an int between 1 to 6
[161]: 4
[165]: members = ['John', 'Bob', 'Mary']
leader = random.choice(members) # randomly picks an item
leader
[165]: 'Mary'
22 PyPI(PythonPackageIndex)
PyPI (Python Package Index) is an online repository of Python packages published by developers
worldwide. It contains thousands of packages for different purposes—data analysis, web develop-
ment, machine learning, and more.
We use pip, Python’s package manager, to install, upgrade, or uninstall packages from PyPI.
[ ]: # !pip install numpy
# !pip uninstall numpy
14