Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
33 views

Python Most Asked Interview Questions?

Python has several basic data types including integers, floats, strings, booleans, lists, and dictionaries. Objects in Python are implemented through classes and instances. Key concepts of OOP like encapsulation, inheritance, polymorphism and abstraction are supported. Strings can be manipulated using methods like upper(), split(), and in. Control flow is implemented using statements like if/else and loops. Functions allow modularization and returning values. Other data types include sets, tuples, and lambda functions. List comprehensions provide a concise way to create lists.

Uploaded by

Sumit Sutar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

Python Most Asked Interview Questions?

Python has several basic data types including integers, floats, strings, booleans, lists, and dictionaries. Objects in Python are implemented through classes and instances. Key concepts of OOP like encapsulation, inheritance, polymorphism and abstraction are supported. Strings can be manipulated using methods like upper(), split(), and in. Control flow is implemented using statements like if/else and loops. Functions allow modularization and returning values. Other data types include sets, tuples, and lambda functions. List comprehensions provide a concise way to create lists.

Uploaded by

Sumit Sutar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Python

Interview Questions
 Basic data types in Python:

Q.1 What are the basic data types in Python?

Ans: The basic data types in Python are;

9 Integer: represents whole numbers.E

9 Float: represents decimal numbers.E

9 String: represents a sequence of characters.E

9 Boolean: represents either True or False.E

9 List: represents an ordered collection of

elements.

Q.2 How do you convert a string to an integer in

Python?

Ans:
You can use the int() function to convert a string

to an integer. For example:

num_str = "10"


num_int = int(num_str)

1
Q.3 How do you check the data type of a variable in
Python?
Ans: You can use the ‘type()’ function to check the
data type of a variable. For example:

num = 10

print(type(num)) # Output: <class 'int'>

Q.4 What is the difference between a list and a tuple in


Python?
Ans: A list is mutable, which means you can modify its
elements, while a tuple is immutable, meaning its
elements cannot be changed after creation.

Q.5 How do you create an empty dictionary in Python?


Ans: You can create an empty dictionary using either the
curly braces {} or the dict() function. For
example:

empty_dict = {}

empty_dict = dict()

2
 OOPS concept in Python:
Q.1 What is OOPS and how is it implemented in Python?
Ans: Object-Oriented Programming (OOPS) is a
programming paradigm that uses objects to
represent real-world entities. In Python, OOPS is
implemented through classes and objects. Classes
are blueprints for creating objects, and objects are
instances of a class.
Q.2 What are the four principles of OOPS?
Ans: The four principles of OOPS are:z
‚ Encapsulation: bundling of data and methods that
operate on that data within a single unit (class).z
‚ Inheritance: ability of a class to inherit properties
and methods from its parent class.z
‚ Polymorphism: ability of an object to take on
different forms or behaviors based on the context.z
‚ Abstraction: representing essential features and
hiding unnecessary details to simplify the
complexity.

3
Q.3 What is method overloading in Python?
Ans: Method overloading in Python refers to defining
multiple methods with the same name but different
parameters within a class. However, Python does not
support method overloading by default as it does in
languages like Java. In Python, you can achieve a
similar effect by using default arguments or using
variable-length arguments.

Q.4 What is method overriding in Python?


Ans: Method overriding in Python refers to defining a
method in a child class that already exists in its
parent class with the same name and signature. The
method in the child class overrides the method in the
parent class, providing a different implementation.

Q.5 What is the difference between a class method and


an instance method in Python?
Ans: A class method is a method bound to the class and
not the instance of the class. It is defined using the
@classmethod decorator and can access only class-
level variables. On the other hand, an instance
method is bound to the instance of the class and can
access both instance and class-level variables.

4
 String handling functions:
Q.1 How do you concatenate two strings in Python?
Ans: You can concatenate two strings using the +
operator. For example:

str1 = "Hello"

str2 = "World"

result = str1 + str2 # Output: "HelloWorld"

Q.2 How do you find the length of a string in Python?


Ans: You can use the len() function to find the length of
a string. For example:

str1 = "Hello World"



length = len(str1) # Output: 11

Q.3 How do you convert a string to uppercase in


Python?
Ans: You can use the upper() method to convert a string
to uppercase. For example:

str1 = "hello"

uppercase_str = str1.upper() # Output: "HELLO"

5
Q.4 How do you split a string into a list of substrings in
Python?
Ans: You can use the split() method to split a string into a
list of substrings based on a delimiter. For example:

str1 = "Hello,World"

substrings = str1.split(",")

# Output: ["Hello", "World"]

Q.5 How do you check if a string contains a specific


substring in Python?
Ans: You can use the in keyword to check if a substring is
present in a string. For example:

str1 = "Hello World"



is_present = "World" in str1 # Output: True

6
 Control statements, functions
in Python:
Q.1 What are control statements in Python?
Ans: Control statements are used to control the flow of
execution in a program. Common control statements
in Python include if-else, for loops, while loops, and
break/continue statements.

Q.2 How do you write an if-else statement in Python?


Ans: An if-else statement in Python is written using the
following syntax:

if condition:

# Code block executed if the condition is
True

else:

# Code block executed if the condition is
False

7
Q.3 How do you define a function in Python?
Ans: A function in Python is defined using the def
keyword. For example:

def greet():

print("Hello, world!")

Q.4 How do you pass arguments to a function in


Python?
Ans: You can pass arguments to a function by including
them inside the parentheses when defining the
function. For example:

def greet(name):

print("Hello, " + name + "!")

Q.5 How do you return a value from a function in


Python?
Ans: You can use the return keyword to return a value
from a function. For example:

def add(a, b):



return a + b

8
 Special data types in Python:

Q.1 What is a set in Python?

Ans: A set in Python is an unordered collection of unique

elements. It is defined using curly braces {} or the

set() constructor. For example:

my_set = {1, 2, 3} # Output: {1, 2, 3}

Q.2 What is a dictionary in Python?

Ans: A dictionary in Python is an unordered collection of

key-value pairs. It is defined using curly braces {} or

the dict() constructor. For example:

my_dict = {"name": "John", "age": 25}

# Output: {"name": "John", "age": 25}

Q.3 How do you access values in a dictionary in

Python?

Ans: You can access values in a dictionary by using the

corresponding key. For example:

my_dict = {"name": "John", "age": 25}


print(my_dict["name"]) # Output: "John"

9
Q.4 What is a tuple in Python?
Ans: A tuple in Python is an ordered and immutable
collection of elements. It is defined using parentheses
() or the tuple() constructor. For example:

my_tuple = (1, 2, 3) # Output: (1, 2, 3)

Q.5 How do you swap the values of two variables in


Python?
Ans: You can swap the values of two variables using a
temporary variable or simultaneous assignment. For
example:

a = 5

b = 10

a, b = b, a

print(a, b) # Output: 10, 5

10
Lambda functions, list

comprehension:

Q.1 What is a lambda function in Python?

Ans: A lambda function is an anonymous function defined

using the lambda keyword. It is typically used for

short, one-line functions. For example:

square = lambda x: x**2



print(square(3)) # Output: 9

Q.2 What is list comprehension in Python?

Ans: List comprehension is a concise way to create lists in

Python based on existing lists or other iterables. It

combines the creation of a new list with a loop and

optional conditional statements. For example:

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



squared_numbers = [x**2 for x in numbers]

print(squared_numbers) # Output: [1, 4, 9, 16,
25]

11
Q.3 How do you filter elements in a list using list
comprehension?
Ans: You can filter elements in a list using list
comprehension by adding a conditional statement.
For example, to filter even numbers:

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



even_numbers = [x for x in numbers if x % 2 ==
0]

print(even_numbers) # Output: [2, 4]

Q.4 Can you have multiple if conditions in list


comprehension?
Ans: Yes, you can have multiple if conditions in list
comprehension by chaining them using the and or or
operators. For example:

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



filtered_numbers = [x for x in numbers if x % 2
== 0 and x > 2]

print(filtered_numbers) # Output: [4]

12
Q.5 How do you create a dictionary using list
comprehension in Python?
Ans: You can create a dictionary using list comprehension
by specifying key-value pairs within curly braces {}.
For example:

keys = ['a', 'b', 'c']



values = [1, 2, 3]

my_dict = {k: v for k, v in zip(keys, values)}

print(my_dict) # Output: {'a': 1, 'b': 2, 'c':
3}

13
 Libraries used for data science:

Pandas, NumPy, Seaborn,

Matplotlib

Q.1 What is Pandas in Python and how is it used in data

science?

Ans: Pandas is a powerful library in Python used for data

manipulation and analysis. It provides data structures

such as DataFrames and Series, and functions for

reading, writing, and manipulating data. Pandas is

widely used for tasks like data cleaning,

transformation, and exploration in data science.

Q.2 What is NumPy in Python and how is it used in data

science?

Ans: NumPy is a fundamental library in Python used for

numerical computing. It provides efficient data

structures for handling multi-dimensional arrays and a

wide range of mathematical functions. NumPy is

extensively used in tasks like numerical operations,

linear algebra, and random number generation in data

science.

14
Q.3 What is Seaborn in Python and how is it used in
data science?
Ans: Seaborn is a Python library built on top of Matplotlib
that provides a high-level interface for creating
informative and attractive statistical graphics. It
simplifies the process of creating visualizations such
as scatter plots, bar plots, box plots, and heatmaps.
Seaborn is commonly used for data visualization and
exploration in data science.

Q.4 What is Matplotlib in Python and how is it used in


data science?
Ans: Matplotlib is a widely-used plotting library in Python
that provides a flexible and comprehensive set of
tools for creating various types of plots and
visualizations. It allows you to create line plots,
scatter plots, histograms, bar plots, and more.
Matplotlib is often used for data visualization and
presentation in data science.

15
Q.5 How do you create a scatter plot using Seaborn?
Ans: You can create a scatter plot using Seaborn's
scatterplot() function, specifying the x and y
variables from your dataset. For example:

import seaborn as sns



import pandas as pd



df = pd.read_csv('data.csv')

sns.scatterplot(x='x_column', y='y_column',
data=df)

16
 Types of plots in Seaborn and
Matplotlib and their uses:
Q.1 What are some commonly used plots in Seaborn
and Matplotlib?
Ans: Some commonly used plots in Seaborn and Matplotlib
includeQ
P Line plot: shows the trend of a variable over time6
P Scatter plot: displays the relationship between
two variables6
P Bar plot: compares categories or groups using
rectangular bars6
P Histogram: visualizes the distribution of a
continuous variable6
P Box plot: represents the distribution of a variable
and displays outliers6
P Heatmap: shows the correlation or relationship
between variables using colors6
P Violin plot: combines a box plot and a kernel
density plot to represent the distribution of a
variable.

17
Q.2 How do you create a box plot using Matplotlib?
Ans: You can create a box plot using Matplotlib's
boxplot() function, providing the data and any
additional parameters. For example:

import matplotlib.pyplot as plt



import pandas as pd



df = pd.read_csv('data.csv')

plt.boxplot(df['column'])

Q.3 How do you create a histogram using Seaborn?


Ans: You can create a histogram using Seaborn's
distplot() function, specifying the variable and
any additional parameters. For example:

import seaborn as sns



import pandas as pd



df = pd.read_csv('data.csv')

sns.distplot(df['column'])

18
Q.4 How do you create a bar plot using Matplotlib?
Ans: You can create a bar plot using Matplotlib's bar() or
barh() functions, providing the data and any
additional parameters. For example:

import matplotlib.pyplot as plt



import pandas as pd



df = pd.read_csv('data.csv')

plt.bar(df['x_column'], df['y_column'])

Q.5 How do you create a heatmap using Seaborn?


Ans: You can create a heatmap using Seaborn's
heatmap() function, specifying the data, row and
column variables, and any additional parameters. For
example:

import seaborn as sns



import pandas as pd



df = pd.read_csv('data.csv')

sns.heatmap(data=df, x='x_column', y='y_column',
cmap='coolwarm')

19
 Library for machine learning:
Scikit-learn:

Q.1 What is Scikit-learn and how is it used in machine


learning?
Ans: Scikit-learn is a popular machine learning library in
Python that provides a wide range of algorithms and
tools for various tasks such as classification,
regression, clustering, dimensionality reduction, and
model evaluation. It is widely used for building
machine learning models and pipelines.

Q.2 How do you train a machine learning model using


Scikit-learn?
Ans: To train a machine learning model using Scikit-learn,
you typically follow these steps‹
p Preprocess and prepare your datao
p Choose a suitable algorithmo
p Split your data into training and testing setso
p Fit the model to the training data using the fit()
methodo
p Evaluate the model's performance using metrics
and test data.

20
Q.3 How do you use cross-validation in Scikit-learn?
Ans: Scikit-learn provides the cross_val_score()
function to perform cross-validation. You can specify
the desired number of folds and the scoring metric to
evaluate the model's performance. For example:

from sklearn.model_selection import


cross_val_score

from sklearn.linear_model import
LinearRegression



model = LinearRegression()

scores = cross_val_score(model, X, y, cv=5,
scoring='r2')

Q.4 How do you make predictions using a trained model


in Scikit-learn?
Ans: Once you have trained a model in Scikit-learn, you
can make predictions on new data using the
predict() method. For example:

model = LinearRegression()

model.fit(X_train, y_train)

predictions = model.predict(X_test)

21
Q.5 How do you save and load a trained model in Scikit-
learn?
Ans: You can save a trained Scikit-learn model to disk
using the joblib module's dump() function. To load
a saved model, you can use the load() function.
For example:

from sklearn.externals import joblib



# Save the model



joblib.dump(model, 'model.pkl')



# Load the model



loaded_model = joblib.load('model.pkl')

22
Why

Bosscoder?
1000+ Alumni placed at Top
Product-based companies.

More than 136% hike for every 



2 out of 3 working professional.

Average package of 24LPA.

Explore More

You might also like