Python Cheatsheet
Python Cheatsheet
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)
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:
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:
print("\\")
Single Quote
print("\'")
Tab
print("\t")
Backspace
It adds a backspace:
print("\b")
Octal Value
print("\ooo")
Hex Value
print("\xhh")
Carriage Return
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.
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
isdigit() Method
string_variable.isdigit()
islower() Method
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()
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
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)
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
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
add() Method
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
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
mydict = {}
<dictionary>[<key>] = <value>
If a specified key already exists, then its value will get updated:
<dictionary>[<key>] = <value>
del keyword is used to delete a specified key:value pair from the dictionary as follows:
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
dictionary.get(keyname)
items() Method
dictionary.items()
keys() Method
Returns a list containing the dictionary's keys:
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.
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
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.
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.
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 parameters while
calling that function.
Example:
The function return statement returns the specified value or data item to the caller.
return [value/expression]
Arguments are the values passed inside the parenthesis of the function while defining as well as
while calling.
Example:
File Handling
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() .
read() # return one big string
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
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
Home Courses
Contact Tutorials
Work With Us Notes
My Gear
Legal Social
Terms GitHub
Privacy Twitter (X)
Refund YouTube
Facebook