Python
Python
Search...
HTML Cheat Sheet CSS Cheat Sheet JS Cheat Sheet Bootstrap Cheat Sheet jQuery Cheat Sheet Angular Cheat Sheet SDE Sheet Face
Python is one of the most widely-used and popular programming languages, was developed by
Guido van Rossum and released first in 1991. Python is a free and open-source language with a
very simple and clean syntax which makes it easy for developers to learn Python. It supports
object-oriented programming and is most commonly used to perform general-purpose
programming.
Why Python?
Easy to Learn – Clean, readable syntax that feels like plain English.
Free & Open-Source – No cost, no restrictions—just pure coding freedom.
Object-Oriented & Versatile – Supports multiple programming paradigms.
Massive Community Support – Tons of libraries, frameworks and active contributors.
Table of Content
Python Basics
Operators in Python
Control Flow
Python Functions
Data Structures in Python
Python Built-In Function
Python OOPs Concepts
Python RegEx
Exception Handling in Python
Debugging in Python
File Handling in Python
Memory Management in Python
Decorators in Python
Libraries in Python
Python Modules
Python Interview Questions Answers
To master python from scratch, you can refer to our article: Python Tutorial
Python Basics
Printing Output
print() function in Python is used to print Python objects as strings as standard output. keyword end
can be used to avoid the new line after the output or end the output with a different string.
https://www.geeksforgeeks.org/python-cheat-sheet/ 1/20
6/2/25, 11:29 PM Python CheatSheet (2025) | GeeksforGeeks
The separator between the inputs to the print() method in Python is by default a space,
however, this can be changed to any character, integer, or string of our choice. The 'sep' argument is
used to do the same thing.
# another example
print('Example', 'geeksforgeeks', sep='@')
Python Input
input() method in Python is used to accept user input. By default, it returns the user input as a
string. By default, the input() function accepts user input as a string.
Output:
Python Comment
Comments in Python are the lines in the code that are ignored by the interpreter during the
execution of the program. There are three types of comments in Python:
name = "geeksforgeeks"
print(name)
Output
geeksforgeeks
https://www.geeksforgeeks.org/python-cheat-sheet/ 2/20
6/2/25, 11:29 PM Python CheatSheet (2025) | GeeksforGeeks
# Variable Declaration
x = "Hello World"
We can check the data type of a variable using type() and convert types if needed.
Operators in Python
In general, Operators are used to execute operations on values and variables. These are standard
symbols used in logical and mathematical processes.
Control Flow
Conditional Statements
x = 10
if x > 5:
print("x is greater than 5")
elif x == 5:
print("x is 5")
else:
print("x is less than 5")
Loops
For Loop:
for i in range(5):
print(i) # Prints 0 to 4
While Loop:
i = 0
while i < 5:
print(i)
https://www.geeksforgeeks.org/python-cheat-sheet/ 3/20
6/2/25, 11:29 PM Python CheatSheet (2025) | GeeksforGeeks
i += 1
break exits the loop, while continue skips the current iteration.
for i in range(10):
if i == 5:
break # Exits loop
if i == 3:
continue # Skips iteration
print(i)
1. Using enumerate to Get Index and Value in a Loop: Want to find the index inside a for loop?
Wrap an iterable with ‘enumerate’ and it will yield the item along with its index. See this code
snippet
vowels=['a','e','i','o','u']
for i, letter in enumerate(vowels):
print (i, letter)
Output
0 a
1 e
2 i
3 o
4 u
Python Functions
Python Functions are a collection of statements that serve a specific purpose. The idea is to bring
together some often or repeatedly performed actions and construct a function so that we can reuse
the code included in it rather than writing the same code for different inputs over and over.
Output
Welcome to GFG
Function Arguments
Arguments are the values given between the function's parenthesis. A function can take as many
parameters as it wants, separated by commas.
print("odd")
Output
even
odd
The function return statement is used to terminate a function and return to the function caller with
the provided value or data item.
# Python program to
# demonstrate return statement
def add(a, b):
def is_true(a):
# returning boolean of a
return bool(a)
# calling function
res = add(2, 3)
print("Result of add function is {}".format(res))
res = is_true(2<5)
print("\nResult of is_true function is {}".format(res))
Output
Output
0 1 2 3 4
https://www.geeksforgeeks.org/python-cheat-sheet/ 5/20
6/2/25, 11:29 PM Python CheatSheet (2025) | GeeksforGeeks
The *args and **kwargs keywords allow functions to take variable-length parameters. The number
of non-keyworded arguments and the action that can be performed on the tuple are specified by
the *args.**kwargs, on the other hand, pass a variable number of keyword arguments dictionary to
function, which can then do dictionary operations.
Output
arg1: Geeks
arg2: for
arg3: Geeks
arg1: Geeks
arg2: for
arg3: Geeks
1. One can return multiple values in Python: In Python, we can return multiple values from a
function. Python allows us to return multiple values by separating them with commas. These values
are implicitly packed into a tuple and when the function is called, the tuple is returned
def func():
return 1, 2, 3, 4, 5
Output
1 2 3 4 5
List in Python
Python list is a sequence data type that is used to store the collection of data. Tuples and String are
other types of sequence data types.
Output
List comprehension
https://www.geeksforgeeks.org/python-cheat-sheet/ 6/20
6/2/25, 11:29 PM Python CheatSheet (2025) | GeeksforGeeks
A Python list comprehension is made up of brackets carrying the expression, which is run for each
element, as well as the for loop, which is used to iterate over the Python list's elements.
# Displaying list
print(List)
Output
[1, 2, 3]
Lists Have Been in Python Since the Beginning: When Guido van Rossum created Python in the
late 1980s, lists were an essential part of the language from the very first version (Python 1.0,
released in 1991). Unlike languages like C or Java, where arrays have strict rules.
Inspired by ABC Language: Python was influenced by the ABC programming language, which
also had a simple and intuitive way of handling sequences. However, Python improved upon it by
making lists mutable (meaning they can be changed), which is one of the biggest reasons for
their popularity.
Dictionary in Python
A dictionary in Python is a collection of key values, used to store data values like a map, which,
unlike other data types holds only a single value as an element.
Output
Dictionary Comprehension
Like List Comprehension, Python allows dictionary comprehension. We can create dictionaries using
simple expressions. A dictionary comprehension takes the form {key: value for (key, value) in
iterable}
print (myDict)
Output
https://www.geeksforgeeks.org/python-cheat-sheet/ 7/20
6/2/25, 11:29 PM Python CheatSheet (2025) | GeeksforGeeks
Dictionaries Are Ordered: Before Python 3.7, dictionaries did not preserve the order of insertion.
However, with the introduction of Python 3.7 and beyond, dictionaries now maintain the order of
the key-value pairs. Now we can rely on the insertion order of keys when iterating through
dictionaries, which was previously a feature exclusive to OrderedDict.
Dictionaries Can Have Any Immutable Type as Keys: The keys of a dictionary must be
immutable, meaning they can be strings, numbers or tuples, but not lists or other mutable types.
This feature ensures that the dictionary keys are hashable, maintaining the integrity and
performance of lookups.
Tuples in Python
Tuple is a list-like collection of Python objects. A tuple stores a succession of values of any kind,
which are indexed by integers.
Output
Sets in Python
Python Set is an unordered collection of data types that can be iterated, mutated and contains no
duplicate elements. The order of the elements in a set is unknown, yet it may contain several
elements.
Output
{'for', 'Geeks'}
Python String
In Python, a string is a data structure that represents a collection of characters. A string cannot be
changed once it has been formed because it is an immutable data type.
Strings in Python can be created using single quotes or double quotes or even triple quotes. In
Python, individual characters of a String can be accessed by using the method of Indexing. Indexing
allows negative address references to access characters from the back of the String.
String1 = "GeeksForGeeks"
print("Initial String: ")
print(String1)
https://www.geeksforgeeks.org/python-cheat-sheet/ 8/20
6/2/25, 11:29 PM Python CheatSheet (2025) | GeeksforGeeks
print(String1[0])
Output
Initial String:
GeeksForGeeks
String Slicing
Strings in Python can be constructed with single, double, or even triple quotes. The slicing method
is used to access a single character or a range of characters in a String. A Slicing operator (colon) is
used to slice a String.
# Creating a String
String1 = "GeeksForGeeks"
print("Initial String: ")
print(String1)
Output
Initial String:
GeeksForGeeks
https://www.geeksforgeeks.org/python-cheat-sheet/ 9/20
6/2/25, 11:29 PM Python CheatSheet (2025) | GeeksforGeeks
In this example, we have a Car class with characteristics that represent the car's make, model and
year. The _make attribute is protected with a single underscore _. The __model attribute is marked
as private with two underscores __. The year attribute is open to the public.
We can use the getter function get_make() to retrieve the protected attribute _make. We can use
the setter method set_model() to edit the private attribute __model. Using the getter method
get_model(), we may retrieve the changed private attribute __model. There are no restrictions on
accessing the public attribute year. We manage the visibility and accessibility of class members by
using encapsulation with private and protected properties, offering a level of data hiding and
abstraction.
class Car:
def __init__(self, make, model, year):
self._make = make # protected attribute
self.__model = model # private attribute
self.year = year # public attribute
def get_make(self):
return self._make
def get_model(self):
return self.__model
Output
Toyota
Camry
2022
https://www.geeksforgeeks.org/python-cheat-sheet/ 10/20
6/2/25, 11:29 PM Python CheatSheet (2025) | GeeksforGeeks
1. Python Supports Multiple Programming Paradigms: One of Python's key strengths is its
flexibility. Python supports several programming paradigms, including:
2. Everything in Python Is an Object: In Python, everything is an object, including data types such
as integers, strings and functions. This allows for object-oriented programming (OOP) principles to
be applied across all aspects of the language, including the ability to define classes, inheritance and
methods.
x = 5
# <class 'int'>
print(type(x))
def greet(name):
return f"Hello, {name}"
# <class 'function'>
print(type(greet))
Output
<class 'int'>
<class 'function'>
Python RegEx
We define a pattern using a regular expression to match email addresses. The pattern r"\b[A-Za-z0-
9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b" is a common pattern for matching email addresses. Using
the re.search() function, the pattern is then found in the given text. If a match is found, we use the
match object's group() method to extract and print the matched email. Otherwise, a message
indicating that no email was found is displayed.
import re
# Text to search
text = "Hello, my email is [email protected]"
Output
https://www.geeksforgeeks.org/python-cheat-sheet/ 11/20
6/2/25, 11:29 PM Python CheatSheet (2025) | GeeksforGeeks
MetaCharacters are helpful, significant and will be used in module re functions, which helps us
comprehend the analogy with RE. The list of metacharacters is shown below.
a = [1, 2, 3]
try:
print ("Second element = %d" %(a[1]))
except:
print ("An error occurred")
Output
Second element = 2
An error occurred
Debugging in Python
Debugging is the process of finding and fixing errors (bugs) in our code. Python provides several
methods and tools to help debug programs effectively.
x = 10
y = 20
print("x:", x)
print("y:", y)
result = x + y
print("result:", result)
Output
x: 10
y: 20
result: 30
https://www.geeksforgeeks.org/python-cheat-sheet/ 12/20
6/2/25, 11:29 PM Python CheatSheet (2025) | GeeksforGeeks
The pdb module provides an interactive debugging environment. We can set breakpoints, step
through the code, inspect variables and more. To start debugging, insert pdb.set_trace() where we
want to start the debugger.
import pdb
x = 5
y = 10
pdb.set_trace() # Debugger starts here
result = x + y
print(result)
Output
> /home/repl/2b752c75-c2c1-44d7-b2bd-fa43a3072b3c/main.py(6)<module>()
-> result = x + y
(Pdb)
Once the program reaches pdb.set_trace(), it will enter the interactive mode where we can run
various commands like:
The logging module is more advanced than print() statements and is useful for debugging in
production environments. It allows us to log messages with different severity levels (DEBUG, INFO,
WARNING, ERROR, CRITICAL).
import logging
Output
import os
def create_file(filename):
try:
https://www.geeksforgeeks.org/python-cheat-sheet/ 13/20
6/2/25, 11:29 PM Python CheatSheet (2025) | GeeksforGeeks
def read_file(filename):
try:
with open(filename, 'r') as f:
contents = f.read()
print(contents)
except IOError:
print("Error: could not read file " + filename)
def delete_file(filename):
try:
os.remove(filename)
print("File " + filename + " deleted successfully.")
except IOError:
print("Error: could not delete file " + filename)
if __name__ == '__main__':
filename = "example.txt"
new_filename = "new_example.txt"
create_file(filename)
read_file(filename)
append_file(filename, "This is some additional text.\n")
read_file(filename)
rename_file(filename, new_filename)
read_file(new_filename)
delete_file(new_filename)
Output
https://www.geeksforgeeks.org/python-cheat-sheet/ 14/20
6/2/25, 11:29 PM Python CheatSheet (2025) | GeeksforGeeks
Python provides built-in functions to handle file operations such as reading from and writing to
files. We can use the open() function to work with files.
1. Opening a File:
The open() function is used to open a file and returns a file object.
read()
readline()
readlines()
# Using readline()
first_line = file.readline()
print(first_line)
# Using readlines()
lines = file.readlines()
print(lines)
3. Writing to a File:
It is good practice to close the file after operations using file.close(), but it is recommended to use
the with statement as it automatically handles file closure.
file.close()
https://www.geeksforgeeks.org/python-cheat-sheet/ 15/20
6/2/25, 11:29 PM Python CheatSheet (2025) | GeeksforGeeks
2. Garbage Collection: Python uses a garbage collector to clean up circular references (when
objects reference each other in a cycle).
import sys
x = 10
y = [1, 2, 3]
# Reference counting
a = [1, 2, 3]
b = a
print(sys.getrefcount(a))
Output
Memory size of x: 28
Memory size of y: 88
3
Decorators in Python
Decorators are used to modifying the behavior of a function or a class. They are usually called
before the definition of a function we want to decorate.
@property
def name(self):
return self.__name
2. setter Decorator
@name.setter
def name(self, value):
self.__name=value
3. deleter Decorator
@name.deleter
def name(self, value):
print('Deleting..')
del self.__name
Libraries in Python
Libraries in Python are collections of pre-written code that allow us to perform common tasks
without having to write everything from scratch. They provide functions and classes to help with
tasks like data manipulation, web scraping and machine learning. Python has a vast ecosystem of
libraries, both built-in and third-party.
Basic Libraries
https://www.geeksforgeeks.org/python-cheat-sheet/ 16/20
6/2/25, 11:29 PM Python CheatSheet (2025) | GeeksforGeeks
These libraries are part of Python's standard library and come bundled with Python installation.
Some Basic Libraries are:
1. math: Provides mathematical functions such as trigonometric, logarithmic and basic arithmetic
operations.
2. datetime: Works with dates and times, allows for formatting and manipulation of date/time data.
3. os: Provides functions for interacting with the operating system, such as working with files and
directories.
4. sys: Provides access to system-specific parameters and functions, such as the interpreter's
version or command-line arguments.
These libraries are essential for data manipulation, analysis and visualization. Some Data Science
and Analysis Libraries are:
1. numpy: A fundamental package for scientific computing with Python. It provides support for
large multidimensional arrays and matrices.
2. pandas: Used for data manipulation and analysis. It provides data structures like DataFrames to
handle structured data.
3. matplotlib: A 2D plotting library to create static, animated and interactive visualizations.
These libraries help us build and interact with web applications and services. Some Web
Development Libraries are:
These libraries help build machine learning models, perform deep learning and work with AI
algorithms. Some Machine Learning and AI Libraries are:
1. scikit-learn: A machine learning library that provides simple and efficient tools for data mining
and data analysis.
2. tensorflow: A deep learning framework developed by Google, used for building neural networks
and training AI models.
Python Modules
A library is a group of modules that collectively address a certain set of requirements or
applications. A module is a file (.py file) that includes functions, class defining statements and
variables linked to a certain activity. The term "standard library modules" refers to the pre-installed
Python modules.
Itertools
Json
Os
Pathlib
Random
Shelve
Zipfile
https://www.geeksforgeeks.org/python-cheat-sheet/ 17/20
6/2/25, 11:29 PM Python CheatSheet (2025) | GeeksforGeeks
1. import this:There is actually a poem written by Tim Peters named as THE ZEN
OF PYTHON which can be read by just writing import this in the interpreter.
import this
Output
2. The "antigravity" Easter Egg in Python: The statement import antigravity in Python is a fun
Easter egg that was added to the language as a joke. When we run this command, it opens a web
browser to a comic from the popular webcomic xkcd (specifically, xkcd #353: "Python").
import antigravity
Similar Reads
Free Python Course Online [2025]
Want to learn Python and finding a course for free to learn Python programming? No need to worry
now, Embark on an exciting journey of Python programming with our free Pyt...
https://www.geeksforgeeks.org/python-cheat-sheet/ 18/20
6/2/25, 11:29 PM Python CheatSheet (2025) | GeeksforGeeks
Python Features
Python is a dynamic, high-level, free open source, and interpreted programming language. It supports
object-oriented programming as well as procedural-oriented programming...
14 min read
Python 3 basics
Python was developed by Guido van Rossum in the early 1990s and its latest version is 3.11.0, we can
simply call it Python3. Python 3.0 was released in 2008. and is interp...
https://www.geeksforgeeks.org/python-cheat-sheet/ 19/20
6/2/25, 11:29 PM Python CheatSheet (2025) | GeeksforGeeks
Registered Address:
K 061, Tower K, Gulshan Vivante
Apartment, Sector 137, Noida, Gautam
Buddh Nagar, Uttar Pradesh, 201305
Advertise with us
Python Tutorial Computer Science DevOps System Design School Subjects Databases
Python Examples GATE CS Notes Git High Level Design Mathematics SQL
Django Tutorial Operating Systems AWS Low Level Design Physics MYSQL
Python Projects Computer Network Docker UML Diagrams Chemistry PostgreSQL
Python Tkinter Database Management Kubernetes Interview Guide Biology PL/SQL
Web Scraping System Azure Design Patterns Social Science MongoDB
OpenCV Tutorial Software Engineering GCP OOAD English Grammar
Python Interview Digital Logic Design DevOps Roadmap System Design
Question Engineering Maths Bootcamp
Interview Questions
https://www.geeksforgeeks.org/python-cheat-sheet/ 20/20