0% found this document useful (0 votes)
5 views12 pages

Python Viva Questions

This document contains a comprehensive list of practical viva questions and answers related to Python programming. It covers fundamental concepts such as data types, functions, exception handling, and modules, as well as advanced topics like decorators, generators, and concurrency. Each question is followed by a concise answer, making it a useful resource for learning and revision.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views12 pages

Python Viva Questions

This document contains a comprehensive list of practical viva questions and answers related to Python programming. It covers fundamental concepts such as data types, functions, exception handling, and modules, as well as advanced topics like decorators, generators, and concurrency. Each question is followed by a concise answer, making it a useful resource for learning and revision.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 12

PYTHON PRACTICAL VIVA QUESTIONS AND ANSWERS

1. What is Python?
Answer: Python is a high-level, interpreted, interactive, and object-oriented
programming language. It is known for its simplicity and readability.

2. What are the key features of Python?


Answer:
- Easy to learn and use
- Interpreted language
- Cross-platform compatibility
- Extensive standard library
- Supports multiple programming paradigms
- Dynamic typing
- Automatic memory management

3. What is PEP 8?
Answer: PEP 8 is Python's style guide that provides coding conventions for writing
readable Python code. It covers naming conventions, code layout, and other aspects
of coding style.

4. What are Python data types?


Answer: Python has several built-in data types:
- Numbers (int, float, complex)
- Strings
- Lists
- Tuples
- Sets
- Dictionaries
- Boolean

5. What is the difference between list and tuple?


Answer:
- Lists are mutable (can be modified)
- Tuples are immutable (cannot be modified)
- Lists use square brackets []
- Tuples use parentheses ()
- Lists are generally used for homogeneous data
- Tuples are used for heterogeneous data

6. What is a dictionary in Python?


Answer: A dictionary is an unordered collection of key-value pairs. It is mutable
and indexed by keys. Example:
my_dict = {'name': 'John', 'age': 25}

7. What are Python functions?


Answer: Functions are blocks of organized, reusable code that perform a specific
task. They are defined using the 'def' keyword.

8. What is the difference between local and global variables?


Answer:
- Local variables are defined inside a function and can only be used within that
function
- Global variables are defined outside functions and can be accessed throughout the
program

9. What are Python modules?


Answer: Modules are files containing Python code that can be imported and used in
other Python programs. They help in organizing code and reusing functionality.
10. What is exception handling in Python?
Answer: Exception handling is a way to handle errors that occur during program
execution. It uses try, except, else, and finally blocks.

11. What is the difference between '==' and 'is'?


Answer:
- '==' compares the values of two objects
- 'is' compares the identity (memory location) of two objects

12. What are Python decorators?


Answer: Decorators are functions that modify the behavior of other functions. They
are used to add functionality to existing code without modifying it.

13. What is list comprehension?


Answer: List comprehension is a concise way to create lists. Example:
squares = [x**2 for x in range(10)]

14. What is the difference between append() and extend() in lists?


Answer:
- append() adds a single element to the end of the list
- extend() adds multiple elements (from another list) to the end of the list

15. What is the use of lambda functions?


Answer: Lambda functions are anonymous functions defined using the lambda keyword.
They are used for simple operations. Example:
square = lambda x: x**2

16. What is the difference between deep copy and shallow copy?
Answer:
- Shallow copy creates a new object but references the same nested objects
- Deep copy creates a completely independent copy of the object and all its nested
objects

17. What are Python generators?


Answer: Generators are functions that return an iterator. They use the yield
keyword instead of return and can maintain their state between calls.

18. What is the use of __init__ in Python?


Answer: __init__ is a special method in Python classes that is automatically called
when an object is created. It is used to initialize the object's attributes.

19. What is inheritance in Python?


Answer: Inheritance is a mechanism where a new class (child class) can inherit
attributes and methods from an existing class (parent class).

20. What is method overriding?


Answer: Method overriding occurs when a child class provides a specific
implementation of a method that is already defined in its parent class.

21. What is the use of super() in Python?


Answer: super() is used to call methods from the parent class in inheritance.

22. What are Python packages?


Answer: Packages are a way of organizing related modules into a directory
hierarchy.

23. What is the difference between break and continue?


Answer:
- break exits the loop completely
- continue skips the current iteration and moves to the next one

24. What is the use of pass statement?


Answer: pass is a null operation that does nothing. It is used as a placeholder
when a statement is required syntactically but no action is needed.

25. What is the difference between str() and repr()?


Answer:
- str() returns a human-readable string representation
- repr() returns an official string representation that can be used to recreate the
object

26. What is the use of __name__ == '__main__'?


Answer: This condition checks if the Python file is being run directly or being
imported as a module. Code under this condition only runs when the file is executed
directly.

27. What are Python iterators?


Answer: Iterators are objects that can be iterated upon. They implement the
iterator protocol with __iter__() and __next__() methods.

28. What is the difference between class method and static method?
Answer:
- Class methods take cls as first parameter and can access class variables
- Static methods don't take any special first parameter and can't access class
variables

29. What is the use of @property decorator?


Answer: @property decorator is used to define getter methods for class attributes,
allowing controlled access to them.

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


Answer:
- Print statement vs print function
- Integer division behavior
- Unicode support
- xrange vs range
- Exception handling syntax
- Input function behavior

31. What is the use of map() function?


Answer: map() applies a function to all items in an input list. Example:
result = map(lambda x: x*2, [1,2,3])

32. What is the use of filter() function?


Answer: filter() creates a list of elements for which a function returns true.
Example:
result = filter(lambda x: x%2==0, [1,2,3,4])

33. What is the use of reduce() function?


Answer: reduce() applies a rolling computation to sequential pairs of values in a
list. Example:
from functools import reduce
result = reduce(lambda x,y: x+y, [1,2,3,4])

34. What is the use of zip() function?


Answer: zip() combines multiple iterables into a single iterable of tuples.
Example:
result = zip([1,2,3], ['a','b','c'])

35. What is the use of enumerate() function?


Answer: enumerate() adds a counter to an iterable. Example:
for index, value in enumerate(['a','b','c']):
print(index, value)

36. What is the use of any() and all() functions?


Answer:
- any() returns True if any element of the iterable is true
- all() returns True if all elements of the iterable are true

37. What is the use of sorted() function?


Answer: sorted() returns a new sorted list from the items in an iterable. Example:
sorted([3,1,2]) returns [1,2,3]

38. What is the use of reversed() function?


Answer: reversed() returns a reverse iterator. Example:
list(reversed([1,2,3])) returns [3,2,1]

39. What is the use of format() method?


Answer: format() formats the specified value(s) and inserts them inside the
string's placeholder. Example:
"Hello {0}".format("World")

40. What is the use of join() method?


Answer: join() joins elements of a sequence with a string separator. Example:
",".join(['a','b','c']) returns "a,b,c"

41. What is the use of split() method?


Answer: split() splits a string into a list where each word is a list item.
Example:
"a b c".split() returns ['a','b','c']

42. What is the use of strip() method?


Answer: strip() removes leading and trailing whitespace from a string. Example:
" hello ".strip() returns "hello"

43. What is the use of replace() method?


Answer: replace() replaces a specified phrase with another specified phrase.
Example:
"Hello World".replace("World", "Python")

44. What is the use of find() method?


Answer: find() returns the index of the first occurrence of the specified value.
Example:
"Hello".find("e") returns 1

45. What is the use of count() method?


Answer: count() returns the number of times a specified value appears in the
string. Example:
"Hello".count("l") returns 2

46. What is the use of index() method?


Answer: index() finds the first occurrence of the specified value. Example:
[1,2,3].index(2) returns 1

47. What is the use of pop() method?


Answer: pop() removes the element at the specified position. Example:
[1,2,3].pop(1) returns 2 and the list becomes [1,3]

48. What is the use of remove() method?


Answer: remove() removes the first occurrence of the element with the specified
value. Example:
[1,2,3,2].remove(2) makes the list [1,3,2]

49. What is the use of insert() method?


Answer: insert() adds an element at the specified position. Example:
[1,2,3].insert(1,4) makes the list [1,4,2,3]

50. What is the use of clear() method?


Answer: clear() removes all elements from the list. Example:
[1,2,3].clear() makes the list []

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


Answer: In Python 2, range() returns a list while xrange() returns an iterator. In
Python 3, range() behaves like xrange() in Python 2.

52. What is the use of *args and **kwargs?


Answer:
- *args allows passing variable number of positional arguments
- **kwargs allows passing variable number of keyword arguments
Example:
def func(*args, **kwargs):
print(args) # tuple of positional arguments
print(kwargs) # dictionary of keyword arguments

53. What is the use of __str__ and __repr__ methods?


Answer:
- __str__ is called by str() and print() to get a user-friendly string
representation
- __repr__ is called by repr() to get an official string representation

54. What is the use of __call__ method?


Answer: __call__ allows an instance of a class to be called as a function. Example:
class Adder:
def __call__(self, x, y):
return x + y
add = Adder()
result = add(5, 3) # returns 8

55. What is the use of __getitem__ and __setitem__?


Answer:
- __getitem__ allows accessing elements using index notation ([])
- __setitem__ allows assigning values using index notation
Example:
class MyList:
def __getitem__(self, index):
return self.data[index]

56. What is the use of __iter__ and __next__?


Answer:
- __iter__ returns an iterator object
- __next__ returns the next item in the sequence
Example:
class Counter:
def __init__(self, low, high):
self.current = low
self.high = high
def __iter__(self):
return self
def __next__(self):
if self.current > self.high:
raise StopIteration
else:
self.current += 1
return self.current - 1

57. What is the use of __enter__ and __exit__?


Answer: These methods are used to implement context managers (with statement).
Example:
class File:
def __enter__(self):
return self.file
def __exit__(self, type, value, traceback):
self.file.close()

58. What is the use of @classmethod decorator?


Answer: @classmethod defines a method that receives the class as the first argument
(cls). Example:
class MyClass:
@classmethod
def class_method(cls):
print(cls.__name__)

59. What is the use of @staticmethod decorator?


Answer: @staticmethod defines a method that doesn't receive any special first
argument. Example:
class MyClass:
@staticmethod
def static_method():
print("This is a static method")

60. What is the use of @abstractmethod?


Answer: @abstractmethod is used to define abstract methods in abstract base
classes. Example:
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass

61. What is the use of collections module?


Answer: The collections module provides specialized container datatypes:
- Counter: counts hashable objects
- defaultdict: dictionary with default values
- OrderedDict: dictionary that remembers insertion order
- namedtuple: tuple with named fields

62. What is the use of itertools module?


Answer: itertools provides functions for creating iterators:
- count(): infinite counter
- cycle(): cycle through iterable
- repeat(): repeat value
- combinations(): combinations of elements
- permutations(): permutations of elements
63. What is the use of functools module?
Answer: functools provides higher-order functions:
- reduce(): reduce sequence to single value
- partial(): partial function application
- wraps(): preserve function metadata
- lru_cache(): memoization decorator

64. What is the use of contextlib module?


Answer: contextlib provides utilities for working with context managers:
- contextmanager: decorator for creating context managers
- closing: context manager for closing objects
- suppress: context manager for suppressing exceptions

65. What is the use of dataclasses?


Answer: dataclasses automatically add special methods to classes:
- __init__: initialization
- __repr__: string representation
- __eq__: equality comparison
Example:
from dataclasses import dataclass
@dataclass
class Point:
x: float
y: float

66. What is the use of type hints?


Answer: Type hints add type information to Python code:
- Improves code readability
- Enables better IDE support
- Helps catch type-related errors
Example:
def greet(name: str) -> str:
return f"Hello, {name}"

67. What is the use of asyncio?


Answer: asyncio provides infrastructure for writing single-threaded concurrent
code:
- Coroutines
- Event loop
- Tasks
- Futures
Example:
import asyncio
async def main():
print('Hello')
await asyncio.sleep(1)
print('World')

68. What is the use of multiprocessing?


Answer: multiprocessing provides process-based parallelism:
- Process: spawn processes
- Pool: process pool
- Queue: inter-process communication
- Pipe: bidirectional communication

69. What is the use of threading?


Answer: threading provides thread-based parallelism:
- Thread: create threads
- Lock: mutual exclusion
- Event: thread synchronization
- Semaphore: limited resource access

70. What is the use of concurrent.futures?


Answer: concurrent.futures provides high-level interface for asynchronously
executing callables:
- ThreadPoolExecutor: thread-based execution
- ProcessPoolExecutor: process-based execution
- Future: represents computation result

71. What is the use of logging module?


Answer: logging provides flexible event logging:
- Loggers: entry points
- Handlers: send logs to destinations
- Formatters: format log messages
- Filters: filter log records

72. What is the use of unittest?


Answer: unittest provides testing framework:
- TestCase: base class for tests
- TestSuite: collection of tests
- TestRunner: runs tests
- Assertions: test conditions

73. What is the use of pytest?


Answer: pytest is a testing framework that:
- Uses simple assert statements
- Provides fixtures
- Supports parameterized testing
- Has rich plugin ecosystem

74. What is the use of doctest?


Answer: doctest tests code examples in docstrings:
- Extracts examples from docstrings
- Runs examples as tests
- Verifies output matches expected
Example:
def square(x):
"""Return the square of x.
>>> square(2)
4
>>> square(-2)
4
"""
return x * x

75. What is the use of pathlib?


Answer: pathlib provides object-oriented filesystem paths:
- Path: represents filesystem path
- PurePath: abstract path
- ConcretePath: actual path
Example:
from pathlib import Path
p = Path('file.txt')
p.write_text('Hello')

76. What is the use of json module?


Answer: json provides JSON serialization:
- dumps(): convert to JSON string
- loads(): parse JSON string
- dump(): write to file
- load(): read from file

77. What is the use of pickle module?


Answer: pickle provides Python object serialization:
- dump(): serialize to file
- load(): deserialize from file
- dumps(): serialize to bytes
- loads(): deserialize from bytes

78. What is the use of csv module?


Answer: csv provides CSV file handling:
- reader(): read CSV file
- writer(): write CSV file
- DictReader(): read as dictionary
- DictWriter(): write from dictionary

79. What is the use of sqlite3 module?


Answer: sqlite3 provides SQLite database interface:
- Connection: database connection
- Cursor: execute SQL commands
- execute(): run SQL statement
- fetchall(): get all results

80. What is the use of datetime module?


Answer: datetime provides date and time handling:
- date: date object
- time: time object
- datetime: date and time
- timedelta: time difference

81. What is the use of random module?


Answer: random provides random number generation:
- random(): random float
- randint(): random integer
- choice(): random element
- shuffle(): randomize sequence

82. What is the use of math module?


Answer: math provides mathematical functions:
- sqrt(): square root
- sin(): sine
- cos(): cosine
- pi: π constant

83. What is the use of statistics module?


Answer: statistics provides statistical functions:
- mean(): arithmetic mean
- median(): median
- mode(): mode
- stdev(): standard deviation

84. What is the use of re module?


Answer: re provides regular expressions:
- search(): find pattern
- match(): match at start
- findall(): find all matches
- sub(): replace matches
85. What is the use of urllib module?
Answer: urllib provides URL handling:
- request: open URLs
- parse: parse URLs
- error: handle errors
- robotparser: parse robots.txt

86. What is the use of requests module?


Answer: requests provides HTTP client:
- get(): GET request
- post(): POST request
- put(): PUT request
- delete(): DELETE request

87. What is the use of socket module?


Answer: socket provides network interface:
- socket(): create socket
- bind(): bind to address
- listen(): listen for connections
- accept(): accept connection

88. What is the use of ssl module?


Answer: ssl provides SSL/TLS support:
- wrap_socket(): wrap socket
- create_default_context(): create context
- CERT_REQUIRED: require certificate
- PROTOCOL_TLS: TLS protocol

89. What is the use of subprocess module?


Answer: subprocess provides process creation:
- run(): run command
- Popen(): create process
- call(): call command
- check_output(): get output

90. What is the use of os module?


Answer: os provides OS interface:
- getcwd(): current directory
- listdir(): list directory
- mkdir(): make directory
- remove(): remove file

91. What is the use of sys module?


Answer: sys provides system-specific parameters:
- argv: command line arguments
- path: module search path
- version: Python version
- exit(): exit program

92. What is the use of argparse module?


Answer: argparse provides command-line argument parsing:
- ArgumentParser: create parser
- add_argument(): add argument
- parse_args(): parse arguments
- help: help message

93. What is the use of configparser module?


Answer: configparser provides configuration file parsing:
- ConfigParser: create parser
- read(): read file
- get(): get value
- set(): set value

94. What is the use of tempfile module?


Answer: tempfile provides temporary file handling:
- TemporaryFile(): temporary file
- NamedTemporaryFile(): named temp file
- mkstemp(): create temp file
- mkdtemp(): create temp directory

95. What is the use of shutil module?


Answer: shutil provides high-level file operations:
- copy(): copy file
- move(): move file
- rmtree(): remove tree
- make_archive(): create archive

96. What is the use of glob module?


Answer: glob provides filename pattern matching:
- glob(): find files
- iglob(): iterator version
- escape(): escape special characters
Example:
import glob
files = glob.glob('*.txt')

97. What is the use of fnmatch module?


Answer: fnmatch provides filename pattern matching:
- fnmatch(): match filename
- filter(): filter names
- translate(): convert pattern
Example:
import fnmatch
if fnmatch.fnmatch('file.txt', '*.txt'):
print('Match')

98. What is the use of linecache module?


Answer: linecache provides line-by-line file reading:
- getline(): get line
- clearcache(): clear cache
- checkcache(): check cache
Example:
import linecache
line = linecache.getline('file.txt', 1)

99. What is the use of difflib module?


Answer: difflib provides helpers for computing deltas:
- Differ(): compare lines
- unified_diff(): unified diff
- context_diff(): context diff
- get_close_matches(): similar strings

100. What is the use of pprint module?


Answer: pprint provides pretty-printing:
- pprint(): pretty print
- pformat(): format string
- PrettyPrinter(): create printer
Example:
from pprint import pprint
data = {'a': 1, 'b': 2}
pprint(data)

Remember to practice these concepts and be prepared to explain them in detail


during your viva. Good luck with your exam!

You might also like