Python CheatSheet
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
Copy
we can display the content present in object using prit function as
follows:-
Copy
Taking Input From the User
The input function is used to take input as string or character from the
user as follows:
Copy
To take input in form of other datatypes we need to typecaste them as
follows:-
To take input as an integer:-
Copy
To take input as an float:-
Copy
range Function
range function returns a sequence of numbers, eg, numbers starting
from 0 to n-1 for range(0, n)
range(int_start_value,int_stop_value,int_step_value)
Copy
Here the start value and step value are by default 1 if not mentioned by
the programmer. but int_stop_value is the compulsory parameter in
range function
Comments
Comments are used to make the code more understandable for
programmers, and they are not executed by compiler or interpreter.
Single line comment
Copy
Multi-line comment
'''This is a
multi-line
comment'''
Copy
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
\n
Copy
Backslash
It adds a backslash
\\
Copy
Single Quote
It adds a single quotation mark
\'
Copy
Tab
It gives a tab space
\t
Copy
Backspace
It adds a backspace
\b
Copy
Octal value
It represents the value of an octal number
\ooo
Copy
Hex value
It represents the value of a hex number
\xhh
Copy
Carriage Return
Carriage return or \r will just work as you have shifted your cursor to the
beginning of the string or line.
\r
Copy
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.
Copy
Indexing
The position of every character placed in the string starts from 0th
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 1, 2, 3, and 4 for the variable
named var_name
Slicing of the string can be obtained by the following syntax-
string_var[int_start_value:int_stop_value:int_step_value]
Copy
var_name[1 : 5]
Copy
Here int_start_value and int_step_value are by default 1 if not
mentioned by the programmer
isalnum() method
Returns True if all the characters in the string are alphanumeric, else
False
string_variable.isalnum()
Copy
here start and stop value are considered 0 and 1 respectively if not
mentioned by the programmmer
isalpha() method
Returns True if all the characters in the string are alphabets
string_variable.isalpha()
Copy
isdecimal() method
Returns True if all the characters in the string are decimals
string_variable.isdecimal()
Copy
isdigit() method
Returns True if all the characters in the string are digits
string_variable.isdigit()
Copy
islower() method
Returns True if all characters in the string are lower case
string_variable.islower()
Copy
isspace() method
Returns True if all characters in the string are whitespaces
string_variable.isspace()
Copy
isupper() method
Returns True if all characters in the string are upper case
string_variable.isupper()
Copy
lower() method
Converts a string into lower case equivalent
string_variable.lower()
Copy
upper() method
Converts a string into upper case equivalent
string_variable.upper()
Copy
strip() method
It removes leading and trailing spaces in the string
string_variable.strip()
Copy
List
A List in Python represents a list of comma-separated values of any data
type between square brackets.
Copy
These elements can be of different datatypes
Indexing
The position of every elements placed in the string starts from 0th
position ans step by step it ends at length-1 position
characterstics of list
Empty List
This method allows you to create an empty list
my_list = []
Copy
index method
Returns the index of the first element with the specified value
list.index(element)
Copy
append method
Adds an element at the end of the list
list.append(element)
Copy
extend method
Add the elements of a given list (or any iterable) to the end of the current
list
list.extend(iterable)
Copy
insert method
Adds an element at the specified position
list.insert(position, element)
Copy
pop method
Removes the element at the specified position and returns it
list.pop(position)
Copy
remove method
The remove() method removes the first occurrence of a given item from
the list
list.remove(element)
Copy
clear method
Removes all the elements from the list
list.clear()
Copy
count method
Returns the number of elements with the specified value
list.count(value)
Copy
reverse method
Reverses the order of the list
list.reverse()
Copy
sort method
Sorts the list
list.sort(reverse=True|False)
Copy
Tuples
Tuples are represented as comma-separated values of any data type
within parentheses.
Tuple Creation
Copy
These elements can be of different datatypes
Indexing
The position of every elements placed in the string starts from 0th
position ans step by step it ends at length-1 position
characterstics of list
tuple.count(value)
Copy
index method
It searches the tuple for a specified value and returns the position.
tuple.index(value)
Copy
Sets
A set is a collection of multiple values which is both unordered and
unindexed. It is written in curly brackets.
Set Creation: Way 1
Copy
Set Creation: Way 2
Copy
characterstics of sets:
• set is unordered
• sets are immutable
• sets have no indexing property
• 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
set.add(element)
Copy
clear() method
Remove all elements from a set
set.clear()
Copy
discard() method
Removes the specified item from the set
set.discard(value)
Copy
intersection() method
Returns intersection of two or more sets
Copy
issubset() method
Checks if a set is a subset of another set
set.issubset(set)
Copy
pop() method
Removes an element from the set
set.pop()
Copy
remove() method
Removes the specified element from the set
set.remove(item)
Copy
union() method
Returns the union of two or more sets
set.union(set1, set2...)
Copy
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
Copy
characterstics of dictionary:
Empty Dictionary
By putting two curly braces, you can create a blank dictionary
mydict={}
Copy
Adding Element to a dictionary
By this method, one can add new elements to the dictionary
<dictionary>[<key>] = <value>
Copy
Updating Element in a dictionary
If a specified key already exists, then its value will get updated
<dictionary>[<key>] = <value>
Copy
Deleting an element from a dictionary
del keyword is used to delete a specified key:value pair from the
dictionary as follows:
del <dictionary>[<key>]
Copy
Dictionary Functions & Methods
Below are some of the methods of dictionaries
len() method
It returns the length of the dictionary, i.e., the count of elements (key:
value pairs) in the dictionary
len(dictionary)
Copy
clear() method
Removes all the elements from the dictionary
dictionary.clear()
Copy
get() method
Returns the value of the specified key
dictionary.get(keyname)
Copy
items() method
Returns a list containing a tuple for each key-value pair
dictionary.items()
Copy
keys() method
Returns a list containing the dictionary's keys
dictionary.keys()
Copy
values() method
Returns a list of all the values in the dictionary
dictionary.values()
Copy
update() method
Updates the dictionary with the specified key-value pairs
dictionary.update(iterable)
Copy
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.
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
Copy
if-else Statement
if(conditional expression):
statements
else:
statements
Copy
if-elif Statement
if (conditional expression):
statements
elif (conditional expression):
statements
else:
statements
Copy
Nested if-else Statement
if (conditional expression):
if (conditional expression):
statements
else:
statements
else:
statements
Copy
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.
Copy
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
Copy
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.
Copy
Continue Statement
The continue statement skips the rest of the loop statements and
causes the next iteration to occur.
Copy
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(parameters):
#statements
Copy
def keyword is used before defining the function.
Function Call
my_function(parameters)
Copy
Whenever we need that block of code in our program simply call that
function name whenever neeeded. If parameters are passed during
defing the function we have to pass the parameters while calling that
function
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
Copy
modes-
close() function
var_name.close()
Copy
read () function
The read functions contains different methods, read(),readline() and
readlines()
Copy
It returns a list of lines
Copy
It returns one line at a time
Copy
write function
This function writes a sequence of strings to the file.
Copy
It is used to write a list of strings
writelines()
Copy
Exception Handling
An exception is an unusual condition that results in an interruption in
the flow of a 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.
try:
[Statement body block]
raise Exception()
except Exceptionname:
[Error processing block]
Copy
else
The else block is executed if the try block have not raise any exception
and code had been running successfully
try:
#statements
except:
#statements
else:
#statements
Copy
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)
It is 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
class class_name:
pass #statements
Copy
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 it is 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
class CodeWithHarry:
# Default constructor
def __init__(self):
self.name = "CodeWithHarry"
Copy
Creating an object
Instantiating an object can be done as follows:
<object-name> = <class-name>(<arguments>)
Copy
filter function
The filter function allows you to process an iterable and extract those
items that satisfy a given condition
filter(function, iterable)
Copy
issubclass function
Used to find whether a class is a subclass of a given class or not as
follows
issubclass(obj, classinfo) # returns true if obj is a
subclass of classinfo
Copy
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
Copy
Generator
Used to generate values on the fly
Copy
Decorators
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)
@property
def name(self):
return self.__name
Copy
setter Decorator
It is used to set the property 'name'
@name.setter
def name(self, value):
self.__name=value
Copy
deleter Decorator
It is used to delete the property 'name'