Python_cheatsheet
Python_cheatsheet
</>CodeWithHarry
Python CheatSheet
"Python Cheatsheet for all python developers"
By CodeWithHarry Updated: 5 April 2025
Basics
We can display the content present in an object using the print function as follows:
var1 = "Shruti"
print("Hi my name is: ", var1)
https://www.codewithharry.com/blogpost/python-cheatsheet 1/24
4/18/25, 11:20 AM Python CheatSheet | Blog | CodeWithHarry
The input function is used to take input as a string or character from the user as follows:
To take input in the form of other data types, we need to typecast them as follows:
range Function
The range function returns a sequence of numbers, e.g., numbers starting from 0 to n-1 for
range(0, n) :
Here the start value and step value are by default 1 if not mentioned by the programmer, but
int_stop_value is a compulsory parameter in the range function.
Example:
https://www.codewithharry.com/blogpost/python-cheatsheet 2/24
4/18/25, 11:20 AM Python CheatSheet | Blog | CodeWithHarry
Comments
Comments are used to make the code more understandable for programmers, and they are
not executed by the compiler or interpreter.
Multi-line Comment
'''This is a
multi-line
comment'''
Escape Sequence
An escape sequence is a sequence of characters that doesn't represent itself but is translated
into another character when used inside a string literal or character. Some of the escape
sequence characters are as follows:
Newline
Newline Character:
print("\n")
Backslash
It adds a backslash:
https://www.codewithharry.com/blogpost/python-cheatsheet 3/24
4/18/25, 11:20 AM Python CheatSheet | Blog | CodeWithHarry
print("\\")
Single Quote
print("\'")
Tab
print("\t")
Backspace
It adds a backspace:
print("\b")
Octal Value
print("\ooo")
Hex Value
print("\xhh")
Carriage Return
https://www.codewithharry.com/blogpost/python-cheatsheet 4/24
4/18/25, 11:20 AM Python CheatSheet | Blog | CodeWithHarry
Carriage return or \r will just work as if you have shifted your cursor to the beginning of the
string or line:
print("\r")
Strings
Python string is a sequence of characters, and each character can be individually accessed
using its index.
String
You can create strings by enclosing text in both forms of quotes - single quotes or double
quotes:
Example:
str = "Shruti"
print("string is ", str)
Indexing
The position of every character placed in the string starts from the 0th position and step by
step it ends at length-1 position.
Slicing
Slicing refers to obtaining a sub-string from the given string. The following code will include
index 1, 2, 3, and 4 for the variable named var_name.
https://www.codewithharry.com/blogpost/python-cheatsheet 5/24
4/18/25, 11:20 AM Python CheatSheet | Blog | CodeWithHarry
string_var[int_start_value:int_stop_value:int_step_value]
var_name[1:5]
Here start and step value are considered 0 and 1 respectively if not mentioned by the
programmer.
isalnum() Method
Returns True if all the characters in the string are alphanumeric, else False :
string_variable.isalnum()
isalpha() Method
string_variable.isalpha()
isdecimal() Method
string_variable.isdecimal()
isdigit() Method
string_variable.isdigit()
islower() Method
https://www.codewithharry.com/blogpost/python-cheatsheet 6/24
4/18/25, 11:20 AM Python CheatSheet | Blog | CodeWithHarry
string_variable.islower()
isspace() Method
string_variable.isspace()
isupper() Method
string_variable.isupper()
lower() Method
string_variable.lower()
upper() Method
string_variable.upper()
strip() Method
string_variable.strip()
https://www.codewithharry.com/blogpost/python-cheatsheet 7/24
4/18/25, 11:20 AM Python CheatSheet | Blog | CodeWithHarry
List
A list in Python represents a list of comma-separated values of any data type between square
brackets:
Indexing
The position of every element placed in the list starts from the 0th position and step by step it
ends at length-1 position. List is ordered, indexed, mutable, and the most flexible and dynamic
collection of elements in Python.
Empty List
my_list = []
index() Method
Returns the index of the first element with the specified value:
list.index(element)
append() Method
list.append(element)
extend() Method
https://www.codewithharry.com/blogpost/python-cheatsheet 8/24
4/18/25, 11:20 AM Python CheatSheet | Blog | CodeWithHarry
Add the elements of a given list (or any iterable) to the end of the current list:
list.extend(iterable)
insert() Method
list.insert(position, element)
pop() Method
list.pop(position)
remove() Method
The remove() method removes the first occurrence of a given item from the list:
list.remove(element)
clear() Method
list.clear()
count() Method
list.count(value)
https://www.codewithharry.com/blogpost/python-cheatsheet 9/24
4/18/25, 11:20 AM Python CheatSheet | Blog | CodeWithHarry
reverse() Method
list.reverse()
sort() Method
list.sort(reverse=True|False)
Tuples
Tuples are represented as comma-separated values of any data type within parentheses.
Tuple Creation
Indexing
The position of every element placed in the tuple starts from the 0th position and step by step
it ends at length-1 position. Tuples are ordered, indexed, immutable, and the most secure
collection of elements.
count() Method
https://www.codewithharry.com/blogpost/python-cheatsheet 10/24
4/18/25, 11:20 AM Python CheatSheet | Blog | CodeWithHarry
tuple.count(value)
index() Method
It searches the tuple for a specified value and returns the position:
tuple.index(value)
Sets
A set is a collection of multiple values which is both unordered and unindexed. It is written in
curly brackets.
Set is an unordered, immutable, non-indexed type of collection. Duplicate elements are not
allowed in sets.
Set Methods
Let's talk about some of the methods of sets:
add() Method
https://www.codewithharry.com/blogpost/python-cheatsheet 11/24
4/18/25, 11:20 AM Python CheatSheet | Blog | CodeWithHarry
set.add(element)
clear() Method
set.clear()
discard() Method
set.discard(value)
intersection() Method
issubset() Method
set.issubset(set)
pop() Method
set.pop()
remove() Method
https://www.codewithharry.com/blogpost/python-cheatsheet 12/24
4/18/25, 11:20 AM Python CheatSheet | Blog | CodeWithHarry
set.remove(item)
union() Method
set.union(set1, set2...)
Dictionaries
The dictionary is an unordered set of comma-separated key:value pairs, within {} , with the
requirement that within a dictionary, no two keys can be the same.
Dictionary
Dictionary is an ordered and mutable collection of elements. Dictionary allows duplicate values
but not duplicate keys.
Empty Dictionary
By putting two curly braces, you can create a blank dictionary:
mydict = {}
https://www.codewithharry.com/blogpost/python-cheatsheet 13/24
4/18/25, 11:20 AM Python CheatSheet | Blog | CodeWithHarry
<dictionary>[<key>] = <value>
<dictionary>[<key>] = <value>
del <dictionary>[<key>]
len() Method
It returns the length of the dictionary, i.e., the count of elements (key: value pairs) in the
dictionary:
len(dictionary)
clear() Method
dictionary.clear()
get() Method
https://www.codewithharry.com/blogpost/python-cheatsheet 14/24
4/18/25, 11:20 AM Python CheatSheet | Blog | CodeWithHarry
dictionary.get(keyname)
items() Method
dictionary.items()
keys() Method
dictionary.keys()
values() Method
dictionary.values()
update() Method
dictionary.update(iterable)
Indentation
In Python, indentation means the code is written with some spaces or tabs into many different
blocks of code to indent it so that the interpreter can easily execute the Python code.
Indentation is applied on conditional statements and loop control statements. Indent specifies
the block of code that is to be executed depending on the conditions.
https://www.codewithharry.com/blogpost/python-cheatsheet 15/24
4/18/25, 11:20 AM Python CheatSheet | Blog | CodeWithHarry
Conditional Statements
The if , elif , and else statements are the conditional statements in Python, and these
implement selection constructs (decision constructs).
if Statement
if (conditional expression):
statements
if-else Statement
if (conditional expression):
statements
else:
statements
if-elif Statement
if (conditional expression):
statements
elif (conditional expression):
statements
else:
statements
if (conditional expression):
if (conditional expression):
statements
else:
statements
else:
statements
https://www.codewithharry.com/blogpost/python-cheatsheet 16/24
4/18/25, 11:20 AM Python CheatSheet | Blog | CodeWithHarry
Example:
a = 15
b = 20
c = 12
if (a > b and a > c):
print(a, "is greatest")
elif (b > c and b > a):
print(b, " is greatest")
else:
print(c, "is greatest")
Loops in Python
A loop or iteration statement repeatedly executes a statement, known as the loop body, until
the controlling expression is false (0).
for Loop
The for loop of Python is designed to process the items of any sequence, such as a list or a
string, one by one.
Example:
while Loop
A while loop is a conditional loop that will repeat the instructions within itself as long as a
conditional remains true.
https://www.codewithharry.com/blogpost/python-cheatsheet 17/24
4/18/25, 11:20 AM Python CheatSheet | Blog | CodeWithHarry
while <logical-expression>:
loop-body
Example:
i = 1
while (i <= 100):
print(i)
i = i + 1
break Statement
The break statement enables a program to skip over a part of the code. A break statement
terminates the very loop it lies within.
Example:
continue Statement
The continue statement skips the rest of the loop statements and causes the next iteration to
occur.
https://www.codewithharry.com/blogpost/python-cheatsheet 18/24
4/18/25, 11:20 AM Python CheatSheet | Blog | CodeWithHarry
Example:
Functions
A function is a block of code that performs a specific task. You can pass parameters into a
function. It helps us to make our code more organized and manageable.
Function Definition
def my_function():
# statements
Function Call
my_function()
Whenever we need that block of code in our program, simply call that function name whenever
needed. If parameters are passed during defining the function, we have to pass the
https://www.codewithharry.com/blogpost/python-cheatsheet 19/24
4/18/25, 11:20 AM Python CheatSheet | Blog | CodeWithHarry
Example:
return [value/expression]
Example:
File Handling
https://www.codewithharry.com/blogpost/python-cheatsheet 20/24
4/18/25, 11:20 AM Python CheatSheet | Blog | CodeWithHarry
File handling refers to reading or writing data from files. Python provides some functions that
allow us to manipulate data in the files.
open() Function
Modes
4. r+ - To read and write data into the file. The previous data in the file will be overridden.
6. a+ - To append and read data from the file. It won’t override existing data.
close() Function
var_name.close()
read() Function
The read functions contain different methods: read() , readline() , and readlines() .
https://www.codewithharry.com/blogpost/python-cheatsheet 21/24
4/18/25, 11:20 AM Python CheatSheet | Blog | CodeWithHarry
write() Function
writelines()
Exception Handling
A basic try-catch block in Python. When the try block throws an error, the control goes to the
except block.
try:
[Statement body block]
raise Exception()
except Exceptionname:
[Error processing block]
else
The else block is executed if the try block has not raised any exception and the code has
been running successfully.
try:
# statements
https://www.codewithharry.com/blogpost/python-cheatsheet 22/24
4/18/25, 11:20 AM Python CheatSheet | Blog | CodeWithHarry
except:
# statements
else:
# statements
finally
The finally block will be executed even if the try block of code has been running
successfully or the except block of code has been executed. The finally block of code will
be executed compulsorily.
It is a programming approach that primarily focuses on using objects and classes. The objects
can be any real-world entities.
class
class class_name:
pass # statements
Creating an Object
<object-name> =
Tags
Share
python cheatsheet
Main Learn
https://www.codewithharry.com/blogpost/python-cheatsheet 23/24
4/18/25, 11:20 AM Python CheatSheet | Blog | CodeWithHarry
Home Courses
Contact Tutorials
Work With Us Notes
My Gear
Legal Social
Terms GitHub
Privacy Twitter (X)
Refund YouTube
Facebook
https://www.codewithharry.com/blogpost/python-cheatsheet 24/24