Nothing Special   »   [go: up one dir, main page]

Phyton

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 11

1. 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 which supports concepts of classes
It can be easily integrated with other languages like C++, Java and more
2. What are Keywords in Python?
Keywords in Python are reserved words which are used as identifiers, function name
or variable name. 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

3. What are Literals in Python and explain about different Literals?


Literals in Python refer to the data that is given in a variable or constant.
Python has various kinds of literals including:

String Literals: It is a sequence of characters enclosed in codes. There can be


single, double and triple strings based on the number of quotes used. Character
literals are single characters surrounded by single or double-quotes.
Numeric Literals: These are unchangeable kind and belong to three different types –
integer, float and complex.
Boolean Literals: They can have either of the two values- True or False which
represents ‘1’ and ‘0’ respectively.
Special Literals: Special literals are sued to classify fields that are not
created. It is represented by the value ‘none’.
Python Interview Questions PDF
4. How can you concatenate two tuples?
Solution ->

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
Output

All you have to do is, use the ‘+’ operator between the two tuples and you’ll get
the concatenated result.

Similarly, let’s concatenate tuple1 with tuple2:

Code

tup1=(1,"a",True)
tup2=(4,5,6)
tup2+tup1
Output

5. What are functions in Python?


Ans: Functions in Python refer to blocks that have organised, and reusable codes to
perform single, and related events. Functions are important to create better
modularity for applications which reuse high degree of coding. Python has a number
of built-in functions like print(). However, it also allows you to create user-
defined functions.

6. How to Install Python?


To Install Python, first go to Anaconda.org and click on “Download Anaconda”. Here,
you can download the latest version of Python. After Python is 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.

7. What is Python Used For?


Python is one of the most popular programming languages in the world today. Whether
you’re browsing through Google, scrolling through Instagram, watching videos on
YouTube, or listening to music on Spotify, all of these applications make use of
Python for their key programming requirements. Python is used across various
platforms, applications, and services such as web development.

8. How can you initialize a 5*5 numpy array with only zeroes?
Solution ->

We will be using the .zeros() method

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.

This will be the output:

9. What is Pandas?
Pandas is an open source python library which has a very rich set of data
structures for data based operations. Pandas with it’s cool features fits 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 is one of the most
important tools to have a grip on.
10. What are dataframes?
A pandas dataframe is a data structure in pandas which is mutable. Pandas has
support for heterogeneous data which is arranged across two axes.( rows and
columns).

Reading files into pandas:-

1
2
Import pandas as pd
df=p.read_csv(“mydata.csv”)
Here df is a pandas data frame. read_csv() is used to read a comma delimited file
as a dataframe in pandas.

11. What is a Pandas Series?


Series is a one dimensional pandas data structure which 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=pd.Series(data)
print(series)
print(type(series))
Output

12. What is pandas groupby?


A pandas groupby is a feature supported by pandas which is used to split and group
an object. Like the sql/mysql/oracle groupby it used to group data by classes,
entities which can be further used for aggregation. A dataframe can be grouped by
one or more columns.

Code

df = pd.DataFrame({'Vehicle':['Etios','Lamborghini','Apache200','Pulsar200'],
'Type':["car","car","motorcycle","motorcycle"]})
df
Output

To perform groupby type the following code:

df.groupby('Type').count()
Output

13. 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=pd.DataFrame()
bikes=["bajaj","tvs","herohonda","kawasaki","bmw"]
cars=["lamborghini","masserati","ferrari","hyundai","ford"]
df["cars"]=cars
df["bikes"]=bikes
df
Output

14. How to create 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=pd.DataFrame(d)
df
Output

15. 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 dataframes 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 dataframes. 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.

16. What kind of joins does pandas offer?


Pandas has a left join, inner join, right join and an outer join.

17. How to merge dataframes in pandas?


Merging depends on the type and fields of different dataframes being merged. If
data is having similar fields data is merged along axis 0 else they are merged
along axis 1.

18. Give the below dataframe drop all rows having Nan.

The dropna function can be used to do that.

df.dropna(inplace=True)
df
Output
19. 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 df.head() returns the top 5 rows. To get the top n rows df.head(n) will be
used.

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


By using 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.

21. How to fetch a data entry from a pandas dataframe using a given value in index?
To fetch a row from dataframe given index x, we can use loc.

Df.loc[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=pd.DataFrame(d)
a=[10,20,30,40,50]
df.index=a
df.loc[10]
Output

22. 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:

Single-line comment
Multiple-line comment
Codes needed for adding comment

#Note –single line comment


“””Note
Note
Note”””—–multiline comment

23. What is the difference between list and tuples in Python?


Lists are mutable, but tuples are immutable.

24. What is 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 value for known keys.

Example

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

25. 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))
26. 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
points. 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.

27. 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: string.lower()

ex: string = ‘GREATLEARNING’ print(string.lower())


o/p: greatlearning

28. 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: dict.keys()
This method returns all the available keys in the dictionary. dict = {1:a, 2:b,
3:c} dict.keys()
o/p: [1, 2, 3]

29. 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 capital then it returns the original string.

Syntax: string_name.capitalize() ex: n = “greatlearning” print(n.capitalize())


o/p: Greatlearning

30. 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: list_name.insert(index, element)
ex: list = [ 0,1, 2, 3, 4, 5, 6, 7 ]
#insert 10 at 6th index
list.insert(6, 10)
o/p: [0,1,2,3,4,5,10,6,7]

31. 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]

32. What is recursion?


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.

33. 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 a for clause, enclosed in brackets.
for ex: list = [i for i in range(1000)]
print list

34. 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 object of the specified size.

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

36. What is the ‘with statement’?


“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 more easy to read.

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

38. 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_ methodolgy is called to acess the class
attributes.

39. What are the tools present to perform statics analysis?


The two static analysis tool 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.

40. What is the difference between tuple and dictionary?


One major difference between a tuple and a dictionary is that dictionary is mutable
while a tuple is not. Meaning the content of a dictionary can be changed without
changing it’s identity, but in tuple that’s not possible.

41. What is pass in Python?


Pass is a statentemen which 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.

42. How can an object be copied in Python?


Not all objects can be copied in Python, but most can. We ca use the “=” operator
to copy an obect to a variable.

ex: var=copy.copy(obj)

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


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

44. What are module and package 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.

45. What is object() function in Python?


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

46. 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 mathematica problems, while
SciPy is used for more complex problems like numerical integration and optimization
and machine learning and so on.

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

48. Define encapsulation in Python?


Encapsulation means binding the code and the data together. A Python class for
example.

49. What is the type () in Python?


type() is a built-in method which either returns the type of the object or returns
a new type object based on the arguments passed.

ex: a = 100
type(a)

o/p: int

50. What is split() function used for?


Split fuction is used to split a string into shorter string using defined
seperatos. letters = (” A, B, C”)
n = text.split(“,”)
print(n)

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

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


Ans. Python has following built-in data types:

Numbers: Python identifies three types of numbers:

Integer: All positive and negative numbers without a fractional part


Float: Any real number with floating-point representation
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 which 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 tuple are immutable while as
List or Dictionary object are mutable.

52. What is docstring in Python?


Ans. 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.
53. 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]
Learn more: How To Reverse a String In Python

54. How to check 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.

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

Python Interview Questions for Experienced Professionals


1. 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=pd.DataFrame(d)
df["Sum"]=df["col1"]+df["col2"]
df["Difference"]=df["col1"]-df["col2"]
df
Output

pandas
2. What are the different functions that can be used by grouby 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.

3. How to select columns in pandas and add them to a new dataframe? What if there
are two columns with the same name?
If df is dataframe in pandas df.columns gives the list of all columns. We can then
form new columns by selecting columns.

If there are two columns with the same name then both columns get copied to the new
dataframe.

Code

print(d_new.columns)
d=d_new[["col1"]]
d
Output

output
4. 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=pd.DataFrame(d)
df=df.drop(["col1"],axis=1)
df
Output

5. 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
Output

6. Given the below dataset find the highest paid player in each college in each
team.

df.groupby(["Team","College"])["Salary"].max()

7. Given the above dataset find the min max and average salary of a player
collegewise and teamwise.
Code
df.groupby(["Team","College"])["Salary"].max.agg([('max','max'),('min','min'),
('count','count'),('avg','min')])
Output

8. 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=pd.DataFrame(d)
a=[10,20,30,40,50]
df.index=a
df
Output

You might also like