Top Python Interview Questions:

(1) What are Keywords in Python:

  • Python keywords are special reversed Words
  • Convey a special meaning to the compiler/ Interpreter.
  • Each keyword has a special meaning and a specific operation.
  • NEVER use it as a variable.
TrueFalseNoneandas
assetdefclasscontinuebreak
else finallyelifdefexcept
globalforiffromimport
raisetryorreturnpass
monlocalinnotisnonlocal

(2) What are Literals in Python?

Literals are the constants used in Python.

Sl.NoValue
1String Literals
2Numeric Literals
3Boolean Literals
4Special Literals

(3) What are Numerical Literals:

WIntLongFloatComplex
+ve and -veUnlimited IntegerReal numberIn the form of
Numbers(Integers With
No Fraction apart
Ex.100,234
Size followed by
upper or lowercase L.
Ex:2342435428
With both integer and fractional part
Ex-2133
a+bj,”a” forms the real part & b forms the imaginary part.
Ex-314

(4) What are Boolean Literals:

Can only have two values :

  • True
  • False

(5) What is Special Literal:

python has one special literal: None

Used to specify the field that has not been created.

(6) What is a Dictionary in Python? Also, create a dictionary where the key is “Trust_name: and there are 4 fruit names associated with it.

mydict= {“Orange”, “apple”, “grapes”, “guava’}

mydict. keys

mydict.values

(7) Create a class with the name”Human” assign a name and age to it and also get values from it.

Class Human {

name= None

age= None

def get_name(self):

print(“Enter Your Name”)

self.name=input()

def get_age(self):

print(“Enter Your Name”)

self.age=input()

def put_nam,e(self):

print(“your name is “, self. name)

def put_age(self)

print(“you age is”, self. age)

person1.get_name()

}

(7) What do you understand by __init__() method.

  • __init__is a special method in Python classes.
  • It is a constructor method for a class
  • __init__ is called whenever an object of the class is constructed.

class student:

__init__(self,name.,age,branch)

self.age =age

self.name=name

self.branch= branch

def print_student(self):

Print(“name”, self. name)

Print(“age”, self. age)

Print(“branch”, self. branch)

(8) What is inheritance?

Inheritance means that one class is acquiring property from another class.

In a family tree, traits such as color, hair, and poor eyesight are passed from generation to generation.

class Fruit:
   def __init__(self):
        Print("I am Fruit")

class citrus(fruit):
def __Init__(self):
super().__init__()
print("I am Citrus")

Lemon=citrus()

(9) What is Numpy and How Can You create a basic 1-D and 2-D array?

import numpy as np

a=np,array([1,2,3])

a

array([1,2,3])

b=np.array([1,2,3],[4,5,6])

b

array ([1,2,3],

[4,5,6])

(10) How can you initialize an array of 5*5 Which contains 0 values?

import numpy as np

np.zeros(5)

(11) Give the examples for creating a Dataframe from list and dictionary:

import pandas as pd

l1=[1.2.3.4.5]

data1=pd.Dataframe(l1)

data1

(12) From this iris dataset, extract only those records where”Sepal length” is greater than 5 and “Sepal. Width” is greater than 3.

Sepal LengthSepal WidthPetal. widthPetal.widthSpecies
5.13.51.40.2setosa
4.93.01.40.2setosa
4.73.21.30.2setosa
4.63.11.50.2setosa
5.03.61.40.2setosa

Ans: import pandas as pd

df=pd.read_csv(“iris.csv”)

iris.head()

df_new= ((df[“Sepal Length’]>5) & df(df[“Sepal Width”]>3)

df_new

(13) How can I get the number of NaN values present in each column of this “nhanes” Dataframe?

import pandas as pd

df=pd.read(“iris.csv”)

df.isna()

df.isna().sum()

(14) How to plot a simple Line Chart?

import numpy as np
from matplotlib import pyplot as plt
x=np,arage(0,10,1)
plt.xlabel("x-axis")
plt.ylabel("y-axis")
plt.plot(x,y)
(please practice yourself)

from matplotlib import pyplot as plt
data ={'apple":"50"."banana":20,"orange":"20"}
name= list(data.keys())
values=list(data.values())

(15) What do you underatnd by Module in Python
Moudles help in logically organizinng our python code.
You can randomize the items of the list using the shuffle() button.
from random import shuffle
x={"mary","had","a", "little","lamb"}
suffle(x)
x
["a","lamb","lady",";Little"]

(16) Write a program to get the length of the String"Opthamology" Without using len function.
a="opnasb"
const=0
for i in a:
   count=count+1
  print(count)


Some New Questions:

(1) What are the Key features of Python?

1. open -source 
2. Oop
3. Easy to learn 
4. Easy to intreper, making Debugging Easy]
5. Easily Intregrated with Oher languages like C++, Java and More. 


(2) What are Keywords In Python?

-Reserved words 
- Help Define Structure and Syntax
- 33 keywords 
Keywords : False, None, True, break, if , else , for, return, continue def


(3) What are Literals in Python?

Literas in Python to the Data that is variable or constant/

String Literals - Sequence of Characters
Numeric Literals - Integer, Float, complex Numbers 
Boolean Literals - Represents True or False
Special Literals - "None" is good Example. 

(4) How can you concoonate tow tuples?

Tup1 = (1,2,3,4,5)

tup2 = (4.5)

What does tup1 + tup 2 dp?
* Let's Look at practically.
print(tup1 + tup2)
(1,2,3,4,5,4,5)

print(tup2+tup1)



What are Functions in Python?

Function in Python refer thartbare organized, reusable pieces of code that perfroms single
and related events. 

Functions are Important to create better modularity fot apllications which reuuse high degree 
of coding. 

Python has a number of Built-in - functions like Print() and allows of user -defined 
functions as well. 


(6) How can You Inilliaze a 5* 5 Numpy array with only zeros. 

Numpy has brilian functions -Zeros() that does exactly this. 

N1=np.zeros(5)

Let's check output code practically. 


(7) What is panadas?

Pandas is open -source libray that has very rich set odf sata structures based operatio\ions. 

Pandas can dela with large variety of files and is one of the most imp tools to have grip on. 

It provides two fantastic data structures- Series and Dataframes?


(8) What are Dataframnes?


- Dataframes are mulltiple Datatypes preseent in pandas Library
- Provides Support for hetergeneous data/ 
Here is the how CSV file can be read using Pandas. 

df=pd.read_csv("mydata.scv")
Let's check it practically. 

import pandas as pd 
df =pd.read_csv ("matches.csv")

df.head()
df.taill()


(9) What is Pandas seriezs?

Series is one dimensional data structure  that suppoets data of almost data of almot any type. 
It supports multiple diff operations for single diomensional ata operation. 
Let us create A series practically check it out. 

import pandas as pd
series =["1","2","3","4","5"]
print(series) 
print(type(series))


(10) what is the Pandas GroupBy functions? 

GroupBy is a feature supported by pandas which is used to split and group an object. 

Like SQL, mySQL and Oracle groupby, it used to group data by classes and entities which can be further 
use for aggregation. 

Let's Understand Practically. 

df=pd.Dataframe ({"vehicle" : ["kia', "lamborgini", KTHRC930, "pulsar"], "Type": ["car. "car. "Bike", "Bike"])
print(df)
df.groupby("Type").count()


(11) How to Create a Dataframe from lists?

Tpo create Dataframe from lits, this is what is requierd. 
* An Empty Dataframe 

df=pd.Dataframe()
bikes=["Bajaj","TVS", "Monda", "Kawasaki" , "BMW"]
cars= ["Lamborgini","Masseriti", "ferrari", "Hyundai", "Ford"]

df["cars"] = cars 
df["bikes"] = bikes 
print(df)


12. how do you create Dataframme from Dictionary?

A disctionay can be directly passed as an argument to the Dataframe() function to create 
a Dataframe. 
It is very straight Foewrad. 

d={"cars":cars, "bikes":bikes}
df=pd.Dataframe(d)

print(df)

13. How to Combine Datafrme using Join function?

function1 = [1,2,3,4,5]
function2 = [3,4,5,6,7]

The stacking is done in Horizontal matter is join() function is used/ 

df=function1.innerjoin(function2)

Pandas supports left join Inner Join, right Join and Outer Join.


14. Which method works for verticl stacking for Dataframe?

The concat() method workss when the Dataframes have the same columns and can be used for 
concatation fof data having similar fields. 

It is used for vertical stacking of Dataframe into a Single Dataframe/ 



15. How to merge Dataframe in pandas?

Merging Depends on the types and fields of Different Dataframes being merged. 

if Data is Having Similar Fields data is merged along axis 0. 

if the fields are differebr, thet merged along axis =1 


16). Given Datafrme , how do you drop all rows having Nan?

The dropna() function pandas to help do just that. 

   Col1  col2
0  1.0    A

1  2.0    B

2  Nan    c

17) How to, acces and first five and Las five functions entries of Datafrme?

The head(5) tail(5) 



18) How to acces data from using value as Index? 

To fetach row from Dataframe given index 'x" we can use loc. 

Lets us see practically

a=[10.20.30,40]

df.index =a 

df.loc[10]



19) How do you add singkle -line and Multi line commenst? 

Single -line comments : it is used to denote single line comments// 

Multiline Comments : """" comments """ {triple Quotes are used across many lines}


20) What is the most memory efficient way to add elements to tuple? 

* Tuples are Imutable
* You cannot elements to existing Tuple. 
* A new one must be created if the values are to be changed. 

21) What is dictionary in Python? 

* A Python Dictionary is collection of items in a no particular order. 
* Dictionaries are written in Curly brackets with keys and Values. 
* This are optimized to retreive for know keys> 

Example : d = {"a": 1, "b" : 2}

22) Finc out the measures of central Tendancy for this Numpy arrat\y. 

np.array ([1.5.5.3,100,4.48])


There are really available functions in Numpy  that will help us with this. 

Function such as mean() median() std () are effective at solving this. 

import numpy as np: 

ni= np.array ([10,9,10,25,24])

print(np.mean())
print(np.median())
print(np.std)


(23) What is the Classifier? 

- A clasifier is used to predict the class of data poiont. 

- Classifier are speial Hypothesis that are used to assign class labels to any particular data
points. 

(24) How to yo convert string into lowecase using Pythoin?

All the Upper cases in a string can be converted into lowercase by using the method. 

String.lower()

Example : string : "GREATLEARNING" print(string.lower())


(25) How do you get list of all the keys in Dictionary? 

One of the ways we can get list of keys by using dict.keys()

This Method will retrusn all the available keys in dictionary. 

Let's check this out practically. 



(26) How can you capitalize the first letter of string? 

We can use Capitalize() function to capitalize in the first character of string. 

If the firest character is capuital then it returns the originakl String/ 

practical examples help concrate your understand on this, so lets' go. 


n="great learning"
print(n.capitalize())


(27)How can you insert an element ar given index in Python?

a =[1,2,3,4,5]

Python has a inbuilt function the insert() function. 

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

a.insert(0,10)

insert 10 and 0th indexx/

a


(28)  How will you remove a duplicate elemnts from list?

a=[1,2,3,4,4,5]
 
we can use ser


(29) What is recursion?

Recursion is a function calling itselt one of more times in body.

One imp thing to note is to terminate a recursion statement.

They would be a problem of an infinite loop if recursion is not terminated.



(30) 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 elements can be as needed/

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



(31) What is the use of bytes() function? 

The bytes() function retuens a simple bytes Object. 
It is used to convert object into bytes object, or create an empty bytes Objects of the 
specified size/ 


(32) What are the different Types of Operators in Python?

Arithmatic : +, - , * , / < %

Relational : < >  <= .= == !=

Asignemnt : = += -= /= *= %= 

Logical : and or not 

Others : Membership, Indetity, and Bitwise Operators 



(33) What is "With Statement" Used for in Python?

* This With statement in {ython is based on Exceptional handling/ 

A file can be opened and closed while executing a block of code, containing with 
statment without using close(). 



(34) What is map() function in Python? 

The map () functioon in Python is used for applying 
a function on lelements of a specified and iterable. 

Let's check this. 


del list 

def add_func(n):
   return n*3

num = (1,2,3,4,5,6)

result= map(add_func,num)

print(result)


(35) What is __init__ in Python? 

This __init__methodology is a reserved method in Python/ 

It is also known as constructor in the world of OOP. 

When an object is created class , the __init__methodology is called to access the class attributes. 


(36) what are the tools present to perform Static Analysis? 

The two static Analysis tools used to find bugs in python are Pychecker and Pylint/ 

Pycheker detects Bugs from the source code and warns about ist style and complexity. 

Pylint checks whether the module matches up to serr coding standards  or not/ 



(38) What is a Difference Between Tuple and Dictionary? 

One Major difference between a tuple and a dictionary nis mutable while a tuple is not. 

Meaning the content of a dictionary can be changed without changing its identity. 

This is not possible is a tuple. 



(39) What is pass in Python? 

Pass is statmenet which does nothing when executed. 

Why? Because it is null statement.

This statement is not ignored by the intrepreter, but the statement results in no operations. 


(40) How can object copied in Python? 

Not all objects can be copied in python, but most can. 

We can use"=" operator to copy an object to a variable. 

Example: var= copy.copy(ob)


(41) How can be number converted to string?

n=10

print(type(n))

new_n = str(n)

print(type(new_n))


(42) What are Modules and Packages in Python? 


Modules are the meaans to structure a program!

Each Python Program file is moduling, importing other attributes and objects/

The folder of a progarm is packages of Modules. 

important to note that a package can have modules or subfolders/ 



(43) What is Difference Between Numpy and Scipy?

Numpy Stands for Numerical Python While Scipy Stands for Scientific Applications. 

Numpy is basic library for defining arrys and simple mathematical problems. 

Scipy is used for more complex problems like numerical integration, optimization and Machine
learning and o\so on. 



(44) What does len() function do? 

The len() function used to determine the length of string, a list, an array and so on. 

let us check it out. 



(45) What does Split do? 

str = "Great learning"

print(len(str))



(46) Deefine Encapsulation in Python. 

* Encapsulation means the code and data together. 
* It is very important concept that is foundationakl to OOPS. 
* Example: A Python Class 




(47) What is the use of Type functions in Python? 

The Type () function is a built-in method which either returns the types of object.

It also returns a new type object  based on argument passed!


(48) What is the Split() function Used For?

The Split function is used to split a string into shorter string using Defined Separators. 

lettes =('A','B','C')
n= letters.split(",")
print(n)


(49) What is Docstring in Python? 

Python Docstringss are string Literals enclosed in Tripple Quotes that appear right after the
definition of a function, method, class or module. 

Gemerally, used to describe the functionality of a particular function, method, class or module. 

(50) What is the use of Lambda Function in Python?

Lambda Function serves as a nameless function that are needed for short periods of time. 

triple = lambda x : x * 3
print(triple(100))

(51) How do You find the factorial of a Number using recursion? 

Recursion is the concept where a function can call itself any number of times till 
a certain Condition is Met. 


The Condition is important to avoid infinite loops. 

Let's implement this!


def factorial(n): 
  if a ==1 : 
    return 1 

  else: 
     return (a* factorial (n-1))


(52) Can you denote the working of the bool() function with examples? 

 The Bool functions in Python returns either logical True or False. 

 It cannot Output anything else apart from the logical Operation.

 Let's Check it out. 

a ="hello"
b=15
c=0
sample_list=[]

print(bool(a))
print(bool(b))
print(bool(c))



Python Interview Questions Expericed users: 


(1) How to create a new Columns in pandas by using values from other columns?

* We can use columns based mathematical operations on a pandas Dataframe. 

* Pandas Columsn Containing Numeric values can be operated upon by operators. 

* Let us check this out practically!

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




(2) What are the Different Functions that can be used by groupby() in pandas?

The Gropuby() function 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 using the functions. 


(3) How to Select columns in pandas and add them to new DataFrame? What if There are two columns 
 with the same name? 

If df is Dataframe in Python, df.columns gives the list of all columns. 

We can the form new columns by selecting a paricular columns.


(4) What is Vstack() in Numpy? Give an Example: 

Vstack() means vertical Stacking. 

Numpy has a very popular functions called Vstack();

import numpy as np

n1=np.array([10,20,30,40,50])
n2=np.array([50,60,70,80,90])

print(np.vsatck ((n1,n2)))


(5) How is Python Code Interpreted? 

When a Python Program is written, It converts the source code written by the develoeper
into immediate Language first. 

This is then converted into machine language that needs to be executed. 

Debugging can be done modularly and on per-line basis/ 



(6) How to Remove spaces from string in Python?

Spaces can be removed from a string in Python by using Strip() or replace()
functions. 

Strip() functions is used to remove the leading and trailing whitespace while the 
replace() function remove all whitespaces.


Str1 = "great Learning"
print(Str1.replace(" ", ""))


(7) Explain the File Processing Modes that Python Supports?

There are four file processing models Python. 

(1) Read-only(r)
(2) Write-only(r)
(3) read-write(rw)
(4) append(a)

Binary flags - ("r", "w", "rw" and "a"}


(8) What is Pickling?

Pickling is the process of converting hierarchy into byte stream for storing it `
into database.

Pickling is also known as serialization.

Unpickling is the reverse of Pickling. 

The byte- stream is converted back into object hierarchy. 


(9) How is Memory Managed in Python? 

Memory Management in Python comprises of a private heap containing al objects and 
data structure. 

The heap is managed by the interpreter and the programmer does not have access at all. 

Morever, there is inbuilt garbage collector that recycles and free memory for the heap space. 


(10) 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 the 
collections, test automation,and independence of the test from the reporting framework.


(11) How Do You Delete a file in Python? 

Files can be deleted in python By using either of the following command. 

os.remove (filename) or os.unlink(filename)


(12) How Do you create an empty class in Python?

To create a empty class we can use pass command after the definition of the class object.

A pass is statment in python that does nothing. 

We have already understood this concept in a previous Question!



(13) What are the Python Decorators?

Decorators are functions that take another functions as argument to modify its behavior 
without changing the function itself. 

There are useful when we want dynamically increaese the functionality of a function 
without changing it. 

Let us understand this using an example!


(14) What does early binding?

Early Binding in a popular concept in OOPS that is used for many purposes. 

Majority, it is used to assign values during compile time to save a lots of time 
during the execution of the entire project. 



(15) What types of Inheritance is supported by Python but not by java?

Multiple Inheritance - This is supported in Python While this cannot be used in java. 

It is implemented very well in python to maximize the programming efficiency. 



Tricky Questions: 


(1) How do you implement a probabbility plot using Numpy and Matplotlib?

import numpy as np 
import pylab
import scipy.stats as stats
from matplotlib import pyplot as plt 

n1=np.random.normal(loc=0,scale=1m,size=1000)

np.percentile(n1,100)

n1= np.random.normal(loc=20, scale=1 , size= 100)

stats.probplot(n1,dist="norm", plot=pylab)

plt.show()



(2) Given the sample dictionary - How would you update the value of "Apple" from 
1o to 100?

fruits: {"Apple": 10, "Orange":20,"Banana": 30, "Guvava": 40}

fruits["Apple"] =30

fruits


(3) How do you find the common elements in the given two sets?

S1 = {1,2,3,4,5}

s2= {5,6,7,8,9}

s1.intersection{s2}



(4) Implement the logic to check if the number is palindrome or not!

#121-121

print(input("Enter Number: "))

temp = n


if (n == n.reverse()):
   print("palindrome Number")
else: 
   print("This is palindrome Number")




(5) Write a Program to prints the follwing patters, 

1

2  2

3  3  3

4   4  4  4

5   5   5   5  5  


Note: please do it Yourself.


(6) If you have dictionary like this -> d1={"k1":10,"k2":20,"k3":30} How would you incerement 
values of all the keys?

d1 = {"k1":10,"k2":20,"k3":30}

for i in d1.keys():
 d[i] = d[i] + 1;


(7) Denote the Usage of args and kwargs in Python

def func1 (*args,**kwargs):
   print(args)
   print(kwargs)

func1(1,"hello",name="sujit")



(8) How do You shallow Copy?

#firt-list = {1,2,3,4,5}
second_list=first_list

second_list.append(6)

print(first_list)
print(second_list)

[1,2,3,4,5,6]
[1,2,3,4,5,6]


(9) What will be the output of the following Piece of code?

a=[1,2,4,5,6,7,8,9]
a[-1:-4:1]

[9876]



(10) How Do You Print the ASCCI value of given a character?

value="a"

print("The ASCII value of "" + value + "" is ", ord(value))











    


























 












Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *