Python Lab Viva Que
Python Lab Viva Que
Features of Python
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.
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
print(my_list)
Output
[1, 2, 3, 'hello', 4]
Tuples in python
Example
print(my_tuple)
Output
(1, 2, 3, 'world')
dictionary in Python
Example
# Creating a dictionary
person = {
"name": "Aman",
"age": 25,
}
# Accessing dictionary elements
print("Name:", person["name"])
print("Age:", person["age"])
print("City:", person["city"])
person["age"] = 26
del person["city"]
print(f"{key}: {value}")
if "name" in person:
keys = person.keys()
values = person.values()
print("Keys:", keys)
print("Values:", values)
# Merging dictionaries
person.update(additional_info)
Output
Name: Aman
Age: 25
Updated dictionary: {'name': 'Aman', 'age': 25, 'city': 'New York', 'job': 'Software Developer'}
Updated age: 26
name: Aman
age: 26
Merged dictionary: {'name': 'Aman', 'age': 27, 'job': 'Software Developer', 'hobbies':
['Reading', 'Traveling']}
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.
range() in Python 2 returns a list, and xrange() returns an iterator, which is more memory
efficient.
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
square = lambda x: x ** 2
Output
Square of 5: 25
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__().
is checks if two objects refer to the same memory location (i.e., they are the same object).
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.
A module is a file containing Python code, and it can define functions, classes, and variables.
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.
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.
extend() adds all elements from an iterable to the end of the list.
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.
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
Output
Python 2 and Python 3 have several differences. Some key differences include:
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.
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.
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.
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.
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.
@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.
Multiple exceptions can be handled using a single except block by specifying them in a tuple.
For example:
try:
# some code
print(f"Error: {e}")
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).
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.
__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.
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.
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.
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:
Unit testing in Python is commonly done using the built-in unittest module.
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.
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.
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.
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.
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).
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:
self.name = name
def speak(self):
# Derived class
class Dog(Animal):
def speak(self):
dog = Dog("Buddy")
print(animal.speak())
print(dog.speak())
Output
__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__.
polymorphism in Python
Example
# Base class
class Animal:
def speak(self):
# Derived class 1
class Dog(Animal):
def speak(self):
class Cat(Animal):
def speak(self):
def animal_sound(animal):
return animal.speak()
# Creating objects
dog = Dog()
cat = Cat()
# Using polymorphism
print(animal_sound(dog))
print(animal_sound(cat))
Output
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 get_balance(self):
return self.__balance
if amount > 0:
self.__balance += amount
else:
self.__balance -= amount
else:
account.deposit(500)
account.withdraw(200)
Output