40 Python Viva Questions & Answers for BCA/Btech/CS Students


Q1. What is the difference between Python 2 and Python 3?

Ans: Python 2 and Python 3 are both versions of the programming language Python, but they are not fully compatible with one another. Python 2 was first released in 2000 and is no longer actively developed, while Python 3 was first released in 2008 and is the current version of the language. One of the main differences between the two is that Python 3 introduced a number of changes to the language's syntax and standard library, which can make it difficult to run code written for Python 2 on Python 3 and vice versa.

Q2. What are some of the most commonly used built-in data types in Python?

Ans: Some of the most commonly used built-in data types in Python include integers, floating-point numbers, strings, lists, and dictionaries.

Q3. How does Python handle memory management?

Ans: Python uses a system called reference counting to manage memory. When a variable is assigned to an object, the reference count for that object is incremented. When the variable is reassigned or goes out of scope, the reference count is decremented. When the reference count for an object reaches zero, the memory for that object is freed.

Q4. What is a Python module, and how are they used?

Ans: A Python module is a file containing Python definitions and statements. The file name is the module name with the suffix .py added. A module can define functions, classes and variables. A module can also include runnable code. Modules can be imported into other modules or into the main module using the import statement.

Q5. How does the use of indentation in Python affect the structure of the code?

Ans: In Python, indentation is used to indicate the block of code that belongs to a control structure, such as a loop or a function definition. Code that is indented at the same level is considered to be in the same block, and the level of indentation determines the structure of the code.

Q6. What is the use of "init" method in python?

Ans: "init" is a special method in Python classes, it is known as a constructor. It is automatically called when an object of a class is created. It can be used to set the initial state of an object.

Q7. Can you explain about "self" keyword in python?

Ans: "self" is a reference to the instance of the class. It is used to access the attributes and methods of the class. It is the first parameter that is passed to the methods in the class.

Q8. How to use exception handling in python?

Ans: In Python, exception handling can be done using try-except block. The code that might raise an exception is put in the try block. The code that will handle the exception is put in the except block. If an exception is raised in the try block, the code in the except block will be executed. If no exception is raised, the code in the except block will be skipped.

Q9. What are the advantages of using python over other programming languages?

Ans: Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is easy to learn, easy to use and maintain, portable, extendable scalable, GUI programming. It is a interpreted language with elegant syntax and makes an excellent choice for scripting and rapid application development in many areas on most platforms.

Q10. How to use packages and modules in python?

Packages are a way of structuring Python's module namespace by using "dotted module names". For example, the module name A.B designates a submodule named B in a package named A. Just like the use of modules saves the authors of different modules from having to worry about each other's global variable names, the use of dotted module names saves the authors of multi-module packages like NumPy or the Python Imaging Library from having to worry about each other's module names.

Q11. What are the advantages and disadvantages of using Python for web development?

Ans: Advantages of using Python for web development include its ease of use and readability, a large selection of libraries and frameworks (such as Django and Flask), and support for multiple platforms. Disadvantages include potentially slower performance than other languages, and a less mature ecosystem for some types of web development.

Q12. How does Python handle concurrency?

Ans: Python has a built-in module called "threading" that can be used to handle concurrency. The module provides a way to create and manage threads, which are separate execution paths that can run concurrently with the main program. Python also has a "concurrent.futures" module which provides a high-level interface for asynchronously executing callables. The module provides a way to use thread and process pools that can be used to parallelize the execution of a function across multiple input values, using the concurrent.futures.ProcessPoolExecutor or concurrent.futures.ThreadPoolExecutor classes.

Q13. Explain about decorators in python?

Ans: In Python, a decorator is a design pattern to extend the functionality of a function or a class without modifying its source code. A decorator is a function that takes another function as its input and returns a new function that usually extends the behavior of the input function in some way. Decorators are applied to a function or a class using the @ symbol, followed by the decorator function name. They are used to add functionality like logging, authentication, etc.

Q14. What is the use of lambda functions in python?

Ans: A lambda function is a small anonymous function in Python. It can have any number of arguments but only one expression. The expression is evaluated and returned when the function is called. Lambda functions can be used wherever function objects are required. They are used when a small function is required for a short period of time. They are also useful when you need to pass a function as an argument to a higher-order function.

Q15. Explain about the use of generators in python?

Ans: Generators are a way to create iterators in Python. They are used to create an iterator and return the next value from the iterator. The yield statement is used to define a generator function. When a generator function is called, it returns an iterator object. Each time the next() method is called on the iterator, the generator function runs until it encounters a yield statement. At that point, the generator function's state is saved and the value of the expression following the yield statement is returned.

Q16. What is the difference between a tuple and a list in Python?

Ans: The main difference between a tuple and a list in Python is that a tuple is immutable, meaning its elements cannot be modified after it is created, while a list is mutable, meaning its elements can be modified after it is created. Tuples are defined using parentheses, ( ) and are generally used to store related pieces of data, such as a record, whereas lists are defined using square brackets, [] and are used to store a collection of items.

Q17. How does Python handle file input/output operations?

Ans: Python provides a built-in module called "os" and "io" that can be used to handle file input/output operations. The "os" module provides functions for working with the file system, such as creating, renaming, and deleting files and directories. The "io" module provides functions for working with file objects, such as opening, closing, reading, and writing files. Additionally, python also has a built-in "open" function that is used to open a file and returns a file object, which can be used to read or write to the file.

Q18. Explain about the use of sets in python?

Ans: A set is a collection of unique elements in Python. It is defined using curly braces {} or the built-in set() function. Sets are used to store multiple items in a single variable. Sets are used to perform mathematical set operations like union, intersection, symmetric difference, etc. They are also useful when you need to keep track of a collection of elements, but do not need to access the elements by index.

Q19. What is the use of the "zip" function in python?

Ans: The "zip" function in Python takes two or more iterables as arguments and returns an iterator that generates tuples containing elements from each of the input iterables. The function stops when the shortest iterable is exhausted. It is useful for iterating over multiple lists or other iterables in parallel, by combining the elements at corresponding positions into a single tuple.

Q20. How can you create a virtual environment in python?

Ans: In python, you can use the "venv" module to create a virtual environment. To create a virtual environment, you can use the following command:
python -m venv myenv
This will create a new directory called "myenv" in the current directory, which will contain the new virtual environment. To activate the virtual environment, you can use the following command:
source myenv/bin/activate
Once the virtual environment is activated, you can install packages and use them without affecting the global environment.

Q21. Explain about the use of "map" function in python?

Ans: The "map" function in Python is a built-in function that applies a given function to each item of an iterable (list, tuple, etc.) and returns an iterator that generates the results. It takes two arguments, a function and an iterable. The function is applied to each item of the iterable and the results are returned in a new iterator. "map" can be useful when you need to apply a certain operation to each item of a list or other iterable, and want to avoid using a for loop.

Q22. What is the use of "pickle" module in python?

Ans: The "pickle" module in Python is used for serializing and de-serializing Python objects. Serialization is the process of converting an object's state to a byte stream, and de-serialization is the process of recreating the object from a byte stream. The "pickle" module can be used to save an object to a file or to send it over a network connection. It can also be used to convert complex data types such as lists, dictionaries and classes into a string format.

Q23. How does Python handle errors and exceptions?

Ans: In Python, errors and exceptions can be handled using try-except blocks. The code that might raise an exception is placed in the "try" block, and the code that will handle the exception is placed in the "except" block. If an exception is raised in the "try" block, the code in the "except" block will be executed. If no exception is raised, the code in the "except" block will be skipped. Additionally, Python also provides the "finally" block, which is executed regardless of whether an exception is raised or not.

Q24. Explain about the use of "assert" statement in python?

Ans: The "assert" statement in Python is a debugging aid that tests a condition, and triggers an error if the condition is not true. It takes an expression as an argument, and raises an "AssertionError" exception if the expression evaluates to false. The "assert" statement is useful for testing invariants and other conditions that should always be true during the execution of a program. It can be used to check the validity of function inputs and outputs, and to check the internal state of an object during the execution of a method.

Q25. How can you measure the execution time of a python script?

Ans: You can use the built-in "time" module to measure the execution time of a python script. The "time.time()" function returns the current time in seconds since the epoch (January 1, 1970). You can call this function at the beginning and end of the script, and calculate the difference to get the execution time. Additionally, python also provides the "timeit" module which is used for measuring the execution time of small code snippets. It provides a simple way to time the execution of a single statement or a block of statements multiple times.

Q26. How does Python handle memory management?

Ans: Python uses a system called reference counting for memory management. Each object in Python has a reference count, which is the number of variables, data structures, or other objects that refer to it. When a new reference to an object is created, the reference count is incremented. When a reference is deleted, the reference count is decremented. When the reference count for an object reaches zero, the memory for that object is freed by Python's garbage collector. Additionally, Python also uses a technique called cyclic garbage collection to detect and break reference cycles that can cause memory leaks.

Q27. Explain about the use of "itertools" module in python?

Ans: The "itertools" module in Python provides a set of functions that are used to work with iterators. These functions are used to create, modify, and consume iterators. They are very powerful and can be used to perform complex operations with a single line of code. Some of the commonly used functions in itertools are "zip", "chain", "product", "combinations", "permutations" etc. They are used to create new iterators for efficiently working with large amounts of data.

Q28. How does Python handle multiple inheritance?

Ans: Python uses a method resolution order (MRO) algorithm called C3 linearization to handle multiple inheritance. When a class inherits from multiple base classes, the MRO algorithm is used to determine the order in which the base classes will be searched for a method or attribute. The C3 algorithm ensures that the method resolution order is predictable and consistent, and that the correct method is called even in the presence of multiple inheritance.

Q29. Explain about the use of "random" module in python?

Ans: The "random" module in Python is used for generating random numbers and for selecting random elements from a list or other iterable. The module provides functions for generating random numbers from various probability distributions, such as uniform, normal, and exponential. It also provides functions for selecting random elements from a list, shuffling the elements of a list, and other operations. The "random" module can be used in many applications like generating random numbers for games, simulations, and cryptography.

Q30. What is the use of "itertools" module in python?

Ans: The "itertools" module in Python is a collection of functions that are used to work with iterators. It provides functions that can be used to combine multiple iterators, filter elements, and perform other operations on them. The "itertools" module can be used to perform complex operations on large data sets without the need to load them into memory. The module provides functions like "product", "permutations", "combinations" etc., which can be used to perform mathematical set operations on iterable.

Q31. Explain about the use of "datetime" module in python?

Ans: The "datetime" module in Python is used for working with dates and times. It provides classes for manipulating dates and times, and for formatting and parsing date and time strings. The "datetime" module can be used to perform operations like adding and subtracting time, comparing dates, and formatting dates for display. It also provides the "timezone" class which can be used to create timezone-aware datetime objects.

Q32. What is the use of "re" module in python?

The "re" (regular expression) module in Python is used for working with regular expressions. Regular expressions are a powerful tool for matching patterns in text, and the "re" module provides functions for searching, matching, and manipulating strings using regular expressions. The module provides a set of functions such as "search", "findall", "sub", "split", etc. that allows you to perform various operations like searching for a pattern, extracting information, and replacing text. It also provides "compile" function that can be used to pre-compile regular expressions for better performance.

Q33. How do you create a dictionary in Python?

Ans: In Python, a dictionary is created using curly braces {} or the built-in dict() function. The syntax for creating a dictionary is {key1: value1, key2: value2, ...}. A dictionary is a collection of key-value pairs, where each key is unique and is used to access the corresponding value. For example, creating a dictionary of countries and their capital cities, can be done as: {'India': 'New Delhi', 'United States': 'Washington, D.C.', 'Japan': 'Tokyo'}

Q34. What is the difference between "shallow copy" and "deep copy" in Python?

Ans: In Python, a shallow copy of an object is a new object that has the same values as the original object, but the two objects are not connected in any way. A deep copy, on the other hand, creates a new object with its own memory space and copies all the values of the original object into the new object. A shallow copy is faster and requires less memory than a deep copy, but a deep copy ensures that the original object and the copied object do not share any memory and are completely independent.

Q35. How can you remove duplicates from a list in Python?

Ans: In Python, there are several ways to remove duplicates from a list, one of the most common ways is to use the set() function. A set is an unordered collection of unique elements. By converting the list to a set, all duplicates will be removed, and then converting it back to a list. Another way is to use list comprehension, where we iterate over the list and check if an element is already present in the new list, if not we append it.

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

unique_numbers = list(set(numbers))

print(unique_numbers) # Output: [1, 2, 3, 4]

Q36. How to find the intersection of two lists in Python?

Ans: The intersection of two lists is the set of elements that are common to both lists. In Python, we can use the built-in "intersection()" method from the "set" class to find the intersection of two lists. We can also use list comprehension and the "in" operator to find the intersection of two lists. For example, to find the intersection of two lists "list1" and "list2", we can use the following code:

list1 = [1, 2, 3, 4]

list2 = [3, 4, 5, 6]

intersection = list(set(list1) & set(list2))

print(intersection) # Output: [3, 4]

Q37. How to find the union of two lists in Python?

Ans: The union of two lists is the set of elements that are present in either of the lists. In Python, we can use the built-in "union()" method from the "set" class to find the union of two lists. We can also use the "|" operator or list comprehension to find the union of two lists. For example, to find the union of two lists "list1" and "list2", we can use the following code:

list1 = [1, 2, 3, 4]

list2 = [3, 4, 5, 6]

union = list(set(list1) | set(list2))

print(union) # Output: [1, 2, 3, 4, 5, 6]

Q38. How to reverse a list in Python?

Ans: In Python, we can use the built-in "reverse()" method to reverse a list. This method modifies the original list, so we can also use slicing to return a new reversed list without modifying the original one. For example, to reverse a list of numbers, we can use the following code:

numbers = [1, 2, 3, 4]

numbers.reverse()

print(numbers) # Output: [4, 3, 2, 1]

Q39. How to check if a list is empty in Python?

Ans: In Python, we can use the "not" operator and the "len()" function to check if a list is empty. For example, to check if a list "my_list" is empty, we can use the following code:

my_list = []

if not my_list:

    print("The list is empty.")

else:

    print("The list is not empty.")

Q40. How to check if an element exists in a list in Python?

Ans: In Python, we can use the "in" operator to check if an element exists in a list. For example, to check if the number 3 exists in a list of numbers, we can use the following code:

numbers = [1, 2, 3, 4]

if 3 in numbers:

    print("The number 3 exists in the list.")

else:

    print("The number 3 does not exist in the list.")


Post a Comment

0 Comments

Close Menu