Python Viva Interview Questions PDF By ScholarHat

scholarhateducation 783 views 25 slides Mar 20, 2025
Slide 1
Slide 1 of 25
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25

About This Presentation

Python Viva Interview Questions PDF By ScholarHat


Slide Content

Mastering Python Viva Interview Questions You Need to Know
Python Viva Questions are important for students and professionals preparing for academic exams or technical interviews. Python is a
widely used programming language known for its simplicity and versatility. To perform well in a Python viva, you should understand key
concepts like data types, loops, functions, OOP, file handling, exception handling, and libraries.
In this Interview tutorial, we provide a list of frequently asked Python Viva Questions with answers. Whether you are a student appearing
for an exam or a professional preparing for an interview, this guide will help you answer questions confidently and effectively.
If you are preparing for a Python viva, these top 20 basic-level questions will help you strengthen your understanding of fundamental
concepts, syntax, and key features of the language. They will also boost your confidence in answering Viva questions effectively.
Python is a high-level, interpreted, and general-purpose programming language. It is known for its easy-to-read syntax and versatility,
making it suitable for various applications, including web development, data analysis, and artificial intelligence.
Top 20 Python Viva Questions and Answers for Basic Level
Q 1. What is Python?
Q 2. What are the key features of Python?

There are several built-in data types in Python, including:
Numeric types: int, float, complex
Sequence types: list, tuple, range
Mapping type: dict
Set types: set, frozenset
Text type: str
Boolean type: bool
Binary types: bytes, bytearray, memoryview
Some key features of Python include:
Easy syntax and readability
Interpreted and dynamically typed
Supports object-oriented, functional, and procedural programming
Large standard library
Cross-platform compatibility
PEP 8 is the Python Enhancement Proposal that provides guidelines for writing clean and readable Python code. It covers naming
conventions, indentation styles, and other coding standards to ensure consistency and maintainability.
List in Python: Lists are mutable (modifiable) ordered collections in Python that can hold a variety of object types, including integers,
strings, and other lists. They allow for dynamic resizing.
Q 3. What is PEP 8?
Q 4. What are Python's data types?
Q5. What are lists and tuples in Python?

Output
Output
Example
Example
(1, 2, 3, 'world')
[1, 2, 3, 'hello', 4]
my_list = [1, 2, 3, "hello"] # A list with mixed data types
my_list.append(4) # Adds an element
print(my_list)
my_tuple = (1, 2, 3, "world") # A tuple with mixed data types
# my_tuple[1] = 5 # Error: Tuples do not support item assignment
print(my_tuple)
Try it Yourself >>
Try it Yourself >>
Tuples in Python: Tuples are immutable (non-modifiable) ordered collections in Python. Once created, the elements in a tuple cannot be
changed, making them suitable for storing fixed data.
A dictionary in Python is a collection of key-value pairs where each key is unique. It is unordered, mutable, and indexed. It allows fast
lookups and is defined using curly braces { }.
Q 6. What is a dictionary in Python?

Example
# Creating a dictionary
person = {



}
"name": "Aman",
"age": 25,
"city": "New York"
# Checking if a key exists
if "name" in person:
# Accessing dictionary elements
print("Name:", person["name"])
print("Age:", person["age"])
print("City:", person["city"])
# Removing a key-value pair
del person["city"]
print("After removal:", person)
# Adding a new key-value pair
person["job"] = "Software Developer"
print("Updated dictionary:", person)
# Modifying an existing value
person["age"] = 26
print("Updated age:", person["age"])
# Looping through dictionary keys and values
for key, value in person.items():
print(f"{key}: {value}")

Output
# Getting all keys and values
keys = person.keys()
values = person.values()
print("Keys:", keys)
print("Values:", values)
print("Name exists in the dictionary.")
# Merging dictionaries
additional_info = {"hobbies": ["Reading", "Traveling"], "age": 27}
person.update(additional_info)
print("Merged dictionary:", person)
Name: Aman
Age: 25
City: New York
Updated dictionary: {'name': 'Aman', 'age': 25, 'city': 'New York', 'job': 'Software Developer'}
Updated age: 26
After removal: {'name': 'Aman', 'age': 26, 'job': 'Software Developer'}
name: Aman
age: 26
job: Software Developer
Name exists in the dictionary.
Keys: dict_keys(['name', 'age', 'job'])
Values: dict_values(['Aman', 26, 'Software Developer'])
Merged dictionary: {'name': 'Aman', 'age': 27, 'job': 'Software Developer', 'hobbies': ['Reading', 'Traveling']}
Q 10. What are Lambda functions?
Q 9. What is the difference between range() and xrange() in Python?
The difference betweenrange() and xrange() in Python:Fvar
Q 7. What is the difference between deepcopy() and shallow copy()?
The main difference between deepcopy() and shallow copy() are:
Try it Yourself >>
range() in Python 2 returns a list, and xrange() returns an iterator, which is more memory efficient.
In Python 3, range() behaves like xrange() in Python 2 and returns an iterator.
A Function in Python is a block of reusable code that performs a specific task. It is defined using the def keyword, and parameters can be
passed to the function for execution.
A shallow copy creates a new object but inserts references to the original objects' elements.
A deep copy creates a new object and recursively copies all objects found in the original object, ensuring no references to the original
objects are retained.
Q 8. What is a function in Python?

Try it Yourself >>
The difference between is and == in Python
== checks if the values of two objects are equal.
is checks if two objects refer to the same memory location (i.e., they are the same object).
A module is a file containing Python code, and it can define functions, classes, and variables.
A package is a collection of modules organized in directories, which allows for a hierarchical structure.
self represents the instance of the class in object-oriented programming. It is used to access variables and methods within the class and
distinguish between instance variables and local variables.
A decorator is a function that modifies the behavior of another function. It is used to add functionality to existing code in a reusable
manner.
A lambda function in Python is a small anonymous function defined using the lambda keyword. It can take any number of arguments but
only has one expression.
An iterator is an object that allows traversing through all the elements of a collection, such as a list or tuple. It implements two methods:
__iter__() and __next__().
Output
Example
Square of 5: 25
# A lambda function to find the square of a number
square = lambda x: x ** 2
print("Square of 5:", square(5))
Q 11. What is an iterator in Python?
Q 14. What is the purpose of self in Python?
Q 15. What are Python modules and packages?
Q 12. What is the difference between is and == in Python?
Q 16. What is a class in Python?
Q 13. What are decorators in Python?

The difference between append() and extend() in Python:
append() adds a single element to the end of a list.
extend() adds all elements from an iterable to the end of the list.
Python uses try, except, else, and finally blocks to handle exceptions. The code inside try is executed, and if an error occurs, it is handled
in the except block. The else block executes if no exception occurs, and finally executes regardless of an exception.
The with statement is used for resource management, such as file handling. It automatically takes care of setup and cleanup actions, like
closing a file after opening it.
A class in Python is a blueprint for creating objects (instances). It defines the methods and attributes that the objects created from it will
have.
Q 17. What are exception-handling mechanisms in Python?
Q 18. What is the difference between append() and extend() in Python?
Q 19. What is the use of the with statement in Python?

Q20. What are list comprehensions in Python?
Q 21. What is the difference between Python 2 and Python 3?
Python 2 and Python 3 have several differences. Some key differences include:
Try it Yourself >>
Python 3 uses print() as a function, while Python 2 uses it as a statement.
Integer division in Python 2 rounds down by default, while Python 3 uses true division (decimal results).
In Python 3, Unicode strings are the default, while in Python 2, strings are ASCII unless explicitly declared as Unicode.
Python uses automatic memory management, which includes a garbage collection system that cleans up unused objects. The memory is
managed through reference counting and cyclic garbage collection. The gc module isused for Python garbage collection.
List comprehensions in Python provide a concise way to create lists. They consist of an expression followed by a for clause, optionally
including if conditions.
When preparing for an advanced-level Python viva, these top 20 questions will deepen your understanding of complex topics,
performance optimization, and real-world implementations. They will also help you answer questions with confidence and clarity.
Output
Example
Squared Numbers: [1, 4, 9, 16, 25]
# List of numbers
numbers = [1, 2, 3, 4, 5]
# List comprehension to square each number
squared_numbers = [x ** 2 for x in numbers]
print("Squared Numbers:", squared_numbers)
Top 20 Python Viva Questions and Answers for Advanced Level
Q 22. How does Python handle memory management?

Q 23. Explain Python's Global Interpreter Lock (GIL).
The Global Interpreter Lock (GIL) is a mutex that protects access to Python objects, ensuring that only one thread can execute Python
bytecode at a time. This can be a bottleneck in CPU-bound multi-threaded programs but does not affect I/O-bound tasks.
Q 26. What are Python generators, and how do they differ from iterators?
Q 24. What is the difference between a method and a function in Python?
The difference between a method and a function in Python:
Multiple exceptions can be handled using a single except block by specifying them in a tuple. For example:
A decorator is a function that takes another function as an argument and extends or alters its behavior without modifying the function
itself. Decorators are commonly used for logging, access control, caching, and other repetitive tasks.
A function is a block of code that is defined using the def keyword and can be called independently of classes.
A method is a function that is associated with an object and is called on the object itself. Methods are typically defined inside a class.
@staticmethod is used to define a method that does not require access to the instance (self) or the class (cls), meaning it works like a
regular function but belongs to the class.
@classmethod is used to define a method that takes the class as its first argument (cls), allowing it to modify the class state.
Generators are a type of iterable in Python that allows lazy evaluation. They are defined using the yield keyword and are more memory
efficient than normal functions.
Iterators are objects that implement the __iter__() and __next__() methods. Generators are a simpler and more memory-efficient form
of iterators.
Q 29. What are Python’s built-in data structures?
Q 28. How can you handle multiple exceptions in Python?
Q 25. What are Python decorators, and how do they work?
Q 27. What is the difference between @staticmethod and @classmethod?
try:



# some code
except (TypeError, ValueError) as e:
print(f"Error: {e}")

Python has several built-in data structures:
Lists (ordered, mutable)
Tuples (ordered, immutable)
Dictionaries (unordered, mutable key-value pairs)
Sets (unordered, mutable, no duplicates)
Frozensets (immutable sets)
Queues(FIFO, implemented using collections.deque)
Python provides a rich set of built-in modules, such as:
os for interacting with the operating system
sys for interacting with the Python runtime environment
math for mathematical operations
datetime for working with dates and times
json for handling JSON data
del is a keyword used to delete an object, list item, or variable from memory.
remove() is a method used on lists to remove the first occurrence of a specified value from the list.
The with statement is used for resource management (e.g., file handling). It simplifies exception handling and ensures that resources like
files or network connections are automatically closed after use. It is used with objects that implement the context management protocol
(__enter__ and __exit__ methods).
Q 32. What are Python’s built-in modules?
Q 30. Explain the with statement in Python.
Q 31. What is the difference between del and remove() in Python?

collections for specialized data structures like deque, Counter, etc.
Unit testing in Python is commonly done using the built-in unittest module.
The isinstance() function is used to check if an object is an instance or subclass of a particular class. Example:
Import the unittest module.
Create a test class that inherits from unittest.TestCase.
Define test methods inside the class. Each test method must start with test_.
Use assertion methods such as assertEqual(), assertTrue(), assertRaises(), etc., to check the expected outcomes.
Run the tests by calling unittest.main() or using a test runner.
staticmethod does not take any special first argument (self or cls). It behaves like a regular function but is scoped within the class.
classmethod takes the class itself (cls) as its first argument and can modify the class state, while a static method cannot.
The finally block is executed no matter what, whether an exception occurs or not. It is typically used for cleanup operations, such as
closing files or releasing resources.
The super() function is used to call methods from a parent class in a subclass, allowing for method overriding and inheritance chains. It is
often used to extend or modify the behavior of inherited methods.
__str__() is used to define a user-friendly string representation of an object. It is used by the print() function.
__repr__() is used to define a string representation that is unambiguous and can be used to recreate the object. It is often used for
debugging.
A list comprehension is a compact way to process and filter elements in a list. It allows for writing more concise and readable code. For
example:
Duck typing refers to the idea that an object's suitability for use is determined by its behavior (methods and attributes) rather than its
class or type. If an object behaves like a certain type (e.g., it has a walk() method), it can be treated as that type, even if it isn't an
explicit subclass of the expected type.
Q 38. How do you perform unit testing in Python?
Q 40. Explain the concept of "duck typing" in Python.
Q 34. What is the finally block in exception handling?
Q 37. What are list comprehensions, and how do they work in Python?
Q 33. What is the difference between __str__() and __repr__() in Python?
Q 39. What are the differences between staticmethod and class method in Python?
Q 36. What is the isinstance() function used for?
Q 35. What is the purpose of the super() function in Python?
isinstance(obj, ClassName)
squares = [x**2 for x in range(10) if x % 2 == 0]
Steps to perform unit testing in Python:
Top 15 Python Viva Questions and Answers for Object-Oriented
Programming

Encapsulation: Bundling data and methods that operate on that data within a single unit, called a class.
Abstraction: Hiding the complexity and only exposing the necessary parts of the object.
Inheritance: Creating a new class from an existing class by inheriting its attributes and methods.
Polymorphism: Allowing different classes to be treated as instances of the same class through inheritance, but each class can
implement its own version of methods.
A class is a blueprint or template for creating objects. It defines the attributes and behaviors that the objects created from the class
will have.
An object is an instance of a class. It is a specific realization of the class with its own state (data) and behavior (methods).
For those preparing for a Python viva on Object-Oriented Programming, these top 15 questions will improve your understanding of key
principles like classes, objects, inheritance, and polymorphism. They will also help you explain concepts clearly and confidently.
Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects," which can contain data in the form of
fields (attributes) and code in the form of procedures (methods). The four main principles of OOP are:
Q 43. What is inheritance in Python?
Q 42. What are classes and objects in Python?
Q 41. What is Object-Oriented Programming (OOP)?

Try it Yourself >>
__init__ is the constructor method that is called after an object is created. It is used to initialize the object's state.
__new__ is a method that is responsible for creating the object in memory. It is called before __init__.
Inheritance In Python allows a class to inherit attributes and methods from another class. The new class (called the child or subclass)
inherits the properties and methods of the existing class (called the parent or superclass) and can override or extend them. Inheritance
promotes code reuse.
Output
Example
print(animal.speak())
print(dog.speak())
# Base class
class Animal:


def __init__(self, name):
self.name = name
Generic Animal makes a sound.
Buddy says Woof!
# Using the classes
animal = Animal("Generic Animal")
dog = Dog("Buddy")
# Derived class
class Dog(Animal):


def speak(self):
return f"{self.name} says Woof!"


def speak(self):
return f"{self.name} makes a sound."
Q 45. What is polymorphism in Python?
Q 44. What is the difference between __init__ and __new__ in Python?

Try it Yourself >>
Polymorphism allows different classes to implement the same method or behavior differently. In Python, polymorphism can be achieved
through method overriding (in inheritance) or method overloading (using default arguments).
Encapsulation is the concept of restricting direct access to some of an object's attributes and methods. It helps to protect the object's
internal state by exposing only the necessary parts. In Python, this is typically done by defining private variables (prefixing with _ or __)
and providing getter and setter methods.
Output
Example
Dog says Woof!
Cat says Meow!
# Creating objects
dog = Dog() cat =
Cat()
# Using polymorphism
print(animal_sound(dog))
print(animal_sound(cat))
# Derived class 1
class Dog(Animal):


def speak(self):
return "Dog says Woof!"
# Derived class 2
class Cat(Animal):


def speak(self):
return "Cat says Meow!"
# Getter method for balance
# Function demonstrating polymorphism
def animal_sound(animal):
return animal.speak()
# Base class
class Animal:


def speak(self):
return "Animal makes a sound."
class BankAccount:



def __init__(self, owner, balance=0):
self.owner = owner # Public attribute
self.__balance = balance # Private attribute (encapsulated)
Q 46. What is encapsulation in Python?

Output
Account owner: Alice
Initial balance: 1000
Updated balance: 1300


def get_balance(self):
return self.__balance
# Creating a BankAccount object
account = BankAccount("Alice", 1000)






# Method to withdraw money
def withdraw(self, amount):
if 0 < amount <= self.__balance:
self.__balance -= amount
else:
print("Invalid withdrawal amount.")
# Modifying the balance using encapsulated methods
account.deposit(500)
account.withdraw(200)






# Setter method for balance
def deposit(self, amount):
if amount > 0:
self.__balance += amount
else:
print("Deposit amount must be positive.")
print("Updated balance:", account.get_balance()) # Access updated balance
# Accessing public and private attributes
print("Account owner:", account.owner) # Accessible
print("Initial balance:", account.get_balance()) # Access private attribute via method
Q 47. What is an abstract class in Python?
An abstract class in Python is a class that cannot be instantiated on its own and must be subclassed. It can contain abstract methods,
which are methods without implementation that must be overridden by subclasses.
Q 49. What is the purpose of the super() function in Python?
Q 48. What is the difference between @staticmethod and @classmethod?
Try it Yourself >>
@staticmethod defines a method that does not take any special first argument (e.g., self or cls). It is used when a method does not
need to modify the object's state or class state.
@classmethod defines a method that takes the class as its first argument (cls). It is used when a method needs to modify the class
state or access class-level properties.

Try it Yourself >>
Multiple inheritance is when a class inherits from more than one parent class. Python supports multiple inheritance, but it can lead to
complex situations such as the "diamond problem." It is handled using the Method Resolution Order (MRO) in Python.
The super() function is used to call methods from a parent class in a subclass, allowing for method overriding and inheritance chains. It is
commonly used in the __init__ method to initialize parent class attributes.
__str__() is used to define the user-friendly string representation of an object. It is called by the print() function.
__repr__() is used to define the official string representation of an object that is unambiguous and can be used to recreate the object. It
is often used for debugging.
Python does not support method overloading in the traditional sense (i.e., defining multiple methods with the same name but different
signatures). However, method overloading can be simulated by using default arguments or variable-length arguments (*args, **kwargs).
Q 52. What is multiple inheritance in Python?
Q 51. What is method overloading in Python?
Q 50. What are __str__() and __repr__() methods in Python?
Output
Example
Example
10
8
# Base class 1
class Animal:


def __init__(self, name):
self.name = name
# Creating a Calculator object
calc = Calculator()


def speak(self):
return f"{self.name} makes a sound."
# Calling the add method with one and two arguments
print(calc.add(5))
print(calc.add(5, 3))
class Calculator:





def add(self, a, b=None):
if b is None:
return a + a # Overloading to handle one argument (returns double)
else:
return a + b # Normal addition for two arguments

Output
Example
Buddy says Woof!
True
# Creating a Dog object
dog = Dog("Buddy")
print(dog.speak())
print(dog.is_warm_blooded)


def is_warm_blooded(self):
return self.is_warm_blooded
# Derived class (Multiple inheritance)
class Dog(Animal, Mammal):



def __init__(self, name):
Animal.__init__(self, name)
Mammal.__init__(self)


def speak(self):
return f"{self.name} says Woof!"
# Base class 2
class Mammal:


def __init__(self, is_warm_blooded=True):
self.is_warm_blooded = is_warm_blooded
class MyClass:




def __init__(self, name):
self.name = name
print(f"Object {self.name} created.")
def __del__(self):


# Creating an object
print(f"Object {self.name} is being destroyed.")
Q 54. What is the __del__ method in Python?
The __del__() method is the destructor in Python, which is called when an object is about to be destroyed. It is used to clean up resources
(e.g., closing files or network connections). However, it is not guaranteed to be called immediately when an object goes out of scope due
to Python's garbage collection mechanism.
Q 53. What is the difference between self and cls in Python?
The difference between self and cls in Python
Try it Yourself >>
self is used in instance methods to refer to the instance of the class (i.e., the object itself).
cls is used in class methods to refer to the class itself (i.e., the class that the method is called on).

Output
import pandas as pd
obj = MyClass("Test Object")
class MyClass:



def __init__(self):
self._internal_var = 42
self.__private_var = 24
Object Test Object created.
Object Test Object is being destroyed.
# From a dictionary
data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35]}
df = pd.DataFrame(data)
# Deleting the object explicitly (or it will be automatically deleted when it goes out of scope)
del obj
DataFrame Series
Q 56. What is Pandas in Python?
Pandas is an open-source Python library used for data manipulation and analysis. It provides data structures like
Q 58. How do you create a DataFrame in Pandas?
You can create a DataFrame using a dictionary or a listor from external files like CSV or Excel.
Q 55. Can Python classes have private members?
Python does not have strict access control like other languages (e.g., Java). However, it does provide a convention for private members by
prefixing them with a single underscore (_) or double underscore (__). While the members are not truly private, this serves as a guideline
for internal use.
Q 59. What is the purpose of the read_csv() function in Pandas?
Q 57. What is the difference between a Pandas DataFrame and a Pandas Series?
The difference between a Pandas DataFrame and a Pandas Series:
Try it Yourself >>
that are efficient for handling large datasets and performing operations like grouping, merging, reshaping, and cleaning data.
and
DataFrame: A 2-dimensional labeled data structure with columns of potentially different types. It's like a table or a spreadsheet with
rows and columns.
Series: A 1-dimensional labeled array that can hold any data type. It is essentially a single column in a DataFrame.
Python viva on Pandas, these top 15 questions will help you understand essential concepts like data manipulation, DataFrame
operations, and handling missing values. They will also boost your confidence in answering Viva questions effectively.
Top 15 Python Viva Questions and Answers for Pandas

The difference between loc[] and iloc[] in Pandas
loc[]: Accesses data by label (i.e., row/column names).
iloc[]: Accesses data by index (i.e., integer position).
You can filter data using conditions inside square brackets or using the query() method.
Pandas provides several methods for handling missing data, such as:
dropna(): Removes missing values.
fillna(): Replaces missing values with a specified value or method (e.g., forward fill or mean).
You can sort data in Pandas using the sort_values() function by specifying the column(s) to sort by.
You can use the concat() function to concatenate DataFrames along a particular axis (rows or columns).
The pivot_table() function is used to create a pivot table by summarizing data based on some column(s) and applying aggregation
functions like sum or mean.
The read_csv() function is used to read a CSV file and convert it into a DataFrame. It can handle large files and support various
customization options like delimiters, handling missing values, and specifying data types.
The groupby() function is used to split the data into groups based on some criteria and perform aggregate operations like sum, mean, or
count. It is commonly used for data aggregation and summarization.
df = pd.read_csv('data.csv')
df.dropna() # Drops rows with missing values
df.fillna(0) # Replaces missing values with 0
df1 = pd.DataFrame({'A': [1, 2], 'B': [3, 4]}) df2 =
pd.DataFrame({'A': [5, 6], 'B': [7, 8]})
df.pivot_table(values='Age', index='Name', aggfunc='mean')
df[df['Age'] > 30] # Filters rows where Age is greater than 30
df.query('Age > 30') # Using query method
df.loc[1, 'Age'] # Accesses row with label 1 and column 'Age'
df.iloc[1, 2] # Accesses row with index 1 and column at index 2
df.sort_values(by='Age') # Sorts by the 'Age' column
df.sort_values(by='Age', ascending=False) # Sorts in descending order
df.groupby('Age').mean() # Groups by 'Age' and computes the mean of other columns
Q 62. What is the groupby() function in Pandas?
Q 60. How do you handle missing data in Pandas?
Q 64. What is the pivot_table() function in Pandas?
Q 63. How can you filter data in a Pandas DataFrame?
Q 65. What are some ways to sort data in a DataFrame?
Q 61. What is the difference between loc[] and iloc[] in Pandas?
Q 66. How do you concatenate two or more DataFrames in Pandas?

df.describe()
import numpy as np
arr = np.array([1, 2, 3])
df.drop_duplicates() # Removes duplicate rows
df['Age'] = df['Age'].apply(lambda x: x + 1) # Adds 1 to each Age
df_combined = pd.concat([df1, df2], axis=0) # Concatenate along rows
df1 = pd.DataFrame({'ID': [1, 2], 'Name': ['Alice', 'Bob']})
df2 = pd.DataFrame({'ID': [1, 3], 'Age': [25, 30]})
df_merged = pd.merge(df1, df2, on='ID', how='inner') # Inner join on 'ID'
Q 71. What is NumPy in Python?
NumPy is an open-source Python library for numerical computing. It provides support for large, multi-dimensional arrays and matrices,
along with a collection of mathematical functions to operate on these arrays efficiently.
Q 72. How do you create a NumPy array?
You can create a NumPy array using the np.array() function, which can convert Python lists or tuples into arrays.
Q 70. How do you handle duplicates in a DataFrame?
Pandas provides the drop_duplicates() function to remove duplicate rows from a DataFrame.
Q 68. How can you merge two DataFrames in Pandas?
You can merge DataFrames using the merge() function, similar to SQL joins (inner, left, right, outer).
Q 69. How do you get summary statistics for a DataFrame?
You can use the describe() function to get summary statistics such as mean, standard deviation, min, and max for numerical columns.
Q 67. What is the purpose of the apply() functionin Pandas?
The apply() function allows you to apply a function along the axis (rows or columns) of a DataFrame. It can be used for element-wise
operations or to apply a custom function to data.
Q 74. What are the benefits of using NumPy arrays over Python lists?
Q 73. What is the difference between a Python list and a NumPy array?
The difference between a Python list and a NumPy array:
Python viva on NumPy, these top 15 questions will help you understand core concepts like arrays, indexing, broadcasting, and
mathematical operations. They will also enhance your confidence in explaining NumPy functions clearly.
Python list: Can hold elements of different data types.
NumPy array: Holds elements of the same data type, making it more efficient for numerical computations. Supports element-wise
operations and is optimized for performance.
Top 15 Python Viva Questions and Answers for NumPy

You can initialize a NumPy array using the following functions:
np.zeros(): Creates an array of zeros.
np.ones(): Creates an array of ones.
np.arange(): Creates an array with evenly spaced values.
np.linspace(): Creates an array with a specified number of evenly spaced values.
You can compute statistical values like mean, median, and standard deviation using NumPy functions:
The shape of a NumPy array is a tuple that represents the number of elements in each dimension. For example, a 2D array with 3 rows and
4 columns will have a shape of (3, 4).
You can reshape a NumPy array using the reshape() function. This allows you to change the dimensions of the array without changing its
data.
Broadcasting is a set of rules that NumPy follows to perform element-wise operations on arrays of different shapes. It automatically
expands the smaller array to match the shape of the larger array during the operation.
NumPy arrays offer better performance for numerical operations, as they are implemented in C and optimized for fast operations. They
are more memory-efficient, support vectorized operations, and allow for advanced indexing and slicing.
NumPy supports element-wise operations, which means you can perform mathematical operations (e.g., addition, subtraction,
multiplication, etc.) directly on arrays.
Q 77. What is broadcasting in NumPy?
Q 76. How do you reshape a NumPy array?
Q 75. What is the shape of a NumPy array?
Q 78. What are some common ways to initialize a NumPy array?
Q 79. How do you perform element-wise operations on NumPy arrays?
Q 80. How do you compute the mean, median, and standard deviation of a NumPy array?
arr = np.array([1, 2, 3, 4, 5])
mean = np.mean(arr) # Mean
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr.shape) # Output: (2, 3)
arr1 = np.array([1, 2, 3]) arr2 = np.array([4, 5, 6])
result = arr1 + arr2 # Element-wise addition
arr = np.array([1, 2, 3, 4, 5, 6])
reshaped_arr = arr.reshape(2, 3) # Reshapes to 2 rows, 3 columns
arr1 = np.array([1, 2, 3])
arr2 = np.array([1])
result = arr1 + arr2 # arr2 is broadcasted to match the shape of arr1
np.zeros((2, 3))
np.ones((2, 3))
np.arange(0, 10, 2)
# 2x3 array of zeros
# 2x3 array of ones
# Array with values from 0 to 10 with a step of 2
np.linspace(0, 10, 5) # Array with 5 evenly spaced values between 0 and 10

arr = np.array([1, 2, 3, 4, 5]) max_val =
np.max(arr) # Maximum value min_val =
np.min(arr) # Minimum value
arr1 = np.array([1, 2]) arr2 = np.array([3, 4]) result
= np.dot(arr1, arr2) # Dot product
median = np.median(arr)
std_dev = np.std(arr)
# Median
# Standard Deviation
arr1 = np.array([1, 2, 3]) arr2 = np.array([4, 5, 6]) vstack_arr = np.vstack((arr1,
arr2)) # Stacks arrays vertically hstack_arr = np.hstack((arr1, arr2)) # Stacks
arrays horizontally
arr = np.array([1, 2, 3, 4, 5])
slice_arr = arr[1:4] # Slices elements from index 1 to 3 (not 4)
arr1 = np.array([1, 2, 3])
arr2 = arr1.copy() # arr2 is a copy, changes to arr2 won't affect arr1
Q 86. What are Python libraries?
Python libraries are pre-written code or modules that provide the functionality to perform various tasks without needing to code
everything from scratch. They include functions, classes, and methods to make coding easier.
Q 87. What is the purpose of NumPy?
Q 82. How do you index and slice a NumPy array?
You can index and slice NumPy arrays similarly to Python lists, but NumPy arrays support advanced slicing and multi-dimensional
indexing.
Q 84. What is the purpose of the np.dot() function?
The np.dot() function is used to compute the dot product of two arrays. It can be used for both matrix multiplication and vector dot
product.
Q 85. How do you stack NumPy arrays vertically and horizontally?
You can stack arrays vertically and horizontally using np.vstack() and np.hstack(), respectively.
Q 81. What is the difference between np.copy() and simple assignment?
np.copy() creates a new array with the same data, whereas simple assignment (e.g., arr2 = arr1) creates a reference to the same array.
Changes made to one will affect the other when using simple assignment.
Q 83. How do you find the maximum and minimum values of a NumPy array?
You can use the np.max() and np.min() functions to find the maximum and minimum values, respectively.
Python viva on libraries, these top 20 questions will help you understand the functionality and use cases of popular Python libraries like
Pandas, NumPy, Matplotlib, and more. They will also boost your ability to explain their features confidently.
Top 20 Python Libraries Viva Questions and Answers

Flask: A micro-framework that is lightweight and flexible, allowing you to build custom applications with minimal setup.6Django: A
full-stack framework that includes built-in features such as user authentication, ORM, and admin interfaces, providing a more
structured approach.
Pandas is a library for data manipulation and analysis. It provides data structures like Series and DataFrame, which are used to handle
structured data (e.g., CSV files, Excel files, SQL queries).
Flask is a lightweight web framework for Python. It is used to build web applications and APIs. Flask is simple to use and gives developers
control over app structure and routing.
NumPy: Used for numerical computations, supporting large, multi-dimensional arrays and matrices.
Pandas: A data manipulation library designed for handling structured data with tools like Series and DataFrame, supporting complex
operations like groupby, merging, and reshaping.
NumPy is a Python library for numerical computing. It provides support for arrays and matrices, along with a large collection of
mathematical functions to operate on these data structures efficiently.
Seaborn is a Python data visualization library built on top of Matplotlib. It provides a high-level interface for drawing attractive statistical
graphics and visualizations, such as heatmaps, box plots, and violin plots.
BeautifulSoup is a Python library used for web scraping purposes. It allows users to parse HTML and XML documents, extract useful
information, and navigate through complex web page structures.
Matplotlib is a plotting library in Python used to create static, animated, and interactive visualizations. It allows users to plot graphs,
charts, and images from data.
TensorFlow is an open-source machine-learning library developed by Google. It is used for building and training deep learning models,
such as neural networks, for tasks like image recognition, language processing, and more.
The requests library in Python is used to send HTTP requests and interact with RESTful APIs. It simplifies making HTTP requests,
handling responses, and dealing with headers, cookies, and sessions.
Q 97. What is Keras?
Q 94. What is Flask used for?
Q 88. What is Pandas used for?
Q 90. What is Seaborn in Python?
Q 89. Explain Matplotlib and its usage.
Q 95. How does Django differ from Flask?
Q 93. Explain the role of BeautifulSoup in web scraping.
Q 91. What is the difference between NumPy and Pandas?
Q 96. What is TensorFlow used for?
Q 92. What is the use of the Requests library?

PyTorch is an open-source deep-learning library developed by Facebook. It provides dynamic computation graphs and supports GPU
acceleration, making it popular for research and production-level applications.
Scikit-learn is a machine-learning library in Python. It provides simple and efficient tools for data mining and data analysis, including
algorithms for classification, regression, clustering, and dimensionality reduction.
Plotly is a graphing library for creating interactive and publication-quality visualizations. It supports a wide range of chart types, including
line charts, bar charts, heat maps, and 3D plots.
SQLite3 is a Python library used to interact with SQLite databases. It provides a lightweight, serverless, and self-contained database
engine for storing and managing relational data.
Keras is an open-source deep-learning framework that provides a high-level interface for building and training neural networks. Keras is
built on top of TensorFlow and makes it easier to develop deep learning models.
OpenCV is a computer vision library used to process and analyze images and videos. It provides various tools for real-time computer
vision applications such as object detection, face recognition, and image manipulation.
SciPy is a Python library used for scientific and technical computing. It builds on NumPy and provides additional functionality for
optimization, integration, interpolation, eigenvalue problems, and other scientific tasks.
This article provides a comprehensive set of Python viva questions, covering basic concepts, advanced OOP principles, Pandas, NumPy,
and essential Python libraries. It includes structured Q&A with examples to help students and professionals prepare effectively. Whether
you are a beginner or an advanced learner, these questions will enhance your understanding of Python. Boost your Python skills with this
Python Data Science & AI Certification Training.
Pillow is a Python Imaging Library (PIL) that adds image processing capabilities to Python. It provides functions for opening,
manipulating, and saving many different image file formats.
SQLAlchemy is a Python SQL toolkit and Object-Relational Mapping (ORM) library. It provides tools for working with relational databases,
allowing developers to interact with databases using Python objects and expressions instead of SQL queries.
Q 98. What is PyTorch?
Q 102. What is SQLAlchemy?
Q 103. What is SciPy used for?
Q 101. What is Pillow in Python?
Q 100. What is OpenCV used for?
Q 99. What is Scikit-learn used for?
Q 104. What is the purpose of the Plotly library?
Q 105. What is the purpose of the SQLite3 library in Python?
Summary
Python Viva Questions - Test Your Knowledge!

Q 1: What is Python?
(a) A type of snake
(b) A high-level, interpreted programming language
(c) A database management system
(d) A web browser
View Answer ⬇
Q 3: What is PEP 8 in Python?
(a) A database tool
(b) A coding style guide for Python
(c) A machine learning algorithm
(d) A debugging tool
Q 2: What are Python's key features?
(a) Simple and easy to learn
(b) Interpreted and dynamically typed
(c) Supports object-oriented programming
(d) All of the above
View Answer ⬇
Q 4: What is the difference between a list and a tuple?
(a) Lists are mutable, while tuples are immutable
(b) Lists are enclosed in square brackets, tuples in parentheses
(c) Tuples have faster execution than lists
(d) All of the above
View Answer ⬇
Q 5: What is the difference between deep copy and shallow copy?
(a) Shallow copy creates a new reference, deep copy creates a separate object
(b) Deep copy is faster than shallow copy
(c) Shallow copy copies all objects recursively
(d) Deep copy only copies the first level of objects
View Answer ⬇
View Answer ⬇