0% found this document useful (0 votes)
3 views

Python viva answers

The document provides a comprehensive overview of Python programming, covering basic, intermediate, and advanced questions related to its features, applications, and functionalities. It includes explanations of Python's data types, control structures, memory management, and libraries, as well as its role in various domains like AI and data science. Additionally, it highlights Python's significance in the Indian education system and its applications in business and industry.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Python viva answers

The document provides a comprehensive overview of Python programming, covering basic, intermediate, and advanced questions related to its features, applications, and functionalities. It includes explanations of Python's data types, control structures, memory management, and libraries, as well as its role in various domains like AI and data science. Additionally, it highlights Python's significance in the Indian education system and its applications in business and industry.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Basic Python Questions

1. What is Python? List some popular applications of Python.

o Python is a high-level, interpreted programming language known for its simplicity


and readability. Popular applications include web development (Django, Flask), data
science (Pandas, NumPy), artificial intelligence (TensorFlow, PyTorch), automation,
and scripting.

2. What are the benefits of using Python in the present scenario?

o Easy to learn, versatile, large standard library, strong community support, cross-
platform compatibility, and extensive use in AI, data science, and automation.

3. Is Python a compiled language or an interpreted language? Explain.

o Python is an interpreted language, meaning the code is executed line by line by the
Python interpreter.

4. What is a dynamically typed language?

o In a dynamically typed language, variable types are determined at runtime, and you
don’t need to declare the type of a variable explicitly.

5. What does the ‘#’ symbol do in Python?

o The # symbol is used for single-line comments in Python.

6. What is the difference between a mutable and an immutable data type?

o Mutable data types can be changed after creation (e.g., lists, dictionaries), while
immutable data types cannot be changed (e.g., strings, tuples).

7. How are arguments passed in Python – by value or by reference?

o Arguments are passed by object reference in Python. If the object is mutable,


changes affect the original object; if immutable, changes do not affect the original
object.

8. What is the difference between a Set and a Dictionary?

o A set is an unordered collection of unique elements, while a dictionary is a collection


of key-value pairs.

9. What is List Comprehension? Give an example.

o List comprehension is a concise way to create lists. Example: [x**2 for x in


range(10)].

10. How is a dictionary different from a list?

o A dictionary stores data in key-value pairs and is unordered, while a list stores
ordered elements accessed by indices.

11. What is the purpose of the pass statement in Python?

o The pass statement is a null operation used as a placeholder where syntactically


some code is required but no action is needed.
12. What is the difference between / and // operators in Python?

o / performs floating-point division, while // performs integer division (floor division).

13. How is exception handling done in Python?

o Using try, except, finally, and raise statements to handle and manage errors.

14. What is a lambda function? Give an example.

o A lambda function is an anonymous function defined with the lambda keyword.


Example: lambda x: x**2.

15. What is the difference between a for loop and a while loop?

o A for loop iterates over a sequence, while a while loop continues as long as a
condition is true.

16. Can we pass a function as an argument in Python? How?

o Yes, functions are first-class objects in Python, so they can be passed as arguments to
other functions.

17. **What are *args and kwargs?

o *args allows you to pass a variable number of positional arguments,


while **kwargs allows you to pass a variable number of keyword arguments.

18. Is indentation required in Python? Why?

o Yes, indentation is required to define blocks of code, replacing the use of braces {} in
other languages.

19. What is variable scope in Python? Explain its types.

o Variable scope defines where a variable can be accessed. Types include local (inside a
function), global (outside functions), and nonlocal (in nested functions).

20. What is a docstring in Python? How can we access it?

o A docstring is a string literal used to document a module, function, or class. It can be


accessed using __doc__ or the help() function.

Intermediate Python Questions

21. What is the difference between break, continue, and pass in Python?

o break exits the loop, continue skips the current iteration, and pass is a placeholder
that does nothing.

22. What are the built-in data types in Python?

o int, float, str, list, tuple, set, dict, bool, etc.

23. How do you floor a number in Python?

o Using the math.floor() function or the // operator.


24. What is the difference between xrange() and range()?

o xrange() (Python 2) returns a generator, while range() (Python 3) returns a list-like


object.

25. What is Dictionary Comprehension? Give an example.

o Dictionary comprehension is a concise way to create dictionaries. Example: {x: x**2


for x in range(5)}.

26. Is Tuple Comprehension possible in Python? Why or why not?

o No, because tuples are immutable. However, you can use generator expressions.

27. Differentiate between a List and a Tuple.

o Lists are mutable, while tuples are immutable.

28. What is the difference between a shallow copy and a deep copy?

o A shallow copy creates a new object but references the same elements, while a deep
copy creates a new object with new elements.

29. Which sorting technique is used by sort() and sorted() functions in Python?

o Timsort, a hybrid sorting algorithm derived from merge sort and insertion sort.

30. What are decorators in Python?

o Decorators are functions that modify the behavior of other functions or methods.

31. How do you debug a Python program?

o Using the pdb module, print statements, or IDE debuggers.

32. What are iterators in Python?

o Iterators are objects that allow traversal through all elements of a collection,
implementing __iter__() and __next__().

33. What are generators in Python?

o Generators are functions that yield values lazily using the yield keyword.

34. Does Python support multiple inheritance? Explain.

o Yes, Python supports multiple inheritance, where a class can inherit from more than
one parent class.

35. What is polymorphism in Python?

o Polymorphism allows methods to behave differently based on the object that calls
them.

36. Define encapsulation in Python.

o Encapsulation is the bundling of data and methods that operate on the data within a
single unit (class).
37. How do you achieve data abstraction in Python?

o Using abstract classes and interfaces to hide implementation details.

38. How is memory management handled in Python?

o Python uses automatic memory management with a garbage collector to reclaim


unused memory.

39. How can you delete a file using Python?

o Using os.remove("filename").

40. What is slicing in Python? Provide an example.

o Slicing extracts a portion of a sequence. Example: my_list[1:4].

41. What is a namespace in Python?

o A namespace is a mapping from names to objects, such as variables, functions, and


classes.

Advanced Python Questions

42. What is PIP in Python?

o PIP is the package installer for Python, used to install and manage libraries.

43. What is the zip() function in Python?

o The zip() function combines multiple iterables into a single iterable of tuples.

44. What are pickling and unpickling?

o Pickling is the process of converting Python objects into a byte stream, and
unpickling is the reverse process.

45. What is the difference between @classmethod, @staticmethod, and instance methods?

o @classmethod works with the class, @staticmethod doesn’t depend on the class or
instance, and instance methods work with the instance.

46. What is the init() method in Python? What is its role?

o The __init__() method is a constructor that initializes an object when it is created.

47. Write a code snippet to display the current time in Python.

python

Copy

from datetime import datetime

print(datetime.now())

48. What are access specifiers in Python? Explain their types.


o Python doesn’t have strict access specifiers, but conventions like _ (protected)
and __ (private) are used.

49. What are unit tests in Python?

o Unit tests are used to test individual components of a program, typically using
the unittest module.

50. What is the Python Global Interpreter Lock (GIL)?

o The GIL is a mutex that prevents multiple threads from executing Python bytecode
simultaneously.

51. What are function annotations in Python?

o Function annotations provide metadata about the types of arguments and return
values.

52. What is metaprogramming in Python?

o Metaprogramming involves writing programs that manipulate other programs or


themselves.

53. What is monkey patching in Python?

o Monkey patching is dynamically modifying or extending classes or modules at


runtime.

54. How does Python handle memory management internally?

o Python uses a private heap for memory management and a garbage collector to
reclaim unused memory.

55. How do you implement a stack and a queue in Python?

o Stack: Use a list with append() and pop(). Queue: Use collections.deque.

56. What is the difference between is and == operators?

o is checks for identity (same object), while == checks for equality (same value).

57. What is the purpose of the with statement in Python?

o The with statement is used for resource management, ensuring proper acquisition
and release of resources.

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

o Shallow copy creates a new object but references the same elements, while deep
copy creates a new object with new elements.

59. What is the difference between JSON and Pickle in Python?

o JSON is a text-based format for serialization, while Pickle is a binary format specific
to Python.

60. Explain how Python’s garbage collection works.


o Python uses reference counting and a cyclic garbage collector to reclaim memory.

61. How can we create a virtual environment in Python?

o Use python -m venv env_name.

62. What are Python modules and packages?

o A module is a single Python file, while a package is a collection of modules in a


directory.

63. What is the difference between import module and from module import function?

o import module imports the entire module, while from module import
function imports a specific function.

64. What is the purpose of the super() function in Python?

o The super() function is used to call methods from a parent class.

65. What is duck typing in Python?

o Duck typing is a concept where the type of an object is determined by its behavior
rather than its class.

66. What is method overloading and method overriding in Python?

o Method overloading is not directly supported in Python, but method overriding


allows a subclass to provide a specific implementation of a method.

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

o Python 3 has better Unicode support, syntax improvements, and removed redundant
constructs.

68. How can we handle missing values in a dataset using Python?

o Using libraries like Pandas, you can use fillna(), dropna(), or interpolation.

69. How does Python support functional programming?

o Python supports functional programming with features like lambda functions, map,
filter, and reduce.

70. What are named tuples in Python?

o Named tuples are tuple subclasses with named fields, created


using collections.namedtuple.

71. What is the purpose of the enum module in Python?

o The enum module provides support for enumerations, which are sets of symbolic
names bound to unique values.

72. How can we generate random numbers in Python?

o Using the random module, e.g., random.randint().

73. What are f-strings in Python?


o F-strings are formatted string literals that allow embedded expressions inside curly
braces.

74. How can we merge two dictionaries in Python?

o Using the update() method or the {**dict1, **dict2} syntax.

75. What is the difference between the sorted() function and the sort() method?

o sorted() returns a new sorted list, while sort() sorts the list in place.

76. How can we count occurrences of a particular element in a list?

o Using the count() method, e.g., my_list.count(element).

77. How does Python implement multi-threading?

o Python uses the threading module, but due to the GIL, it is not suitable for CPU-
bound tasks.

78. What is the difference between multiprocessing and multithreading in Python?

o Multiprocessing uses separate memory spaces, while multithreading shares memory


space.

79. How can we read and write CSV files in Python?

o Using the csv module or libraries like Pandas.

80. What is the difference between os and sys modules in Python?

o The os module provides functions for interacting with the operating system,
while sys provides access to system-specific parameters.

81. What is itertools in Python?

o itertools is a module that provides functions for creating iterators for efficient
looping.

82. How do you use the map() function in Python?

o The map() function applies a function to all items in an iterable.


Example: map(lambda x: x**2, [1, 2, 3]).

83. What is the purpose of the filter() function in Python?

o The filter() function filters elements based on a condition. Example: filter(lambda x: x


> 2, [1, 2, 3]).

84. How does the reduce() function work in Python?

o The reduce() function applies a function cumulatively to the items of an iterable.


Example: reduce(lambda x, y: x + y, [1, 2, 3]).

85. What is the collections module in Python?

o The collections module provides specialized container datatypes


like Counter, defaultdict, and deque.
86. What is the difference between Counter and defaultdict in Python?

o Counter counts hashable objects, while defaultdict provides default values for
missing keys.

87. What is the difference between time.sleep() and threading.sleep()?

o time.sleep() pauses the entire program, while threading.sleep() pauses only the
current thread.

88. How can we make an API call using Python?

o Using libraries like requests. Example: requests.get("https://api.example.com").

89. How do we send an email using Python?

o Using the smtplib module.

90. How can we scrape websites using Python?

o Using libraries like BeautifulSoup and requests.

91. How can we perform unit testing using unittest in Python?

o By creating test cases that inherit from unittest.TestCase and using methods
like assertEqual().

92. How can we use Python for database operations?

o Using libraries like sqlite3, psycopg2, or ORMs like SQLAlchemy.

93. What is the purpose of the sqlite3 module in Python?

o The sqlite3 module provides an interface for working with SQLite databases.

94. How does Python handle file handling operations?

o Using built-in functions like open(), read(), write(), and close().

95. How can we execute shell commands using Python?

o Using the subprocess module.

96. What is the subprocess module in Python?

o The subprocess module allows you to spawn new processes and interact with them.

97. How can we serialize and deserialize objects using Python?

o Using the pickle module or JSON.

98. How can we work with dates and times in Python?

o Using the datetime module.

99. What is the re module used for in Python?

o The re module provides support for regular expressions.


100. How do we use regular expressions in Python?
- Using the re module, e.g., re.search(pattern, string).

Miscellaneous Questions

101. What are some real-world applications of Python in India?


- Python is used in web development, data analysis, AI, machine learning, and automation in
industries like IT, finance, and healthcare.

102. How is Python used in the Indian education system?


- Python is taught in schools and colleges as a beginner-friendly programming language and
is used in research and data analysis.

103. What role does Python play in AI and data science in India?
- Python is the leading language for AI and data science due to its extensive libraries like
TensorFlow, PyTorch, and Pandas.

104. How can Python help in developing software solutions for Indian businesses?
- Python can automate processes, analyze data, and build scalable web applications for
businesses.

105. What are the career prospects for Python programmers in India?
- Python programmers are in high demand in fields like software development, data science,
AI, and automation.

106. How can Python be used in automating government processes in India?


- Python can automate data processing, reporting, and decision-making in government
systems.

107. How does Python compare with Java in terms of popularity in India?
- Python is more popular for data science and AI, while Java is widely used in enterprise
applications.

108. What are some popular Python communities and meetups in India?
- PyCon India, Python Pune, and Bangalore Python User Group are popular communities.

You might also like