0% found this document useful (0 votes)
2 views15 pages

Python Lab Viva Que

The document provides a comprehensive overview of Python, covering its key features, data types, and programming concepts such as object-oriented programming, functions, and exception handling. It explains various Python constructs like lists, dictionaries, decorators, and generators, as well as differences between Python 2 and 3. Additionally, it discusses memory management, the Global Interpreter Lock, and unit testing, making it a valuable resource for understanding Python programming.

Uploaded by

myself.dutt24
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)
2 views15 pages

Python Lab Viva Que

The document provides a comprehensive overview of Python, covering its key features, data types, and programming concepts such as object-oriented programming, functions, and exception handling. It explains various Python constructs like lists, dictionaries, decorators, and generators, as well as differences between Python 2 and 3. Additionally, it discusses memory management, the Global Interpreter Lock, and unit testing, making it a valuable resource for understanding Python programming.

Uploaded by

myself.dutt24
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/ 15

Q 1. What is Python?

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.

Q 2. What are the key features of Python?

Features of Python

Easy syntax and readability

Interpreted and dynamically typed

Supports object-oriented, functional, and procedural programming

Large standard library

Cross-platform compatibility

Q 3. What is PEP 8?

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.

Q 4. What are Python's data types?

Python's data types

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

Q5. What are lists and tuples in Python?

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.
Example

my_list = [1, 2, 3, "hello"] # A list with mixed data types

my_list.append(4) # Adds an element

print(my_list)

Try it Yourself >>

Output

[1, 2, 3, 'hello', 4]

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.

Tuples in python

Example

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

Output

(1, 2, 3, 'world')

Q 6. What is a dictionary in Python?

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 { }.

dictionary in Python

Example

# Creating a dictionary

person = {

"name": "Aman",

"age": 25,

"city": "New York"

}
# Accessing dictionary elements

print("Name:", person["name"])

print("Age:", person["age"])

print("City:", person["city"])

# 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"])

# Removing a key-value pair

del person["city"]

print("After removal:", person)

# Looping through dictionary keys and values

for key, value in person.items():

print(f"{key}: {value}")

# Checking if a key exists

if "name" in person:

print("Name exists in the dictionary.")

# Getting all keys and values

keys = person.keys()
values = person.values()

print("Keys:", keys)

print("Values:", values)

# Merging dictionaries

additional_info = {"hobbies": ["Reading", "Traveling"], "age": 27}

person.update(additional_info)

print("Merged dictionary:", person)

Try it Yourself >>

Output

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 7. What is the difference between deepcopy() and shallow copy()?

The main difference between deepcopy() and shallow copy() are:

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?

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.

Q 9. What is the difference between range() and xrange() in Python?

The difference betweenrange() and xrange() in Python:Fvar

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.

Q 10. What are Lambda functions?

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.

Example

# A lambda function to find the square of a number

square = lambda x: x ** 2

print("Square of 5:", square(5))

Try it Yourself >>

Output

Square of 5: 25

Q 11. What is an iterator in Python?

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__().

Q 12. What is the difference between is and == in Python?

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).

Q 13. What are decorators in Python?

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.
Q 14. What is the purpose of self in Python?

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.

Q 15. What are Python modules and packages?

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.

Q 16. What is a class in Python?

class in Python

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?

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.

Q 18. What is the difference between append() and extend() 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.

Q 19. What is the use of the with statement in Python?

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.

Q20. What are list comprehensions in Python?

list comprehensions in Python

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.

Example

# 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)

Try it Yourself >>

Output

Squared Numbers: [1, 4, 9, 16, 25]

Q 21. What is the difference between Python 2 and Python 3?

Python 2 and Python 3 have several differences. Some key differences include:

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.

Q 22. How does Python handle memory management?

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.

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 24. What is the difference between a method and a function in Python?

The difference between a method and a function in Python:

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.

Q 25. What are Python decorators, and how do they work?

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.
Q 26. What are Python generators, and how do they differ from iterators?

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 27. What is the difference between @staticmethod and @classmethod?

@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.

Q 28. How can you handle multiple exceptions in Python?

Multiple exceptions can be handled using a single except block by specifying them in a tuple.
For example:

try:

# some code

except (TypeError, ValueError) as e:

print(f"Error: {e}")

Q 29. What are Python’s built-in data structures?

Python’s built-in data structures

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)

Q 30. Explain the with statement in Python.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 31. What is the difference between del and remove() in Python?

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.

Q 32. What are Python’s built-in modules?

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

collections for specialized data structures like deque, Counter, etc.

Q 33. What is the difference between __str__() and __repr__() in Python?

__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.

Q 34. What is the finally block in exception handling?

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.

Q 35. What is the purpose of the super() function 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 often used to extend or modify the behavior
of inherited methods.

Q 36. What is the isinstance() function used for?

The isinstance() function is used to check if an object is an instance or subclass of a


particular class. Example:

isinstance(obj, ClassName)
Q 37. What are list comprehensions, and how do they work in Python

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:

squares = [x**2 for x in range(10) if x % 2 == 0]

Q 38. How do you perform unit testing in Python?

Unit testing in Python is commonly done using the built-in unittest module.

Steps to perform unit testing in Python:

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.

Q 39. What are the differences between staticmethod and class method in Python?

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.

Q 40. Explain the concept of "duck typing" in Python.

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 41. What is Object-Oriented Programming (OOP)?

OOP's Concepts in Python

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:

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.

Q 42. What are classes and objects in Python?

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).

Q 43. What is inheritance in Python?

inheritance in Python

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.

Example

# Base class

class Animal:

def __init__(self, name):

self.name = name

def speak(self):

return f"{self.name} makes a sound."

# Derived class

class Dog(Animal):

def speak(self):

return f"{self.name} says Woof!"

# Using the classes


animal = Animal("Generic Animal")

dog = Dog("Buddy")

print(animal.speak())

print(dog.speak())

Try it Yourself >>

Output

Generic Animal makes a sound.

Buddy says Woof!

Q 44. What is the difference between __init__ and __new__ in Python?

__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__.

Q 45. What is polymorphism in Python?

polymorphism in Python

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).

Example

# Base class

class Animal:

def speak(self):

return "Animal makes a sound."

# 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!"

# Function demonstrating polymorphism

def animal_sound(animal):

return animal.speak()

# Creating objects

dog = Dog()

cat = Cat()

# Using polymorphism

print(animal_sound(dog))

print(animal_sound(cat))

Try it Yourself >>

Output

Dog says Woof!

Cat says Meow!

Q 46. What is encapsulation in Python?

encapsulation in Python

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.

class BankAccount:

def __init__(self, owner, balance=0):


self.owner = owner # Public attribute

self.__balance = balance # Private attribute (encapsulated)

# Getter method for balance

def get_balance(self):

return self.__balance

# Setter method for balance

def deposit(self, amount):

if amount > 0:

self.__balance += amount

else:

print("Deposit amount must be positive.")

# Method to withdraw money

def withdraw(self, amount):

if 0 < amount <= self.__balance:

self.__balance -= amount

else:

print("Invalid withdrawal amount.")

# Creating a BankAccount object

account = BankAccount("Alice", 1000)

# Accessing public and private attributes

print("Account owner:", account.owner) # Accessible

print("Initial balance:", account.get_balance()) # Access private attribute via method


# Modifying the balance using encapsulated methods

account.deposit(500)

account.withdraw(200)

print("Updated balance:", account.get_balance()) # Access updated balance

Try it Yourself >>

Output

Account owner: Alice

Initial balance: 1000

Updated balance: 1300

You might also like