Level Up Your Python Skills: Essential Interview Questions Answered
PYTHON INTERVIEW QUESTIONS
Table of Contents
ToggleWhat are the basic data types in Python?
The basic data types in Python are:
Integer : represents whole numbers.
Float : represents decimal numbers.
String : represents a sequence of characters.
Boolean : represents either True or False.
List : represents an ordered collection of elements.
How do you convert a string to an integer in Python?
The int() method converts strings to integers.
For example:
num_str = "10"
num_int = int(num_str)
How do you check the data type of a variable in Python?
You may use the ‘type()’ method to determine the data type of a variable.
For example:
num = 10
print (type(num)) # Output: <class 'int'>
What is the difference between a list and a tuple in Python?
A list may be modified, however a tuple cannot be altered once created.
How do you create an empty dictionary in Python?
To build an empty dictionary, use either the curly braces {} or the dict() method.
For example:
empty_dict = {}
empty_dict = dict()
OOPS concept in Python:
What is OOPS and how is it implemented in Python?
Object-Oriented Programming (OOPS) employs objects to represent real-world things. Python implements object-oriented programming (OOPS) via classes and objects. Classes are blueprints for producing things, whereas objects are instances of those classes.
What are the four principles of OOPS?
The four principles of OOPS are:
- Encapsulation : bundling of data and methods that operate on that data within a single unit (class).
- Inheritance : ability of a class to inherit properties and methods from its parent class.
- Polymorphism : ability of an object to take on different forms or behaviors based on the context.
- Abstraction : representing essential features and hiding unnecessary details to simplify the complexity.
What is method overloading in Python?
In Python, method overloading is creating numerous methods with the same name but different arguments within a class. Python does not have built-in support for method overloading, unlike Java. In Python, you may achieve the same result by utilizing default or variable-length parameters.
What is method overriding in Python?
In Python, method overriding occurs when a child class defines a method with the same name and signature as the parent class. The child class’s method overrides the parent’s method, resulting in a different implementation.
What is the difference between a class method and an instance method in Python?
A class method is connected to the class, not its instance. It uses the @classmethod decorator and can only access class-level variables. Instance methods have access to both instance and class-level variables as they are tied to the class instance.
String handling functions:
How do you concatenate two strings in Python?
The + operator allows you to concatenate two strings.
For example:
str1 = "Hello"
str2 = "World"
result = str1 + str2Ā Ā Ā Ā Ā Ā Ā # Output: "HelloWorld"
How do you find the length of a string in Python?
Use the len() method to determine the length of a string.
For example:
str1 = "Hello World"
length = len(str1)
# Output: 11
How do you convert a string to uppercase in Python?
The upper() function converts a string to uppercase.
For example:
str1 = "hello"
uppercase_str = str1.upper()
# Output: "HELLO"
How do you split a string into a list of substrings in Python?
The split() function splits a text into substrings depending on a delimiter.
For example:
str1 = "Hello,World"
substrings = str1.split(",")
# Output: ["Hello", "World"]
How do you check if a string contains a specific substring in Python?
You may use the in keyword to see if a substring exists in a string.
For example:
str1 = "Hello World"
is_present = "World" in str1
# Output: True
Control statements, functions in Python:
What are control statements in Python?
Control statements guide the execution of a program. Common control statements in Python are if-else, for loops, while loops, and break/continue commands.
How do you write an if-else statement in Python?
To write an if-else statement in Python, use the following syntax:
if condition:
Ā Ā Ā Ā Ā # Code block executed if the condition is True
else:
Ā Ā Ā Ā Ā # Code block executed if the condition is False
How do you define a function in Python?
Python functions are defined using the def keyword. For example:
def greet ():
Ā print("Hello, world")
How do you pass arguments to a function in Python?
To send arguments to a function, include them inside parentheses when declaring it.
For example:
def greet(name):
print("Hello, " + name + "!")
How do you return a value from a function in Python?
To return a value from a function, use the return keyword.
For example:
def add(a, b):
Ā return a + b
Special data types in Python:
What is a set in Python?
A set in Python is an unsorted collection of distinct items. It is defined with curly braces {} or set() constructor.
For example:
my_set = {1, 2, 3}Ā Ā Ā Ā # Output: {1, 2, 3}
What is a dictionary in Python?
A dictionary in Python is an unsorted collection of key-value pairs. It’s defined with curly braces {} or the dict() constructor.
For example:
my_dict = {"name" :"John" ,"age" :25}
# Output: {"name": "John", "age": 25}
How do you access values in a dictionary in Python?
You may access values in a dictionary by typing the relevant key.
For example:
my_dict = {"name" : "John", "age": 25}
print(my_dict["name"])
# Output: "John"
What is a tuple in Python?
Python defines a tuple as an ordered and immutable collection of items. It is defined in parentheses () or using the tuple() constructor.
For example:
my_tuple = (1,2,3) # Output: (1, 2, 3)
How do you swap the values of two variables in Python?
Use a temporary variable or simultaneous assignment to swap the values of two variables.
For example:
a = 5
b = 10
a, b = b, a
print(a, b) # Output: 10, 5
Lambda functions, list comprehension:
What is a lambda function in Python?
A lambda function is an anonymous function created with the lambda keyword. It is commonly used for small, one-line routines.
For example:
square = lambdax: x** 2
print(square(3))
# Output: 9
What is list comprehension in Python?
Python’s list comprehension function creates lists from existing iterables. This code creates a new list, loops through it, and includes optional conditionals.
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]
How do you filter elements in a list using list comprehension?
List comprehension allows you to filter entries in a list by adding a conditional expression.
For instance, filtering 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]
Can you have multiple if conditions in list comprehension?
Yes, you can have several if conditions in list comprehension by chaining them together with the and 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]
How do you create a dictionary using list comprehension in Python?
To construct a dictionary using list comprehension, define key-value pairs between curly brackets {}.
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}
Types of plots in Seaborn and Matplotlib and their uses:
What are some commonly used plots in Seaborn and Matplotlib?
Some commonly used plots in Seaborn and Matplotlib include:
- Line plot : shows the trend of a variable over time.
- Scatter plot : displays the relationship between two variables.
- Bar plot : compares categories or groups using rectangular bars.
- Histogram : visualizes the distribution of a continuous variable.
- Box plot : represents the distribution of a variable and displays outliers.
- Heatmap : shows the correlation or relationship between variables using colors.
- Violin plot : combines a box plot and a kernel density plot to represent the distribution of a variable.
How do you create a box plot using Matplotlib?
You may use Matplotlib’s boxplot() function to generate a box plot by passing in the data and any other arguments.
For example:
import matplotlib.pyplot as plt
import pandas as pd
df = pd.read_csv('data.csv')
plt.boxplot(df['column'])
How do you create a histogram using Seaborn?
Seaborn’s distplot() method allows you to construct a histogram by supplying the variable and any other arguments.
For example:
import seaborn as sns
import pandas as pd
df = pd.read_csv('data.csv')
sns.distplot(df['column'])
How do you create a bar plot using Matplotlib?
To produce a bar plot, use Matplotlib’s bar() or barh() functions with the data and any extra arguments.
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'])
How do you create a heatmap using Seaborn?
To produce a heatmap, use Seaborn’s heatmap() function, supplying the data, row and column variables, and any other options.
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')
Library for machine learning: Scikit-learn:
What is Scikit-learn and how is it used in machine learning?
Scikit-learn is a popular Python machine learning framework that offers algorithms and tools for classification, regression, clustering, dimensionality reduction, and model assessment. It is commonly used to create machine learning models and pipelines.
How do you train a machine learning model using Scikit-learn?
To train a machine learning model using Scikit-learn, take the following steps:
- Preprocess and organize your data.
- Select an appropriate algorithm.
- Divide your data into training and test sets.
- Fit the model to the training data via the fit() function.
- AssessĀ theĀ model’sĀ performanceĀ usingĀ metricsĀ andĀ testĀ data.
How do you use cross-validation in Scikit-learn?
Scikit-learn’s cross_val_score() method enables cross-validation. To evaluate model performance, give the appropriate number of folds and scoring metric.
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')
How do you make predictions using a trained model in Scikit-learn?
Scikit-learn’s predict() function allows you to make predictions on new data after training the model.
For example:
model = LinearRegression()
model.fit(X_train, y_train)
predictions = model.predict(X_test)
How do you save and load a trained model in Scikit-learn?
To save a trained Scikit-learn model to disk, use the joblib module’s dump() method. To retrieve a stored model, use the load() method.
For example:
from import sklearn.externals joblib
# Save the model
joblib.dump(model,'model.pkl')
# Load the model
loaded_model = joblib.load('model.pkl')