Python CheatSheet
Basics
Basic syntax from the python programming language
Showing Output To User
The print function is used to display or print output as follows
risus
CCRT
EIEN See)
we can display the content present in object using prit function as follows:
Sits
print("Hi my name is: ",var1)
Taking Input From the User
The input function is used to take input as string or character from the user as follows:
var1 = input("Enter
Panam
To take input in form of other datatypes we need to typecaste them as follows:-
To take input as an integer-
vari=int(input("enter the integer value"))
Peters)
To take input as an float:-
Nels eaters eui id Grn ea CL Tanr eC)
puna Cc)
range Function
range function returns a sequence of numbers, eg, numbers starting from 0 to n-I for
range(0, n)Here the start value and step value are by default | if not mentioned by the programmer.
but int_stop_value is the compulsory parameter in range function
example-
Display all even numbers between | to 100
oan) (0,101,2):
print (i)
Comments
Comments are used to make the code more understandable for programmers, and they
are not executed by compiler or interpreter.
Single line comment
Sas
Multi-line comment
Escape Sequence
An escape sequence is a sequence of characters; it doesn't represent itself (but is
translated into another character) when used inside string literal or character. Some of
the escape sequence characters are as follows:
Newline
Newline Character
Backslash
Itadds a backslashSingle Quote
Itadds a single quotation mark
print("\'")
Tab
It gives a tab space
sth a)
Backspace
Itadds a backspace
Petia
;
Octal value
It represents the value of an octal number
print("\ooo")
Hex value
it represents the value of a hex number
Pana Gae cD)
Carriage Return
Carriage return or \r will just work as you have shifted your cursor to the beginning of the
string or line.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,
Sse oars
example
Indexing
The position of every character placed in the string starts from Oth position ans 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 |, 2, 3, and 4 for the variable named var_name
Slicing of the string can be obtained by the following syntax-
SORES]
Scar eae
here start and step value are considered 0 and | respectively if not mentioned by the
programmmer
isalnum() method
Returns True if all the characters in the string are alphanumeric, else False
Ce mec Cece PUTO)
isalpha() method
Returns True if all the characters in the string are alphabetsBeStm CSc ICeeec ITO)
isdecimal() method
Returns True if all the characters in the string are decimals
eeu s ca Ceee cout)
isdigit() method
Returns True if all the characters in the string are digits
string variable. isdigit()
islower() method
Returns True if all characters in the string are lower case
riable.islower()
isspace() method
Returns True if all characters in the string are whitespaces
string_variable.isspace()
isupper() method
Returns True if all characters in the string are upper case
string_variable.isupper()
lower() method
Converts a string into lower case equivalent
string_variable.lower()
upper() methodConverts a string into upper case equivalent
string_variable.upper()
strip() method
It removes leading and trailing spaces in the string
string_variable.strip()
A List in Python represents a list of comma-separated values of any data type between
square brackets.
These elements can be of different datatypes
Indexing
The position of every elements placed in the string starts from Oth position ans step by
step it ends at length-1 position
List is ordered,indexed,mutable and most flexible and dynamic collection of elements in
python.
Empty List
This method allows you to create an empty list
Cet see)
index method
Returns the index of the first element with the specified value
Ore euo)
append method
Adds an element at the end of the list
Cua)extend method
Add the elements of a given list (or any iterable) to the end of the current list
SRE sent)
insert method
Adds an element at the specified position
SRE ae UTC
(position, element)
pop method
Removes the element at the specified position and returns it
list.pop(position)
remove method
The remove() method removes the first occurrence of a given item from the list
Reet)
clear method
Removes all the elements from the list
petiatot C0)
count method
Returns the number of elements with the specified value
sees nec)
reverse method
Reverses the order of the listsort method
Sorts the list
Sr )
Tuples
Tuples are represented as comma-separated values of any data type within
parentheses.
Tuple Creation
OCs mast
These elements can be of different datatypes
Indexing
The position of every elements placed in the string starts from Oth position ans step by
step it ends at length-1 position
Tuples are ordered,ndexing,immutable and most secured collection of elements
Lets talk about some of the tuple methods:
count method
it returns the number of times a specified value occurs in a tuple
meee TA)
index method
It searches the tuple for a specified value and returns the position.
BUT SOc Fut}
Sets
A set is a collection of multiple values which is both unordered and unindexed. It is written
in curly brackets.
Set Creation: Way 1Set is unordered,immutable,non-indexed type of collection.Duplicate elements are not
allowed in sets.
Set Methods
Lets talk about some of the methods of sets:
add() method
Adds an element to a set
-add(element)
clear() method
Remove all elements from a set
ott e)
discard() method
Removes the specified item from the set
are (Ora)
intersection() method
Returns intersection of two or more sets
-intersection(set1, set2 ... etc)
issubset() method
Checks if a set is a subset of another setpop() method
Removes an element from the set
-pop()
remove() method
Removes the specified element from the set
Lek)
union() method
Returns the union of two or more sets
-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 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
Adding Element to a dictionary
By this method, one can add new elements to the dictionary[] =
Updating Element in a dictionary
If a specified key already exists, then its value will get updated
[] =
Deleting an element from a dictionary
del keyword is used to delete a specified key-value pair from the dictionary as follows
Cec as CLECs
Dictionary Functions & Methods
Below are some of the methods of dictionaries
len() method
It returns the length of the dictionary, i.c., the count of elements (key: value pairs) in the
dictionary
(dictionary)
clear() method
Removes all the elements from the dictionary
dictionary.clear()
get() method
Returns the value of the specified key
dictionary. get (keyname)
items() method
Returns a list containing a tuple for each key-value pairdictionary. items()
keys() method
Returns a list containing the dictionary’s keys
dictionary. keys()
values() method
Returns a list of all the values in the dictionary
dictionary. values()
update() method
Updates the dictionary with the specified key-value pairs
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
(conditional expression):
Berd
if-else Statement(conditional expression):
Bere
Reread
if-elif Statement
(conditional expression):
Bee ied
Cosco
Bee
Bere
Nested if-else Statement
(conditional expression):
Corecess
etd
Steed
Beret
example-
*)
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.
RSC Ie tls Samer Troe
Be ma
example-
icra (1,101,1):
print (4
While Loop
Awhile loop is a conditional loop that will repeat the instructions within itself as long as a
conditional remains true.
while :
Steg
example-
print (i)
oo
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
Se eee US uta
Brescirae
Stare este
cers
Reet)
Sete)
example-
ae ae (1,161,1):
etnae an oa)Gera
ete
Pann aay
Continue Statement
The continue statement skips the rest of the loop statements and causes the next
iteration to occur.
Se ee UIST cues
Beteiet
Stance he tes
oneti)
Sr teited
Seite)
Rete)
example-
for i in [2,3,4,6,
phaet 3
oaeunt)
print(i)
Functions
A function is a block of code that performs a specific task. You can pass parameters into
a function. tt helps us to make our code more organized and manageable.
Function Definition
Coa urasCOn
def keyword is used before defining the function.
Function CallCae CuTO)
Whenever we need that block of code in our program simply call that function name
whenever needed. If parameters are passed during defing the function we have to pass
the parameters while calling that function
example-
Carton PtssCE surety)
EU)
cer)
eu er))
add() cats
Return statement in Python function
The function return statement return the specified value or data item to the caller.
Sam ACCS CuB)
Arguments in python function
Arguments are the values passed inside the parenthesis of the function while defining as
well as while calling.
rg Corser a cee
ey
my _function(argi,arg2,arg3....argn)
example-
Caren
eit)
pe CaED)
etree)
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() functionTEC t ji }
modes-
1.r- to read the content from file
2.w - to write the content into file
3.a- to append the existing content into file
4. r#: To read and write data into the file. The previous data in the file will be overridden.
5. w#: To write and read data. It will override existing data.
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 contains different methods, read(),readline() and readlines()
ero aa Sats
It returns a list of lines
Pee TEL @ Rate ee
it returns one line at a time
eCSEL aE
write function
This function writes a sequence of strings to the file.
Exception Handlingin that results in an interruption in the flow of a
‘An exception is an unusual condi
program.
try and except
A basic try-catch block in python. When the try block throws an error, the control goes to
the except block.
re
eseiecnea Nm rad]
raise Exception()
except Exceptionname:
eae ees aa)
else
The else block is executed if the try block have not raise any exception and code had
been running successfully
ress
finally
Finally block will be executed even if try block of code has been running successsfully or
except block of code is been executed. finally block of code will be executed compulsory
Object Oriented Programming (OOPS)
itis a programming approach that primarily focuses on using objects and classes. The
objects can be any real-world entities.
class
The syntax for writing a class in python
Pee
Creating an objectInstantiating an object can be done as follows:
DEUS ee ius)
self parameter
The self parameter is the first parameter of any function present in the class. It can be of
different name but this parameter is must while defining any function into class as itis
used to access other data members of the class
class with a constructor
Constructor is the special function of the class which is used to initialize the objects. The
syntax for writing a class with the constructor in python
Ce ep
def _init_(self)
Psa ee Cea
CSC eo en
print (self.name)
Inheritance in python
By using inheritance, we can create a class which uses all the properties and behavior of
another class. The new class is known as a derived class or child class, and the one
whose properties are acquired is known as a base class or parent class.
It provides the re-usability of the code.
Types of inheritance-
Single inheritance
Multiple inheritance
Multilevel inheritance
Hierarchical inheritancefilter function
The filter function allows you to process an iterable and extract those items that satisfy a
given condition
issubclass function
Used to find whether a class is a subclass of a given class or not as follows
issubclass(obj, classinfo)
Iterators and Generators
Here are some of the advanced topics of the Python programming language like iterators
and generators
Iterator
Used to create an iterator over an iterable
prea ets Sehr cee COT
print(next(iter_list))
Pstna Goss etc EEo))
print(next (iter_list))
Generator
Used to generate values on the fly
Coma O
ce
Pins Ghee CM Stes strap)
en
Pitas Ga} Pane)
Seon
es
Crs Gn UE Ce Ui ica)
etnDecorators
Decorators are used to modifying the behavior of a function or a class. They are usually
called before the definition of a function you want to decorate.
property Decorator (getter)
Cas
Cau
Cetus ae
setter Decorator
Itis used to set the property ‘name’
CR ees
Cau Seam
self.__name=value
deleter Decorator
Itis used to delete the property ‘name’
Cre ec
def (eotaaC tT
eae
del self.__name
CodeWithHarry — copyrigh fyOQOo