Python ?
Python ?
1. What is Python?
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. After 30 years, Van Rossum stepped down as the leader of the
community in 2018.
Python interpreters are available for many operating systems. CPython, the
reference implementation of Python, is open-source software and has a
community-based development model, as do nearly all of its variant
implementations. The non-profit Python Software Foundation manages
Python and CPython.
2. Why Python?
2|Page
installed, it is a pretty straightforward process. The next step is to power up
an IDE and start coding in Python. If you wish to learn more about the
process, check out this Python Tutorial. Check out How to install python.
– Web Applications
We can use Python to develop web applications. It contains HTML and XML
libraries, JSON libraries, email processing libraries, request
libraries, beautiful soup libraries, Feedparser libraries, and other internet
protocols. Instagram uses Django, a Python web framework.
3|Page
– Desktop GUI Applications
The Graphical User Interface (GUI) is a user interface that allows for easy
interaction with any programme. Python contains the Tk GUI framework for
creating user interfaces.
– Console-based Application
Python has a number of free libraries and modules that help in the creation
of command-line applications. To read and write, the appropriate IO
libraries are used. It has capabilities for processing parameters and
generating console help text built-in. There are additional advanced
libraries that may be used to create standalone console applications.
– Software Development
4|Page
Putting machine learning algorithms into practice requires a lot of
arithmetic. Numpy, Pandas, Scipy, Scikit-learn, and other scientific and
numerical Python libraries are available. If you know how to use Python,
you’ll be able to import libraries on top of the code. A few prominent
machine library frameworks are listed below.
SciPy
Scikit learn
NumPy
Pandas
Matplotlib
– 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
HeeksCNC
AnyCAD
5|Page
RCAM
– Enterprise Applications
Python has a lot of libraries for working with pictures. The picture can be
altered to our specifications. OpenCV, Pillow, and SimpleITK are all image
processing libraries present in python. In this topic, we’ve covered a wide
range of applications in which Python plays a critical part in their
development. We’ll study more about Python principles in the upcoming
tutorial.
6|Page
Since it is an interpreted language it executes any code line by
line and throws an error if it finds something missing.
Python is free to use and has a large open-source community.
Python has a lot of support for libraries that provide numerous
functions for doing any task at hand.
One of the best features of Python is its portability: it can and
does run on any platform without having to change the
requirements.
Provides a lot of functionality in lesser lines of code compared to
other programming languages like Java, C++, etc.
6. What are the 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 language. Integers, floating-point
numbers, Booleans, and character strings are some of the most common
forms of literal. Python supports the following literals:
7|Page
Numeric Literals: These are unchangeable numbers that may be divided
into three types: integer, float, and complex.
Boolean Literals: True or False, which signify ‘1’ and ‘0,’ respectively, can be
assigned to them.
Special Literals: It’s used to categorize fields that have not been
generated. ‘None’ is the value that is used to represent it.
8|Page
9. How is Python an interpreted language?
An interpreter takes your code and executes (does) the actions you
provide, produces the variables you specify, and performs a lot of behind-
the-scenes work to ensure it works smoothly or warns you about issues.
9|Page
11. What is namespace in Python?
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.
10 | P a g e
A Python module is a collection of Python commands and definitions in a
single file. In a module, you may specify functions, classes, and variables. A
module can also include executable code. When code is organized into
modules, it is easier to understand and use. It also logically organizes the
code.
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:
11 | P a g e
Unit testing support that is incorporated
There’s a built-in development server as well as a rapid
debugger.
Restful request dispatch with a Unicode basis
The use of cookies is permitted.
Templating WSGI 1.0 compatible jinja2
Additionally, the flask gives you complete control over the
progress of your project.
HTTP request processing function
Flask is a lightweight and versatile web framework that can be
easily integrated with a few extensions.
You may use your favorite device to connect. The main API for
ORM Basic is well-designed and organized.
Extremely adaptable
In terms of manufacturing, the flask is easy to use.
12 | P a g e
aspires to include all of the batteries that a web application would require,
so programmers simply need to open the box and start working, bringing
in Django’s many components as they go.
Django includes an ORM by default, but Pyramid and Flask provide the
developer control over how (and whether) their data is stored. SQLAlchemy
is the most popular ORM for non-Django web apps, but there are lots of
alternative options, ranging from DynamoDB and MongoDB to simple local
persistence like LevelDB or regular SQLite. Pyramid is designed to work with
any sort of persistence layer, even those that have yet to be conceived.
1. Model
2. View
13 | P a g e
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.
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:
def harshit_fun():
y = 100
print (y)
harshit_func()
100
14 | P a g e
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)
def first_func():
y = 100
def nested_func1():
print(y)
nested_func1()
first_func()
15 | P a g e
20. List the common built-in data types in Python?
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:
Example:
Sets: Sets are basically collections of unique items where order is not
uniform.
Example:
set = {1,2,3}
16 | P a g e
Dictionary: A dictionary always stores values in key and value pairs where
each value can be accessed by its particular key.
Example:
Boolean: There are only two boolean values: True and False
The attributes of a class are also called variables. There are three access
modifiers in Python for variables, namely
class Mobile:
def price(self):
17 | P a g e
return m2
Sam_m = Mobile()
print(Sam_m.m1)
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
18 | P a g e
23. What is the difference between lists and tuples in Python?
List and tuple are data structures in 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 list is more convenient for actions like The items may be accessed using the
insertion and deletion. tuple data type.
19 | P a g e
24. How can you concatenate two tuples?
tup1 = (1,”a”,True)
tup2 = (4,5,6)
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.
Code:
tup1=(1,"a",True)
tup2=(4,5,6)
tup2+tup1
20 | P a g e
25. What are functions in Python?
Ans: 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.
26. How can you initialize a 5*5 numpy array with only zeroes?
import numpy as np
n1=np.zeros((5,5))
n1
Use np.zeros() 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.
21 | P a g e
12 Import pandas as pddf=p.read_csv(“mydata.csv”)
Code:
import pandas as pd
data=["1",2,"three",4.0]
series=pd.Series(data)
print(series)
print(type(series))
Code:
df = pd.DataFrame({'Vehicle':['Etios','Lamborghini','Apache200','Pulsar200'],
'Type':["car","car","motorcycle","motorcycle"]})
22 | P a g e
df
df.groupby('Type').count()
Code:
df=pd.DataFrame()
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"]
23 | P a g e
cars=["lamborghini","masserati","ferrari","hyundai","ford"]
d={"cars":cars,"bikes":bikes}
df=pd.DataFrame(d)
df
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.
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.
24 | P a g e
36. Give the below dataframe drop all rows having Nan.
df.dropna(inplace=True)
df
By using the head(5) function we can get the top five entries of a
dataframe. By default df.head() returns the top 5 rows. To get the top n
rows df.head(n) will be used.
By using the tail(5) function we can get the top five entries of a dataframe.
By default df.tail() returns the top 5 rows. To get the last n rows df.tail(n) will
be used.
Code:
import pandas as pd
bikes=["bajaj","tvs","herohonda","kawasaki","bmw"]
cars=["lamborghini","masserati","ferrari","hyundai","ford"]
d={"cars":cars,"bikes":bikes}
df=pd.DataFrame(d)
25 | P a g e
a=[10,20,30,40,50]
df.index=a
df.loc[10]
40. What are comments and how can you add comments in
Python?
1. Single-line comment
2. Multiple-line comment
Codes needed for adding a comment
“””Note
Note
Note”””—–multiline comment
Example
d={“a”:1,”b”:2}
26 | P a g e
42. What is the difference between a tuple and a dictionary?
43. Find out the mean, median and standard deviation of this
numpy array -> np.array([1,5,3,100,4,48])
import numpy as np
n1=np.array([10,20,30,40,50,60])
print(np.mean(n1))
print(np.median(n1))
print(np.std(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: string.lower()
ex:
o/p: greatlearning
27 | P a g e
46. How do you get a list of all the keys in a dictionary?
o/p: [1, 2, 3]
Syntax:
1 string_name.capitalize()
ex:
n = “greatlearning” print(n.capitalize())
o/p: Greatlearning
Syntax:
1 list_name.insert(index, element)
ex:
list = [ 0,1, 2, 3, 4, 5, 6, 7 ]
28 | P a g e
list.insert(6, 10)
o/p: [0,1,2,3,4,5,10,6,7]
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 it 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
29 | P a g e
52. 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.
def add(n):
print(list(res))
o/p: 30,50,70,90
30 | P a g e
56. 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.
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=copy.copy(obj)
31 | P a g e
61. What are modules and packages in Python?
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.
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.
32 | P a g e
66. 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 = text.split(“,”)
print(n)
33 | P a g e
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.
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__)
34 | P a g e
Ouput: Takes in a number n, returns the square of n.
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.
35 | P a g e
Code:
import pandas as pd
a=[1,2,3]
b=[2,3,5]
d={"col1":a,"col2":b}
df=pd.DataFrame(d)
df["Sum"]=df["col1"]+df["col2"]
df["Difference"]=df["col1"]-df["col2"]
df
Output:
74. What are the different functions that can be used by grouby
in pandas ?
Data is divided into groups based on categories and then the data in these
individual groups can be aggregated by the aforementioned functions.
36 | P a g e
75. How to delete a column or group of columns in pandas? Given
the below dataframe drop column “col1”.
d={"col1":[1,2,3],"col2":["A","B","C"]}
df=pd.DataFrame(d)
df=df.drop(["col1"],axis=1)
df
76. Given the following data frame drop rows having column
values as A.
Code:
d={"col1":[1,2,3],"col2":["A","B","C"]}
df=pd.DataFrame(d)
df.dropna(inplace=True)
df=df[df.col1!=1]
df
Code:
import pandas as pd
37 | P a g e
bikes=["bajaj","tvs","herohonda","kawasaki","bmw"]
cars=["lamborghini","masserati","ferrari","hyundai","ford"]
d={"cars":cars,"bikes":bikes}
df=pd.DataFrame(d)
a=[10,20,30,40,50]
df.index=a
df
print(sum)
vstack() is a function to align rows vertically. All rows must have the same
number of elements.
38 | P a g e
Code:
import numpy as np
n1=np.array([10,20,30,40,50])
n2=np.array([50,60,70,80,90])
print(np.vstack((n1,n2)))
print (str.strip())
o/p: greatlearning
39 | P a g e
82. What is pickling and unpickling?
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.
40 | P a g e
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
return func(a, b)
return inner
@smart_divide
print(a/b)
divide(1,0)
41 | P a g e
at compile time then it is called static typed language and when the type
check is done at run time, it’s called dynamically typed language.
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”)
42 | P a g e
print(Str1[substr1])
Str1 = ("g", "r", "e", "a", "t", "l", "e", "a", “r”, “n”, “i”, “n”, “g”)
print(Str1[0,14, 2])
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)
43 | P a g e
91. What is Scope Resolution in Python?
a. Local scope – The variable declared inside a loop, the function body is
accessible only within that function or loop.
b. Global scope – The variable is declared outside any other code at the
topmost level and is accessible everywhere.
The scope resolution for any variable is made in java in a particular order,
and that order is
Local Scope -> enclosing scope -> global scope -> built-in scope
1 a for a in iterator
Or,
44 | P a g e
list1 = [a for a in range(5)]
print(list1)
print(list2)
With respect to python 2.0, the difference between range and xrange
function is as follows:
for i in range(1,10,2):
45 | P a g e
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.
46 | P a g e