Understanding Python: Features & Applications
Understanding Python: Features & Applications
Python was created and first released in 1991 by Guido van Rossum. It is a high-level,
general-purpose programming language emphasizing code readability and providing
easy-to-use syntax.
Several developers and programmers prefer using Python for their programming needs
due to its simplicity.
2. Why Python?
– Web Applications:
We can use Python to develop web applications. It contains HTML and XML libraries,
JSON libraries, email processing libraries, request [Link] uses Django, a
Python web framework.
This is the time of artificial intelligence, in which a machine can execute tasks as well as
a person can. Python is an excellent programming language for artificial intelligence and
machine learning applications. It has a number of scientific and mathematical libraries
that make doing difficult computations simple.A few prominent machine library
frameworks are listed below.
● NumPy
● Pandas
● Matplotlib
● SciPy
– Business Applications:
Standard apps are not the same as business applications. This type of program
necessitates a lot of scalability and readability, which Python gives.
3D CAD Applications
● Fandango (Popular)
● CAMVOX
Python is one of the most popular programming languages used by data scientists and
AIML professionals. This popularity is due to the following key features of Python:
A literal is a simple and direct form of expressing a value. Literals reflect the primitive
type options available in that [Link], floating-point numbers, Booleans, and
character strings are some of the most common forms of literal.
Python is an interpreted language with dynamic typing. Because the code is not
converted to a binary form, these languages are sometimes referred to as “scripting”
languages. While I say dynamically typed, I’m referring to the fact that types don’t have
to be stated when coding; the interpreter finds them out at runtime.
8. What is pep 8?
Local Namespace: This namespace stores the local names of functions. This
namespace is created when a function is invoked and only lives till the function returns.
Global Namespace: Names from various imported modules that you are utilizing in a
project are stored in this namespace. It’s formed when the module is added to the
project and lasts till the script is completed.
Built-in Namespace: This namespace contains the names of built-in functions and
exceptions.
Local variables are declared inside a function and have a scope that is confined to that
function alone, whereas global variables are defined outside of any function and have a
global scope. To put it another way, local variables are only available within the function
in which they were created, but global variables are accessible across the programme
and throughout each function.
Local Variables
Local variables are variables that are created within a function and are exclusive to that
function. Outside of the function, it can’t be accessed.
Global Variables
Global variables are variables that are defined outside of any function and are available
throughout the programme, that is, both inside and outside of each function.
Benefits:
There are several compelling reasons to utilize Flask as a web application framework.
Like-
Django is more popular because it has plenty of functionality out of the box, making
complicated applications easier to build. Django is best suited for larger projects with a
lot of features. The features may be overkill for lesser applications.
1. Model
The Model, which is represented by a database, is the logical data structure that
underpins the whole programme (generally relational databases such as MySql,
Postgres).
2. View
The View is the user interface, or what you see when you visit a website in your
browser. HTML/CSS/Javascript files are used to represent them.
3. Controller
The Controller is the link between the view and the model, and it is responsible for
transferring data from the model to the view.
Your application will revolve around the model using MVC, either displaying or altering
it.
15. Explain Scope in Python?
Think of scope as the father of a family; every object works within a scope. A formal
definition would be this is a block of code under which no matter how many objects you
declare they remain relevant. A few examples of the same are given below:
● Local Scope: When you create a variable inside a function that belongs to
the local scope of that function itself and it will only be used inside that
function.
Example:
def harshit_fun():
y = 100
print (y)
harshit_func()
100
● Global Scope: When a variable is created inside the main body of python
code, it is called the global scope. The best part about global scope is they
are accessible within any part of the python code from any scope be it global
or local.
Example:
y = 100
def harshit_func():
print (y)
harshit_func()
print (y)
Example:
def first_func():
y = 100
def nested_func1():
print(y)
nested_func1()
first_func()
● Module Level Scope: This essentially refers to the global objects of the
current module accessible within the program.
● Outermost Scope: This is a reference to all the built-in names that you can
call in the program.
List: We have already seen a bit about lists, to put a formal definition a list is an ordered
sequence of items that are mutable, also the elements inside lists can belong to
different data types.
Example:
Tuples: This too is an ordered sequence of elements but unlike lists tuples are
immutable meaning it cannot be changed once declared.
Example:
String: This is called the sequence of characters declared within single or double
quotes.
Example:
Sets: Sets are basically collections of unique items where order is not uniform.
Example:
set = {1,2,3}
Dictionary: A dictionary always stores values in key and value pairs where each value
can be accessed by its particular key.
Example:
The attributes of a class are also called variables. There are three access modifiers in
Python for variables, namely
b. private – The variables declared as private are accessible only within the current
class.
c. protected – The variables declared as protected are accessible only within the current
package.
– Local attributes are defined within a code-block/method and can be accessed only
within that code-block/method.
– Global attributes are defined outside the code-block/method and can be accessible
everywhere.
class Mobile:
def price(self):
return m2
Sam_m = Mobile()
print(Sam_m.m1)
18. What are Keywords in Python?
Keywords in Python are reserved words that are used as identifiers, function names, or
variable names. They help define the structure and syntax of the language.
There are a total of 33 keywords in Python 3.7 which can change in the next version,
i.e., Python 3.8. A list of all the keywords is provided below:
Keywords in Python:
as elif if or yield
break except
List and tuple are data structures in the python that may store one or more objects or
values. Using square brackets, you may build a list to hold numerous objects in one
variable. Tuples, like arrays, may hold numerous items in a single variable and are
defined with parenthesis.
Lists Tuples
The impacts of iterations are Time Consuming. Iterations have the effect of making
things go faster.
The list is more convenient for actions like The items may be accessed using the
insertion and deletion. tuple data type.
There are numerous techniques built into lists. There aren’t many built-in methods in
Tuple.
Changes and faults that are unexpected are It is difficult to take place in a tuple.
more likely to occur.
They consume a lot of memory given the nature They consume less memory
of this data structure
tup1 = (1,”a”,True)
tup2 = (4,5,6)
Concatenation of tuples means that we are adding the elements of one tuple at the end
of another tuple.
Code:
tup1=(1,"a",True)
tup2=(4,5,6)
tup1+tup2
All you have to do is, use the ‘+’ operator between the two tuples and you’ll get the
concatenated result.
Functions in Python refer to blocks that have organized, and reusable codes to perform
single, and related events. Functions are important to create better modularity for
applications that reuse a high degree of coding. Python has a number of built-in
functions like print(). However, it also allows you to create user-defined functions.
22. How can you initialize a 5*5 numpy arrays with only zeroes?
import numpy as np
n1=[Link]((5,5))
n1
Use [Link]() and pass in the dimensions inside it. Since we want a 5*5 matrix, we will
pass (5,5) inside the .zeros() method.
Pandas is an open-source python library that has a very rich set of data structures for
data-based operations. Pandas with their cool features fit in every role of data
operation, whether it be academics or solving complex business problems. Pandas can
deal with a large variety of files and are one of the most important tools to have a grip
on.
A pandas dataframe is a data structure in pandas that is mutable. Pandas have support
for heterogeneous data which is arranged across two axes. ( rows and columns).
Here, df is a pandas data frame. read_csv() is used to read a comma-delimited file as a
dataframe in pandas.
25. What is a Pandas Series?
Series is a one-dimensional panda’s data structure that can data of almost any type. It
resembles an excel column. It supports multiple operations and is used for
single-dimensional data operations.
Code:
import pandas as pd
data=["1",2,"three",4.0]
series=[Link](data)
print(series)
print(type(series))
A pandas group by is a feature supported by pandas that are used to split and group an
object. Like the sql/mysql/oracle group by it is used to group data by classes, and
entities which can be further used for aggregation. A dataframe can be grouped by one
or more columns.
Code:
df =
[Link]({'Vehicle':['Etios','Lamborghini','Apache200','Pulsar200
'], 'Type':["car","car","motorcycle","motorcycle"]})
df
Code:
df=[Link]()
bikes=["bajaj","tvs","herohonda","kawasaki","bmw"]
cars=["lamborghini","masserati","ferrari","hyundai","ford"]
df["cars"]=cars
df["bikes"]=bikes
df
Code:
import pandas as pd
bikes=["bajaj","tvs","herohonda","kawasaki","bmw"]
cars=["lamborghini","masserati","ferrari","hyundai","ford"]
d={"cars":cars,"bikes":bikes}
df=[Link](d)
df
Two different data frames can be stacked either horizontally or vertically by the concat(),
append(), and join() functions in pandas.
Concat works best when the data frames have the same columns and can be used for
concatenation of data having similar fields and is basically vertical stacking of
dataframes into a single dataframe.
Append() is used for horizontal stacking of data frames. If two tables(dataframes) are to
be merged together then this is the best concatenation function.
Join is used when we need to extract data from different dataframes which are having
one or more common columns. The stacking is horizontal in this case.
Before going through the questions, here’s a quick video to help you refresh your
memory on Python.
Pandas have a left join, inner join, right join, and outer join.
Merging depends on the type and fields of different data frames being merged. If data
has similar fields data is merged along axis 0 else they are merged along axis 1.
32. Give the below dataframe drop all rows having Nan.
[Link](inplace=True)
df
33. How to access the first five entries of a dataframe?
By using the head(5) function we can get the top five entries of a dataframe. By default
[Link]() returns the top 5 rows. To get the top n rows [Link](n) will be used.
By using the tail(5) function we can get the top five entries of a dataframe. By default
[Link]() returns the top 5 rows. To get the last n rows [Link](n) will be used.
35. How to fetch a data entry from a pandas dataframe using a given value
in index?
Code:
import pandas as pd
bikes=["bajaj","tvs","herohonda","kawasaki","bmw"]
cars=["lamborghini","masserati","ferrari","hyundai","ford"]
d={"cars":cars,"bikes":bikes}
df=[Link](d)
a=[10,20,30,40,50]
[Link]=a
[Link][10]
36. What are comments and how can you add comments in Python?
“””Note
Note
Note”””—–multiline comment
Example
d={“a”:1,”b”:2}
One major difference between a tuple and a dictionary is that a dictionary is mutable
while a tuple is not. Meaning the content of a dictionary can be changed without
changing its identity, but in a tuple, that’s not possible.
39. Find out the mean, median and standard deviation of this numpy array
-> [Link]([1,5,3,100,4,48])
import numpy as np
n1=[Link]([10,20,30,40,50,60])
print([Link](n1))
print([Link](n1))
print([Link](n1))
A classifier is used to predict the class of any data point. Classifiers are special
hypotheses that are used to assign class labels to any particular data point. A classifier
often uses training data to understand the relation between input variables and the
class. Classification is a method used in supervised learning in Machine Learning.
All the upper cases in a string can be converted into lowercase by using the method:
[Link]()
ex:
We can use the capitalize() function to capitalize the first character of a string. If the
first character is already in the capital then it returns the original string.
Syntax:
1 string_name.capitalize()
ex:
n = “greatlearning” print([Link]())
Syntax:
1 list_name.insert(index, element)
ex:
list = [ 0,1, 2, 3, 4, 5, 6, 7 ]
[Link](6, 10)
o/p: [0,1,2,3,4,5,10,6,7]
45. How will you remove duplicate elements from a list?
There are various methods to remove duplicate elements from a list. But, the most
common one is, converting the list into a set by using the set() function and using the
list() function to convert it back to a list if required.
ex:
list0 = [2, 6, 4, 7, 4, 6, 7, 2]
Recursion is a function calling itself one or more times in its body. One very important
condition a recursive function should have to be used in a program is, it should
terminate, else there would be a problem of an infinite loop.
List comprehensions are used for transforming one list into another list. Elements can
be conditionally included in the new list and each element can be transformed as
needed. It consists of an expression leading to a for clause, enclosed in brackets.
For ex:
print list
48. What is the bytes() function?
The bytes() function returns a bytes object. It is used to convert objects into bytes
objects or create empty bytes objects of the specified size.
The “with” statement in python is used in exception handling. A file can be opened and
closed while executing a block of code, containing the “with” statement., without using
the close() function. It essentially makes the code much easier to read.
The map() function in Python is used for applying a function on all elements of a
specified iterable. It consists of two parameters, function and iterable. The function is
taken as an argument and then applied to all the elements of an iterable(passed as the
second argument). An object list is returned as a result.
def add(n):
print(list(res))
o/p: 30,50,70,90
52. What is __init__ in Python?
The two static analysis tools used to find bugs in Python are Pychecker and Pylint.
Pychecker detects bugs from the source code and warns about its style and complexity.
While Pylint checks whether the module matches upto a coding standard.
Pass is a statement that does nothing when executed. In other words, it is a Null
statement. This statement is not ignored by the interpreter, but the statement results in
no operation. It is used when you do not want any command to execute but a statement
is required.
Not all objects can be copied in Python, but most can. We can use the “=” operator to
copy an object to a variable.
ex:
var=[Link](obj)
Modules are the way to structure a program. Each Python program file is a module,
importing other attributes and objects. The folder of a program is a package of modules.
A package can have modules or subfolders.
In Python, the object() function returns an empty object. New properties or methods
cannot be added to this object.
NumPy stands for Numerical Python while SciPy stands for Scientific Python. NumPy is
the basic library for defining arrays and simple mathematical problems, while SciPy is
used for more complex problems like numerical integration and optimization and
machine learning and so on.
len() is used to determine the length of a string, a list, an array, and so on.
ex:
str = “greatlearning”
print(len(str))
o/p: 13
Encapsulation means binding the code and the data together. A Python class for
example.
62. What is the type () in Python?
type() is a built-in method that either returns the type of the object or returns a new type
of object based on the arguments passed.
ex:
a = 100
type(a)
o/p: int
Split function is used to split a string into shorter strings using defined separators.
n = [Link](“,”)
print(n)
1. Integer: All positive and negative numbers without a fractional part
2. Float: Any real number with floating-point representation
3. Complex numbers: A number with a real and imaginary component
represented as x+yj. x and y are floats and j is -1(square root of -1 called an
imaginary number)
Boolean: The Boolean data type is a data type that has one of two possible values i.e.
True or False. Note that ‘T’ and ‘F’ are capital letters.
String: A string value is a collection of one or more characters put in single, double or
triple quotes.
List: A list object is an ordered collection of one or more data items that can be of
different types, put in square brackets. A list is mutable and thus can be modified, we
can add, edit or delete individual elements in a list.
Frozen set: They are like a set but immutable, which means we cannot modify their
values once they are created.
Python docstrings are the string literals enclosed in triple quotes that appear right after
the definition of a function, method, class, or module. These are generally used to
describe the functionality of a particular function, method, class, or module. We can
access these docstrings using the __doc__ attribute.
Here is an example:
def square(n):
return n**2
print(square.__doc__)
Ouput: Takes in a number n, returns the square of n.
In Python, there are no in-built functions that help us reverse a string. We need to make
use of an array slicing operation for the same.
1 str_reverse = string[::-1]
To check the Python Version in CMD, press CMD + Space. This opens Spotlight. Here,
type “terminal” and press enter. To execute the command, type python –version or
python -V and press enter. This will return the python version in the next line below the
command.
================================================================
Intermediate level
===============================================================
69. How to create a new column in pandas by using values from other
columns?
Code:
import pandas as pd
a=[1,2,3]
b=[2,3,5]
d={"col1":a,"col2":b}
df=[Link](d)
df["Sum"]=df["col1"]+df["col2"]
df["Difference"]=df["col1"]-df["col2"]
df
Output:
70. What are the different functions that can be used by group by in pandas
?
grouby() in pandas can be used with multiple aggregate functions. Some of which are
sum(),mean(), count(),std().
Data is divided into groups based on categories and then the data in these individual
groups can be aggregated by the aforementioned functions.
d={"col1":[1,2,3],"col2":["A","B","C"]}
df=[Link](d)
df=[Link](["col1"],axis=1)
df
72. Given the following data frame drop rows having column values as A.
Code:
d={"col1":[1,2,3],"col2":["A","B","C"]}
df=[Link](d)
[Link](inplace=True)
df=df[df.col1!=1]
df
Code:
import pandas as pd
bikes=["bajaj","tvs","herohonda","kawasaki","bmw"]
cars=["lamborghini","masserati","ferrari","hyundai","ford"]
d={"cars":cars,"bikes":bikes}
df=[Link](d)
a=[10,20,30,40,50]
[Link]=a
df
74. What do you understand about the lambda function? Create a lambda
function which will print the sum of all the elements in this list -> [5, 8, 10,
20, 50, 100]
Lambda functions are anonymous functions in Python. They are defined using the
keyword lambda. Lambda functions can take any number of arguments, but they can
only have one expression.
print(sum)
vstack() is a function to align rows vertically. All rows must have the same number of
elements.
Code:
import numpy as np
n1=[Link]([10,20,30,40,50])
n2=[Link]([50,60,70,80,90])
print([Link]((n1,n2)))
Spaces can be removed from a string in python by using strip() or replace() functions.
Strip() function is used to remove the leading and trailing white spaces while the
replace() function is used to remove all the white spaces in the string:
print ([Link]())
o/p: greatlearning
Pickling is the process of converting a Python object hierarchy into a byte stream for
storing it into a database. It is also known as serialization. Unpickling is the reverse of
pickling. The byte stream is converted back into an object hierarchy.
Memory management in python comprises a private heap containing all objects and
data structure. The heap is managed by the interpreter and the programmer does not
have access to it at all. The Python memory manager does all the memory allocation.
Moreover, there is an inbuilt garbage collector that recycles and frees memory for the
heap space.
Unittest is a unit testing framework in Python. It supports sharing of setup and shutdown
code for tests, aggregation of tests into collections,test automation, and independence
of the tests from the reporting framework.
To create an empty class we can use the pass command after the definition of the class
object. A pass is a statement in Python that does nothing.
Decorators are functions that take another function as an argument to modify its
behavior without changing the function itself. These are useful when we want to
dynamically increase the functionality of a function without changing it.
Here is an example:
def smart_divide(func):
print("Dividing", a, "by", b)
if b == 0:
return func(a, b)
return inner
@smart_divide
print(a/b)
divide(1,0)
1. In dynamic typed language the objects are bound with type by assignments at
run time.
2. Dynamically typed programming languages produce less optimized code
comparatively
3. In dynamically typed languages, types for variables need not be defined
before using them. Hence, it can be allocated dynamically.
Slicing in Python refers to accessing parts of a sequence. The sequence can be any
mutable and iterable object. slice( ) is a function used in Python to divide the given
sequence into required segments.
There are two variations of using the slice function. Syntax for slicing in python:
1. slice(start,stop)
2. silica(start, stop, step)
Ex:
Str1 = ("g", "r", "e", "a", "t", "l", "e", "a", “r”, “n”, “i”, “n”,
“g”)
substr1 = slice(3, 5)
print(Str1[substr1])
Str1 = ("g", "r", "e", "a", "t", "l", "e", "a", “r”, “n”, “i”, “n”,
“g”)
print(Str1[3,5])
Str1 = ("g", "r", "e", "a", "t", "l", "e", "a", “r”, “n”, “i”, “n”,
“g”)
print(Str1[substr1])
Str1 = ("g", "r", "e", "a", "t", "l", "e", "a", “r”, “n”, “i”, “n”,
“g”)
print(Str1[0,14, 2])
85. What is the difference between Python Arrays and lists?
Python Arrays and List both are ordered collections of elements and are mutable, but
the difference lies in working with them
Arrays store heterogeneous data when imported from the array module, but arrays can
store homogeneous data imported from the numpy module. But lists can store
heterogeneous data, and to use lists, it doesn’t have to be imported from any module.
import array as a1
print (array1)
Or,
import numpy as a2
print(array2)
1. Arrays have to be declared before using it but lists need not be declared.
2. Numerical operations are easier to do on arrays as compared to lists.
86. What are Dict and List comprehensions?
List comprehensions provide a more compact and elegant way to create lists than
for-loops, and also a new list can be created from existing lists.
1 a for a in iterator
Or,
Ex:
print(list1)
print(list2)
Ex:
range() and xrange() are inbuilt functions in python used to generate integer numbers in
the specified range. The difference between the two can be understood if python
version 2.0 is used because the python version 3.0 xrange() function is re-implemented
as the range() function itself.
With respect to python 2.0, the difference between range and xrange function is as
follows:
Example:
for i in range(1,10,2):
print(i)
.py are the source code files in python that the python interpreter interprets.
.pyc are the compiled files that are bytecodes generated by the python compiler, but
.pyc files are only created for inbuilt modules/files
===================================================================
Pandas in Python
1) 𝐍𝐮𝐦𝐏𝐲 - Numerical Computation