0% found this document useful (0 votes)
3 views42 pages

Understanding Python: Features & Applications

Uploaded by

shamak1836
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views42 pages

Understanding Python: Features & Applications

Uploaded by

shamak1836
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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.​

2. Why Python?

Python is a high-level, general-purpose programming language. Python is a


programming language that may be used to create desktop GUI apps, websites, and
online applications. As a high-level programming language, Python also allows you to
concentrate on the application’s essential functionality while handling routine
programming duties.

3. What are the applications of Python?​


Python is notable for its general-purpose character, which allows it to be used in
practically any software development sector.

– 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.

– Scientific and Numeric:

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.

Oddo is a Python-based all-in-one application that offers a wide range of business


applications.

Audio or Video-based Applications

Python is a versatile programming language that may be used to construct multimedia

3D CAD Applications

Engineering-related architecture is designed using CAD (Computer-aided design). It’s


used to create a three-dimensional visualization of a system component. The following
features in Python can be used to develop a 3D CAD application:

●​ Fandango (Popular)
●​ CAMVOX

4. What are the advantages of Python?

Python is a general-purpose dynamic programming language that is high-level and


interpreted. Its architectural framework prioritizes code readability and utilizes
indentation extensively.
●​ Adaptable, simple to read, learn, and write
●​ Data structures that are pretty easy to work on
●​ High-level language
●​ The language that is dynamically typed (No need to mention data type based on the
value assigned, it takes data type)
●​ Object-oriented programming language
●​ Interactive and transportable
●​ Ideal for prototypes since it allows you to add additional features with minimal code.
●​ Python is free to use and has a large open-source community.
●​ Provides a lot of functionality in lesser lines of code compared to other programming
languages like Java, C++, etc.

5. What are the key features of Python?

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:

●​ Python is easy to learn due to its clear syntax and readability


●​ Python is easy to interpret, making debugging easy
●​ Python is free and Open-source
●​ It can be used across different languages
●​ It is an object-oriented language that supports concepts of classes
●​ It can be easily integrated with other languages like C++, Java, and more

6. What do you mean by Python literals?

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.

●​ String literals: “halo” , ‘12345’


●​ Int literals: 0,1,2,-1,-2
●​ Long literals: 89675L
●​ Float literals: 3.14
●​ Complex literals: 12j
●​ Boolean literals: True or False
●​ Special literals: None
●​ Unicode literals: u”hello”
●​ List literals: [], [5, 6, 7]
●​ Tuple literals: (), (9,), (8, 9, 0)
●​ Dict literals: {}, {‘x’:1}
●​ Set literals: {8, 9, 10}

7. What type of language is Python?


Python is an interpreted, interactive, object-oriented programming language. Classes,
modules, exceptions, dynamic typing, and extremely high-level dynamic data types are
all present.

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?

Python Enhancement Proposal (PEP) is an acronym for Python Enhancement


Proposal, and there are numerous of them. A Python Enhancement Proposal (PEP) is a
document that explains new features suggested for Python and details elements of
Python for the community, such as design and style.

9. What is namespace in Python?

A namespace is essentially a technique for ensuring that all of the names in a


programme are distinct and may be used interchangeably. You may already be aware
that everything in Python is an object, including strings, lists, functions, and so on.
Another notable thing is that Python uses dictionaries to implement namespaces. A
name-to-object mapping exists, with the names serving as keys and the objects serving
as values. The same name can be used by many namespaces, each mapping it to a
distinct object. Here are a few namespace examples:

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.

10. What are Python modules?


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.

11. What are local variables and global variables in Python?

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.

[Link] what Flask is and its benefits?

Flask is an open-source web framework. Flask is a set of tools, frameworks, and


technologies for building online applications. A web page, a wiki, a huge web-based
calendar software, or a commercial website is used to build this web app. Flask is a
micro-framework, which means it doesn’t rely on other libraries too much.

Benefits:

There are several compelling reasons to utilize Flask as a web application framework.
Like-

●​ 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.
●​ Flask is a lightweight and versatile web framework that can be easily
integrated with a few extensions.
●​ In terms of manufacturing, the flask is easy to use.

13. Is Django better than Flask?

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.

14. Discuss Django architecture

Django has an MVC (Model-View-Controller) architecture, which is divided into three


parts:

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)

●​ Nested Function: This is also known as a function inside a function, as


stated in the example above in local scope variable y is not available outside
the function but within any function inside another function.

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.

16. List the common built-in data types in Python?

Given below are the most commonly used built-in datatypes :


Numbers: Consists of integers, floating-point numbers, and complex numbers.

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:

list = [100, “Great learning”, 30]

Tuples: This too is an ordered sequence of elements but unlike lists tuples are
immutable meaning it cannot be changed once declared.

Example:

tup_2 = (100, “Great Learning”, 20)

String: This is called the sequence of characters declared within single or double
quotes.

Example:

“Hi, I work at great learning”

‘Hi, I work at great learning’

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:

[12] harshit = {1:’video_games’, 2:’sports’, 3:’content’}


Boolean: There are only two boolean values: True and False

17. What are global, protected, and private attributes in Python?

The attributes of a class are also called variables. There are three access modifiers in
Python for variables, namely

a. public – The variables declared as public are accessible everywhere, inside or


outside the class.

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.

Attributes are also classified as:

– 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:

m1 = "Samsung Mobiles" //Global attributes

def price(self):

m2 = "Costly mobiles" //Local attributes

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:

False class finally is return

None continue for lambda try

True def from nonlocal while

and del global not with

as elif if or yield

assert else import pass

break except

19. What is the difference between lists and tuples in Python?

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

Lists are mutable. Tuples are immutable.

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.

Lists take up more memory. When compared to a list, a tuple uses


less memory.

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

Syntax: Syntax: tup_2 = (100, “Great


Learning”, 20)
list = [100, “Great Learning”, 30]
20. How can you concatenate two tuples?

Let’s say we have two tuples like this ->

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.

Now, let’s go ahead and concatenate tuple2 with tuple1:

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.

21. What are functions in Python?

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?

We will be using the .zeros() method.

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.

23. What are Pandas?

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.

24. What are data frames?

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).

Reading files into pandas:-

12 Import pandas as pddf=p.read_csv(“[Link]”)


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.

Creating a series from data:

Code:

import pandas as pd

data=["1",2,"three",4.0]

series=[Link](data)

print(series)

print(type(series))

26. What do you understand about pandas group by?

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

To perform group by type the following code:


[Link]('Type').count()

27. How to create a dataframe from lists?

To create a dataframe from lists,

1) create an empty dataframe​


2) add lists as individuals columns to the list

Code:

df=[Link]()

bikes=["bajaj","tvs","herohonda","kawasaki","bmw"]

cars=["lamborghini","masserati","ferrari","hyundai","ford"]

df["cars"]=cars

df["bikes"]=bikes

df

28. How to create a data frame from a dictionary?

A dictionary can be directly passed as an argument to the DataFrame() function to


create the data frame.

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

29. How to combine dataframes in pandas?

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.

30. What kind of joins does pandas offer?

Pandas have a left join, inner join, right join, and outer join.

31. How to merge dataframes in pandas?

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.

The dropna function can be used to do that.

[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.

34. How to access the last five entries of a dataframe?

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?

To fetch a row from a dataframe given index x, we can use loc.

[Link][10] where 10 is the value of the 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?

Comments in Python refer to a piece of text intended for information. It is especially


relevant when more than one person works on a set of codes. It can be used to analyse
code, leave feedback, and debug it. There are two types of comments which includes:

1.​ Single-line comment


2.​ Multiple-line comment

Codes needed for adding a comment

#Note –single line comment

“””Note

Note

Note”””—–multiline comment

37. What is a dictionary in Python? Give an example.

A Python dictionary is a collection of items in no particular order. Python dictionaries are


written in curly brackets with keys and values. Dictionaries are optimised to retrieve
values for known keys.

Example

d={“a”:1,”b”:2}

38. What is the difference between a tuple and a dictionary?

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))

40. What is a classifier?

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.

41. In Python how do you convert a string into lowercase?

All the upper cases in a string can be converted into lowercase by using the method:
[Link]()

ex:

string = ‘GREATLEARNING’ print([Link]())

42. How do you get a list of all the keys in a dictionary?

One of the ways we can get a list of keys is by using: [Link]()

This method returns all the available keys in the dictionary.

dict = {1:a, 2:b, 3:c} [Link]()


43. How can you capitalize the first letter of a string?

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]())

44. How can you insert an element at a given index in Python?

Python has an inbuilt function called the insert() function.

It can be used used to insert an element at a given index.

Syntax:

1 list_name.insert(index, element)

ex:

list = [ 0,1, 2, 3, 4, 5, 6, 7 ]

#insert 10 at 6th index

[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]

list1 = list(set(list0)) print (“The list without duplicates : ” +


str(list1))

o/p: The list without duplicates : [2, 4, 6, 7]

46. What is recursion?

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.

47. Explain Python List Comprehension.

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:

list = [i for i in range(1000)]

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.

49. What are the different types of operators in Python?

Python has the following basic operators:

Arithmetic (Addition(+), Substraction(-), Multiplication(*), Division(/), Modulus(%) ),


Relational (<, >, <=, >=, ==, !=, ),​
Assignment (=. +=, -=, /=, *=, %= ),​
Logical (and, or not ), Membership, Identity, and Bitwise Operators

50. What is the ‘with statement’?

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.

51. What is a map() function in Python?

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):

return n + n number= (15, 25, 35, 45)

res= map(add, num)

print(list(res))

o/p: 30,50,70,90
52. What is __init__ in Python?

_init_ methodology is a reserved method in Python aka constructor in OOP. When an


object is created from a class and _init_ methodology is called to access the class
attributes.

Also Read: Python __init__- An Overview

53. What are the tools present to perform static analysis?

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.

54. What is pass in Python?

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.

55. How can an object be copied in Python?

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)

56. How can a number be converted to a string?

The inbuilt function str() can be used to convert a number to a string.


57. 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.

58. What is the object() function in Python?

In Python, the object() function returns an empty object. New properties or methods
cannot be added to this object.

59. What is the difference between NumPy and SciPy?

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.

60. What does len() do?

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

61. Define encapsulation in Python?

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

63. What is the split() function used for?

Split function is used to split a string into shorter strings using defined separators.

letters= ('' A, B, C”)

n = [Link](“,”)

print(n)

o/p: [‘A’, ‘B’, ‘C’ ]

64. What are the built-in types does python provide?

Python has following built-in data types:

Numbers: Python identifies three types of numbers:

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.

Set: An unordered collection of unique objects enclosed in curly brackets

Frozen set: They are like a set but immutable, which means we cannot modify their
values once they are created.

Dictionary: A dictionary object is unordered in which there is a key associated with


each value and we can access each value through its key. A collection of such pairs is
enclosed in curly brackets. For example {‘First Name’: ’Tom’, ’last name’: ’Hardy’} Note
that Number values, strings, and tuples are immutable while List or Dictionary objects
are mutable.

65. What is docstring in Python?

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):

'''Takes in a number n, returns the square of n'''

return n**2

print(square.__doc__)
Ouput: Takes in a number n, returns the square of n.

66. How to Reverse a String in Python?

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]

67. How to check the Python Version in CMD?

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.

68. Is Python case sensitive when dealing with identifiers?

Yes. Python is case-sensitive when dealing with identifiers. It is a case-sensitive


language. Thus, “variable” and “Variable” would not be the same.

================================================================​
Intermediate level

===============================================================

69. How to create a new column in pandas by using values from other
columns?

We can perform column based mathematical operations on a pandas dataframe.


Pandas columns containing numeric values can be operated upon by operators.

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.

71. How to delete a column or group of columns in pandas? Given the


below dataframe drop column “col1”.

drop() function can be used to delete the columns from a dataframe.

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

73. What is Reindexing in pandas?

Reindexing is the process of re-assigning the index of a pandas dataframe.

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.

from functools import reduce

sequences = [5, 8, 10, 20, 50, 100]

sum = reduce (lambda x, y: x+y, sequences)

print(sum)

75. What is vstack() in numpy? Give an example.

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)))

76. How to remove spaces from a string in Python?

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:

[Link](” “,””) ex1: str1= “great learning”

print ([Link]())

o/p: great learning

ex2: str2=”great learning”

print ([Link](” “,””))

o/p: greatlearning

77. What is pickling and unpickling?

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.

78. How is memory managed in Python?

This is one of the most commonly asked python interview questions

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.

79. What is unittest in Python?

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.

80. How do you delete a file in Python?

Files can be deleted in Python by using the command [Link] (filename) or


[Link](filename)

81. How do you create an empty class in Python?

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.

82. What are Python decorators?

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):

def inner(a, b):

print("Dividing", a, "by", b)

if b == 0:

print("Make sure Denominator is not zero")


return

return func(a, b)

return inner

@smart_divide

def divide(a, b):

print(a/b)

divide(1,0)

Here smart_divide is a decorator function that is used to add functionality to simple


divide function.

83. What is a dynamically typed language?

Type checking is an important part of any programming language which is about


ensuring minimum type errors. The type defined for variables are checked either at
compile-time or run-time. When the type-check is done 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.

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.

84. What is slicing in Python?

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])

//same code can be written in the following way also

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”)

substr1 = slice(0, 14, 2)

print(Str1[substr1])

//same code can be written in the following way also

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

array1 = [Link]('i', [1 , 2 ,5] )

print (array1)

Or,

import numpy as a2

array2 = [Link]([5, 6, 9, 2])

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.

The syntax used is as follows:

1 a for a in iterator

Or,

1 a for a in iterator if condition

Ex:

list1 = [a for a in range(5)]

print(list1)

list2 = [a for a in range(5) if a < 3]

print(list2)

Dictionary comprehensions provide a more compact and elegant way to create a


dictionary, and also, a new dictionary can be created from existing dictionaries.

The syntax used is:

1 {key: expression for an item in iterator}

Ex:

dict([(i, i*2) for i in range(5)])


87. What is the difference between xrange and range in Python?

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:

1.​ range() takes more memory comparatively


2.​ xrange(), execution speed is faster comparatively
3.​ range () returns a list of integers and xrange() returns a generator object.

Example:

for i in range(1,10,2):

print(i)

88. What is the difference between .py and .pyc files?

.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

2) 𝐏𝐚𝐧𝐝𝐚𝐬 - Data Manipulation & Analysis

3) 𝐌𝐚𝐭𝐩𝐥𝐨𝐭𝐥𝐢𝐛- Plotting & Visualization

4) 𝐒𝐞𝐚𝐛𝐨𝐫𝐧- Statistical Data Visualization

5) 𝐏𝐥𝐨𝐭𝐥𝐲 - For 3D visualization

6) 𝐒𝐭𝐚𝐭𝐬𝐌𝐨𝐝𝐞𝐥𝐬 - Statistical Modelling, Testing & Analysis

7) 𝐒𝐜𝐢𝐤𝐢𝐭-𝐋𝐞𝐚𝐫𝐧 - Machine Learning & Data Mining

●​ The process of cleaning messy data is known as data munging or


data wrangling
●​ Data frame: Data frame is the main object in the [Link] is
used to represent the data in the form of rows and
columns(tabular or excel spreadsheet like data)

You might also like