0% found this document useful (0 votes)
593 views4 pages

Python Viva Questions and Answers Guide

Top 25 Python Programming Viva Questions

Uploaded by

Akash Deshmukhe
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)
593 views4 pages

Python Viva Questions and Answers Guide

Top 25 Python Programming Viva Questions

Uploaded by

Akash Deshmukhe
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

1.

Basics of Python

1. What is Python?
Python is a high-level, interpreted, and dynamically typed programming language
designed for simplicity and readability. It supports multiple paradigms, including
procedural, object-oriented, and functional programming.

2. What are the key features of Python?

 Easy to learn and use


 Interpreted and dynamically typed
 Extensive standard library
 Cross-platform compatibility
 Supports multiple programming paradigms

3. What is Python used for?


Python is used in web development, data analysis, artificial intelligence, machine
learning, scientific computing, game development, and more.

2. Variables and Data Types

4. What are the data types in Python?

 Numeric types: int, float, complex


 Sequence types: list, tuple, range
 Text type: str
 Set types: set, frozenset
 Mapping type: dict
 Boolean type: bool
 None type: NoneType

5. What is the difference between mutable and immutable objects?

 Mutable: Can be changed after creation (e.g., list, dict, set).


 Immutable: Cannot be changed after creation (e.g., int, float, tuple, str).

6. How is memory managed in Python?


Memory management in Python involves private heap space and automatic garbage
collection, which reclaims unused memory.

3. Control Statements

7. What are control statements in Python?


Control statements direct the flow of execution in a program:
 Conditional statements: if, elif, else
 Loops: for, while
 Control keywords: break, continue, pass

8. What is the difference between break and continue?

 break: Exits the nearest enclosing loop.


 continue: Skips the current iteration and moves to the next iteration of the loop.

4. Functions

9. What is a function in Python?


A function is a reusable block of code that performs a specific task. It is defined using
the def keyword.

10. What are the types of functions in Python?

 Built-in functions: Provided by Python (e.g., print(), len()).


 User-defined functions: Created by users using def.
 Anonymous functions: Created using lambda.

11. What is a lambda function?


A lambda function is an anonymous function defined using the lambda keyword,
useful for short, simple operations.

Example:

add = lambda x, y: x + y
print(add(2, 3)) # Output: 5

5. Object-Oriented Programming

12. What is object-oriented programming in Python?


Object-oriented programming (OOP) organizes code into objects, which are instances
of classes. Key concepts include encapsulation, inheritance, and polymorphism.

13. What is the difference between a class and an object?

 Class: A blueprint for creating objects.


 Object: An instance of a class.

14. What are Python's access specifiers?

 Public: Accessible from anywhere ([Link]).


 Protected: Accessible within the class and its subclasses (self._variable).
 Private: Accessible only within the class (self.__variable).
6. Modules and Packages

15. What is the difference between a module and a package?

 Module: A single Python file containing functions, classes, or variables.


 Package: A collection of modules organized into directories with an __init__.py file.

16. How do you import modules in Python?


Use the import keyword:

import math
print([Link](16)) # Output: 4.0

7. File Handling

17. How does Python handle files?


Python uses built-in functions like open(), read(), write(), and close() for file
operations. File modes include:

 "r": Read
 "w": Write
 "a": Append
 "r+": Read and write

18. What is the difference between read() and readlines()?

 read(): Reads the entire file as a single string.


 readlines(): Reads the file line by line into a list.

8. Exception Handling

19. What is exception handling in Python?


Exception handling manages runtime errors using try, except, else, and finally.

20. How do you raise exceptions in Python?


Use the raise keyword:

if age < 18:


raise ValueError("Age must be 18 or above.")

9. Advanced Concepts

21. What is a decorator in Python?


A decorator is a function that modifies the behavior of another function or method. It
is defined using the @decorator_name syntax.
Example:

def decorator(func):
def wrapper():
print("Before the function call")
func()
print("After the function call")
return wrapper

@decorator
def say_hello():
print("Hello!")

say_hello()

22. What are Python generators?


Generators are functions that yield values one at a time using the yield keyword,
instead of returning all at once.

Example:

def generator():
for i in range(3):
yield i

for value in generator():


print(value)

10. Data Structures

23. What is the difference between a list and a tuple?

 List: Mutable, defined using [].


 Tuple: Immutable, defined using ().

24. What is the difference between a set and a dictionary?

 Set: Unordered collection of unique elements.


 Dictionary: Collection of key-value pairs.

11. Miscellaneous

25. What are Python's key benefits over other programming languages?

 Easy to learn and use


 Extensive libraries and frameworks
 Versatile for various applications
 Active community and support

Common questions

Powered by AI

Python's support for procedural, object-oriented, and functional programming allows developers to choose the best paradigm for a specific task. This flexibility can lead to clearer, more maintainable code by using procedural constructs for straightforward tasks, object-oriented patterns for complex system architecture, and functional approaches for data operations or pipelines .

Python's dynamic typing allows variables to change type during execution, leading to flexible coding practices but potentially increasing memory management complexity. Python handles this by using a private heap space and an automatic garbage collector, ensuring efficient memory usage by reclaiming unused objects .

A lambda function is an anonymous function defined using the `lambda` keyword, designed for short-term use and simple operations. In contrast, a regular function is defined using the `def` keyword, often requiring more lines for definition but capable of more complex and reusable operations with named references .

Extensive use of exception handling could lead to code that masks underlying issues, making debugging difficult. It may also hinder performance if exceptions are used as control flow mechanisms. Properly handling and logging exceptions is crucial to maintaining clarity and ensuring that non-critical errors don't obscure real issues .

A `set` would be more advantageous when you need to store a collection of unique elements, as it automatically removes duplicate entries. Additionally, sets provide faster membership tests and operations like unions or intersections compared to lists due to their underlying hash table implementation .

Decorators modify the behavior of functions or methods, allowing developers to add functionality (such as logging, access control, or modification) without changing the core function code. This promotes code reuse and modularity, as decorators can be applied across multiple functions, separating concerns and reducing repetitive code .

Python's garbage collection keeps memory efficient by reclaiming unused memory, which is beneficial in long-running applications by preventing memory leaks. However, garbage collection algorithms may incur overhead, occasionally causing performance lags. Developers need to manage object references effectively to minimize garbage collection's impact on performance .

Being an interpreted language means Python code runs directly within the interpreter, which can simplify development by allowing for interactive execution and immediate feedback, facilitating rapid prototyping. However, this could impact performance as interpreted code generally runs slower than compiled code. For deployment, dependency management can be challenging across different environments .

The `break` statement exits the nearest enclosing loop immediately, effectively terminating further execution of that loop, while `continue` skips the remaining code in the current loop iteration and proceeds with the next iteration. These controls are crucial for managing loop behavior and flow, allowing for precise execution control within loops .

Encapsulation restricts access to certain components of an object, promoting modular and secure code by exposing only necessary functionalities. Inheritance allows for new classes to inherit properties and methods from existing classes, promoting code reuse and a clearer hierarchy. These OOP concepts aid in constructing robust, scalable Python programs by encouraging a structured approach .

You might also like