Python Cheat Sheet: Click Here
Python Cheat Sheet: Click Here
Python Cheat Sheet: Click Here
© Copyright by Interviewbit
Contents
21. Comprehensions in Python
22. String Manipulation in Python
23. Formatting Dates in Python
24. Python RegEx
25. Debugging in Python
26. Logging in Python
27. Lambda Function in Python
28. Ternary Operator in Python
29. *args and **kwargs in Python
30. if __name__ == "__main__" in Python
31. Python Dataclasses
32. Python Virtual Environment
33. Python Commands
Returns sum
+ Addition of 2 1+3=4
numbers
Returns the
- Subtraction difference of 1 - 3 = -2
2 numbers
Returns the
* Multiplication product of 2 1*3=3
numbers
Returns the
value of a
1/3=
/ Division divided by b
0.33
as a decimal
value
Returns the
Floored
// floor of a 1 // 3 = 0
Division
divided by b
Returns the
remainder
% Remainder 1%3=1
when a is
divided by b
DataTypes Examples
Integers 0, 2, -1, 5
3. Python Variables
Variables are names given to data items that may take on one or more values during
a program’s runtime.
Following are the variable naming conventions in python:
It cannot begin with a number.
It must be a single word.
It must consist of letters and _ symbols only.
Variables in Python which start with _ (underscore) are considered as “Unuseful”.
Some examples are shown below:
4. Python Comments
Comments are lines of text/code in the program, which are ignored by the compiler
during program execution.
There are multiple types of comments in python:
Inline Comment -
We can write an Inline Comment by typing # followed by the comment.
Multiline Comment -
We can write a Multiline Comment by typing # followed by the comment in each of
the lines.
# Multiline
# Comment
# Function to calculate
# sum of 2 numbers
def fun(a, b):
return a + b
Docstring Comment -
Docstring comments are achieved by Typing the comment within triple quotes. ( '''
comment ''' )
'''
This is a function
to find sum
of 2 numbers.
This is an example of
docstring comment.
'''
def fun(a, b):
return a + b
# For List
a = [1, 2, 3]
print(len(a))
# For string
a = "hello"
print(len(a))
# For tuple
a = ('1', '2', '3')
print(len(a))
The ord() function in Python will return an integer that represents the Unicode
Character passed into it. It takes a single character as a parameter.
Example:
Implicit Type Casting: In implicit type casting, the python compiler internally
typecasts one variable into another type without the external action of the user.
Example:
int_num = 100
float_num = 1.01
ans = int_num + float_num
print(type(int_num))
print(type(float_num))
# ans is implicitly typecasted to float type for greater precision
print(type(ans))
Explicit Type Casting: In explicit type casting, the user explicitly forces the
compiler to convert a variable from one type to another. The different ways of
explicit typecasting are given below:
1. Integer to String or Float:
To typecast an integer into a string type, we use the str() method. Similarly, to
typecast it into a float type, we use the float() method.
For example:
2. Float to Integer:
To typecast a float datatype into an integer datatype, we use the int() method.
For example:
== Is equal to
!= Not Equal to
# Equality Operator
>>> 10 == 10
True # 10 is equal to 10, so true
>>> 10 == "10"
False # The first string is of type int, 2nd of type string, so false.
# Greater than
>>> 10 > 20
False # 10 is lesser than 20, so above expression is false.
# Inequality
>>> 10 != 20
True # 10 is not equal to 20, so the expression is true
# Greater than or equal to
>>> (2 + 3) >= (4 + 1)
True # (2 + 3) = 5 and (4 + 1) = 5, so the expression is true.
Examples:
# and operator
print(True and False)
False
# or operator
print(True or False)
True
# not operator
print(not False)
True
Else Statements: This statement is used to perform some operation, if all the if
and elif statements evaluates to be false.
for i in range(5):
print(i)
Output:
0
1
2
3
4
a = [1, 3, 5, 7]
for ele in a:
print(ele)
Output:
1
3
5
7
While Loops:
This is used for executing set of statements within its block as long as the
associated loop condition is evaluated to True as shown in the image below:
>>> count = 5
>>> while count > 0:
... print(count)
... count -= 1
...
5
4
3
2
1
continue: continue statement allows us to send the control back to the starting
of the loop, skipping all the lines of code below it in the loop. This is explained in
the flowchart below:
pass: The pass statement is basically a null statement, which is generally used as
a placeholder. It is used to prevent any code from executing in its scope.
for i in range(5):
if i % 2 == 0:
pass
else:
print(i)
Output:
1
3
return: return statement allows us to send the control of the program outside
the function we are currently in. A function can have multiple return statements,
but can encounter only one of them during the course of its execution.
def func(x):
if x == 'Hello':
return True
else:
return False
12. Functions in Python
Functions are used to well-organized our code and enhance code readability and
reusability. In Python, a function is defined using the def keyword. A function can
return some value, or not depending upon its use case. If it has to return a value, the
return statement (which has been discussed) is used. The syntax of a python function
is shown in the image below:
Example of a function:
print(getSum(5, 6))
printSum(5, 6)
The rules used in Python to resolve scope for local and global variables are as follows:
Code in the global scope cannot use any local variables.
Code in a function’s local scope cannot use variables in any other local scope.
However, a local scope can access global variables.
We can use the same name for different variables if they are in different scopes.
14. Global Statement
To modify a global variable from inside a function, we use the global statement:
def func():
global value
value = "Local"
value = "Global"
func()
print(value)
Output:
Local
We set the value of “value” as Global. To change its value from inside the function, we
use the global keyword along with “value” to change its value to local, and then print
it.
import math
print(math.pi)
Output:
3.141592653589793
If we want to perform any string manipulations, we can use the string module as
import string in python. More of this is covered in the String Manipulation section
below.
Example:
17. Lists in Python
Lists are used to store multiple items in a single variable. Their usage and some
functions are shown below with examples:
Slicing a List:
Slicing is the process of accessing a part or subset of a given list. The slicing is
explained in the image below:
Copying the contents of a list, some finite number of times into the same or some list
is called list replication.
Output:
Sunday
Monday
Tuesday
Wednesday
Sorting a List:
Sorting a list means arranging the elements of the list in some particular order.
We sort a list by using the sort() function.
example = [1, 5, 3, 7, 2]
# Sort in ascending order
example.sort()
print(example)
# Sort in descending order
example.sort(reverse = True)
print(example)
Output:
['Sunday', 'Monday', 'Tuesday', 'Wednesday']
['Monday', 'Sunday', 'Tuesday', 'Wednesday']
['Wednesday', 'Tuesday', 'Sunday', 'Monday']
[1, 2, 3, 5, 7]
[7, 5, 3, 2, 1]
18. Tuples in Python
Tuples are entities in Python that work almost similar to that of lists, but differ in the
main feature from lists, is in that they are inmutable.
They are initialized by writing the elements of the tuple with (), separated by
commas.
19. Python Dictionaries
Dictionaries in Python are equivalent to Maps in C++/JAVA. They are used to store
data in key-value pairs.
Printing key and values in dictionaries:
To print the keys of the dictionary, use the .keys() method and to print the values, use
.values() method.
Output:
first
second
third
sunday
monday
tuesday
Merging 2 dictionaries
We can merge 2 dictionaries into 1 by using the update() method.
20. Sets in Python
Initializing Sets:
Sets are initialized using curly braces {} or set() in python.
A python set is basically an unordered collection of unique values, i.e. it will
automatically remove duplicate values from the set.
s = {1, 2, 3}
print(s)
s = set([1, 2, 3])
print(s)
s = {1, 2, 3, 3, 2, 4, 5, 5}
print(s)
Output:
{1, 2, 3}
{1, 2, 3}
{1, 2, 3, 4, 5}
s = {1, 2, 3, 3, 2, 4, 5, 5}
print(s)
# Insert single element
s.add(6)
print(s)
Output:
{1, 2, 3, 4, 5}
{1, 2, 3, 4, 5, 6}
To insert multiple elements into a set, we use the update function and pass a list of
elements to be inserted as parameters.
s = {1, 2, 3, 3, 2, 4, 5, 5}
# Insert multiple elements
s.update([6, 7, 8])
print(s)
Output:
{1, 2, 3, 4, 5, 6, 7, 8}
s = {1, 2, 3, 3, 2, 4, 5, 5}
print(s)
# Remove will raise an error if the element is not in the set
s.remove(4)
print(s)
# Discard doesn't raise any errors
s.discard(1)
print(s)
Output:
{1, 2, 3, 4, 5}
{1, 2, 3, 5}
{2, 3, 5}
Operators in sets:
Examples:
a = {1, 2, 3, 3, 2, 4, 5, 5}
b = {4, 6, 7, 9, 3}
# Performs the Intersection of 2 sets and prints them
print(a & b)
# Performs the Union of 2 sets and prints them
print(a | b)
# Performs the Difference of 2 sets and prints them
print(a - b)
# Performs the Symmetric Difference of 2 sets and prints them
print(a ^ b)
Output:
{3, 4}
{1, 2, 3, 4, 5, 6, 7, 9}
{1, 2, 5}
{1, 2, 5, 6, 7, 9}
21. Comprehensions in Python
List Comprehensions:
It is a shorter syntax to create a new list using values of an existing list.
a = [0, 1, 2, 3]
# b will store values which are 1 greater than the values stored in a
b = [i + 1 for i in a]
print(b)
Output:
[1, 2, 3, 4]
Set Comprehension:
It is a shorter syntax to create a new set using values of an existing set.
a = {0, 1, 2, 3}
# b will store squares of the elements of a
b = {i ** 2 for i in a}
print(b)
Output:
{0, 1, 4, 9}
Dict Comprehension:
It is a shorter syntax to create a new dictionary using values of an existing
dictionary.
a = {'Hello':'World', 'First': 1}
# b stores elements of a in value-key pair format
b = {val: k for k , val in a.items()}
print(b)
Output:
{'World': 'Hello', 1: 'First'}
\t Tab Space
\n Newline
\\ Backslash
\’ Single Quote
Multiline Strings:
Multiline Strings are used in python through triple quotes '''
Example:
a = ''' Hello
World!
This is a
Multiline String.'''
print(a)
Output:
Hello
World!
This is a
Multiline String.
Strings Indexing:
Strings in Python are indexed the same way as a list of characters, based on 0-based
indexing. We can access elements of a string at some index by using the [] operators.
Consider an example of the string value Python .
a = "Python"
print(a[0], a[2], a[4])
print(a[-1], a[-3], a[-5])
Output:
P t o
n h y
Strings Slicing:
a = "Hello"
# Slices the string from 0 to 3 indexes
print(a[0:3])
# Slices the string from 3 to -1(same as 4) indexes
print(a[3:-1])
Output:
Hel
l
a = "Hello"
print(a)
# Converts string to uppercase
print(a.upper())
# Converts string to lowercase
print(a.lower())
# Checks if string is uppercase
print(a.isupper())
# Checks if string is lowercase
print(a.islower())
Output:
Hello
HELLO
hello
False
False
Function Explanation
split() function splits the into tokens, based on some delimiters and returns the result
as a list.
# split function
newList = s.split(',')
print(newList)
Output:
['One', 'Two', 'Three']
In general, a string can be split to list using split() method and a list can be joined to
string using the join() method as shown in the image below:
String Formatting:
String Formatting is done with the str.format() function.
first = "first"
second = "second"
s = "Sunday is the {} day of the week, whereas Monday is the {} day of the week".format
print(s)
Output:
Sunday is the first day of the week, whereas Monday is the second day of the week
Template Strings:
It is recommended to be used when formatting strings generated by users. They
make the code less complex so are easier to understand. They can be used by
importing the Template class from the string module.
Example:
import datetime
tm = datetime.time(1, 30, 11, 22)
print(tm)
Output:
01:30:11.000022
date class: We can represent date values using the date class.
Example:
import datetime
date = datetime.date(2000, 11, 16)
print('Date date is ', date.day, ' day of ', date.month, ' month of the year ', date
Output:
Date date is 16 day of 11 month of the year 2000
Conversion from date to time: We can convert a date to its corresponding time
using the strptime() function.
Example:
24. Python RegEx
Regex Matching
The re module in python allows us to perform regex matching operations.
import re
landline = re.compile(r'\d\d\d\d-\d\d\d\d')
num = landline.search('LandLine Number is 2435-4153')
print('Landline Number is: {}'.format(num.group()))
Output:
Landline Number is: 2435-4153
The above example landline number from the string and stores it appropriately in the
num variable using regex matching.
Parenthesis Grouping
A group is a part of a regex pattern enclosed in parenthesis (). We can put matches
into different groups using the parenthesis (). We can access the groups using group()
function.
import re
landline = re.compile(r'(\d\d\d\d)-(\d\d\d\d)')
num = landline.search('LandLine Number is 2435-4153')
# This will print the first group, which is the entire regex enclosed in the brackets
print(num.group(0))
# This will print the second group, which is the nested regex enclosed in the 1st set o
print(num.group(1))
# This will print the third group, which is the nested regex enclosed in the 2nd set of
print(num.group(2))
Output:
2435-4153
2435
4153
Symbol Matches
Example:
Here we define a regex pattern,
address = "(\\d*)\\s?(.+),\\s(.+)\\s([A-Z]{2,3})\\s(\\d{4})"
From the above table, we can explain some of the symbols in this pattern:
\s?: 0 or 1 whitespace.
(\d*): 0 or more digit characters.
(.+): Greater than or equal to 1 characters.
\s: Single Whitespace
([A-Z]{2, 3}): 2 or 3 Uppercase alphabets
(\d{4}): 4 digit characters
25. Debugging in Python
Raising Exceptions with raise statement:
The raise statement is used to raise exceptions and consists of 3 components:
raise keyword
Exception() function call
Parameter of the Exception() function, which usually contains an error message.
Traceback as String
There is a function in python called traceback.format_exc() which returns the
traceback displayed by Python when a raised Exception is not handled as a String
type. The Traceback Module is required to be imported for this purpose.
Example:
import traceback
try:
raise Exception('Error Message.')
except:
with open('error.txt', 'w') as error_file:
error_file.write(traceback.format_exc())
print('The traceback info was written to error.txt.')
Output:
The traceback info was written to error.txt.
>>> sum = 4
>>> assert sum == 5, 'Addition Error'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError: Addition Error
Assertions can be disabled by passing the -O option when running Python as shown in
the commands below.
26. Logging in Python
Logging allows us to keep track of some events which occurs when some so ware
runs. It becomes highly important in So ware Development, Debugging and Running
So wares.
import logging
# Create and configues the logger
logging.basicConfig(filename="newfile.log", format='%(asctime)s %(message)s', filemode=
# Creates logging object
logg = logging.getLogger()
# Sets the level of logging to DEBUG
logg.setLevel(logging.DEBUG)
# Messages
logg.debug("Debug Message")
logger.warning("Its a Warning")
logger.info("Just an information")
Levels of Logging:
Described in order of increasing importance
Confirms the
working of things
INFO logging.info() at the end of the
module in the
program.
Indicates or flags
CRITICAL logging.critical() fatal errors in the
program.
These are small anonymous functions in python, which can take any number of
arguments but returns only 1 expression.
Let us understand it with an example,
Consider the function which multiplies 2 numbers:
mul = lambda a, b: a * b
print(mul(3, 5))
Output:
15
f = 2
s = 2
# if the sum of f and s is greater than 0 the sum
# is printed, else 0 is printed
print(f + s if (f + s > 0) else 0)
Output:
4
31. Python Dataclasses
Python Classes used for storing data objects are called Dataclasses. They have certain
features like:
Comparison with other objects of the same type is possible.
Stores data, representing a particular data type.
Python 2.7:
The example shows the performing function of Dataclasses in older versions of
python when Dataclasses were not yet introduced.
class Self:
def __init__(self, x):
self.x = x
ob = Self("One")
print(ob.x)
Output:
One
Python 3.7:
The example shows using dataclasses in newer versions of python.
Usage Steps:
33. Python Commands
Magic Commands are one of the new features added to the python shell. Basically,
they are enhancements over the normal python code, provided by the IPython
Kernel. The main syntax for these commands is that they are prefixed by as “%”
character. They prove useful in solving many common problems we encounter while
coding and also provide us some versatile shortcuts.
There are main kinds of commands:
%prefix: The command will operate only on the given single line of code.
%%prefix: The command will operate on the entire code block.
Some examples of these commands in Python are:
%run: It is used for running an external file in Python.
def runner():
print("Hello World")
runner()
%run runner.py
Output:
Hello World
%%time: This allows us to track the amount of time taken by our code for
execution.
%%time
for i in range(10000):
a = a + i**2
Output:
CPU Times: user: 3.72 ms, sys: 9us, , total: 3.73ms, Wall time: 3.75ms
%%writefile: This command will copy content from our current code cell to
another external file.
%%writefile code.py
def func():
print("Hello")
func()
Output:
Overwriting code.py
%pycat code.py
def func():
print("Hello")
func()
%who: This command lists all the variables in the Python notebook.
a = "hello"
b = 5
c = 1
%who
Output:
a b c
%%html: This command will let us write and execute html code in the current
cell.
%%html
<html>
<body>
<table>
<tr>
<th>Name</th>
<th>Country</th>
<th>Age</th>
</tr>
<tr>
<td>Sid</td>
<td>India</td>
<td>22</td>
</tr>
<tr>
<td>Dave</td>
<td>UK</td>
<td>28</td>
</tr>
</table>
</body>
</html>
Output:
%env: This command allows us to list all the environment variables, set a value
for such a variable, and get the value of such a variable.
Note: All the magic commands can be listed by using the %lsmagic command.
Some other useful tools for Python
Conclusion
We can conclude that Python is a robust, high-level, interpreted programming
language. It is also an Object Oriented Programming Language that strongly follows
all OOPs principles. It has various inbuilt powerful modules that follow simple syntax
which makes it appealing to both beginners and experienced folks alike. A vast
collection of libraries and functions makes the development of any sort much easier
in Python. In this cheat sheet, we have covered the most common fundamentals of
python language that would help you kickstart your career in python.
Useful Resources:
Python Interview Questions
Python Projects
Python Developer: Career Guide
Python Developer Skills
Fast Track Python
Css Interview Questions Laravel Interview Questions Asp Net Interview Questions