1)WHAT IS LISTS?
ANS: In Python, a list is a built-in data structure that allows you to store an ordered collection of items. Lists are versatile and can hold elements of different data types, including integers, floats, strings, and even other lists. They are mutable, meaning you can modify their contents after creation.
Key Characteristics of Lists in Python
1)Ordered: The items in a list maintain the order in which they are added. Each item can be accessed using its index, starting from 0.
2)Mutable: You can change, add, or remove items from a list after it has been created.
3)Dynamic Size: Lists can grow and shrink in size as needed. You do not need to specify the size of the list when you create it.
4)Heterogeneous: Lists can contain elements of different types. For example, a list can include integers, strings, and other lists.
python
Creating a list
fruits = [“apple”, “banana”, “orange”]
print(fruits) # Output: [‘apple’, ‘banana’, ‘orange’]
2)What is a Tuple?
ANS: A tuple is a built-in data structure in Python that is used to store an ordered collection of items. Tuples are similar to lists, but they have some key differences that make them unique and useful in certain scenarios.
Key Characteristics of Tuples
1)Ordered: Like lists, tuples maintain the order of the elements. The items can be accessed using their index, starting from 0.
2)Immutable: Once a tuple is created, its contents cannot be changed. This means you cannot add, remove, or modify elements in a tuple. This immutability makes tuples suitable for use as keys in dictionaries and for storing data that should not be modified.
3)Heterogeneous: Tuples can contain elements of different data types. For example, a tuple can include integers, strings, and even other tuples.
Creating a tuple
my_tuple = (1, 2, 3, “apple”, “banana”)
print(my_tuple) # Output: (1, 2, 3, ‘apple’, ‘banana’)
3)What is a dictionary?
ANS: A dictionary in Python is a built-in data structure that stores data in key-value pairs. It is an unordered collection, meaning that the items do not have a defined order, and each key must be unique within the dictionary. Dictionaries are also mutable, allowing you to add, remove, or change items after the dictionary has been created.
Key Characteristics of Dictionaries
1)Key-Value Pairs: Each item in a dictionary consists of a key and a corresponding value. The key is used to access the value.
2)Unordered: Dictionaries do not maintain the order of items. As of Python 3.7, the insertion order is preserved, but this should not be relied upon for logic that depends on ordering.
3)Mutable: You can modify a dictionary by adding new key-value pairs, updating existing values, or removing items.
EXAMPLE:-
Creating a dictionary using curly braces
my_dict = {
“name”: “Alice”,
“age”: 30,
“city”: “New York”
}
Creating a dictionary using the dict() constructor
another_dict = dict(name=”Bob”, age=25, city=”Los Angeles”)
print(my_dict) # Output: {‘name’: ‘Alice’, ‘age’: 30, ‘city’: ‘New York’}
print(another_dict) # Output: {‘name’: ‘Bob’, ‘age’: 25, ‘city’: ‘Los Angeles’}
4)Explain Modules and Packages in Python?
ANS: In Python, modules and packages are essential concepts that help organize and manage code effectively. They allow developers to structure their programs in a modular way, making it easier to maintain and reuse code.
Modules
A module is a single file (with a .py extension) that contains Python code, which can include functions, classes, and variables. Modules allow you to break down your code into smaller, manageable pieces, promoting code reuse and organization.
EXAMPLE:-
mymodule.py
def greet(name):
return f”Hello, {name}!”
PI = 3.14159
5)What is OOPS concept?
ANS: Object-Oriented Programming (OOP) is a programming paradigm that uses “objects” to represent data and methods to manipulate that data. OOP is based on several key concepts that help organize and structure code in a way that is modular, reusable, and easier to understand. The main concepts of OOP are:
- Classes and Objects
Class: A class is a blueprint or template for creating objects. It defines a set of attributes (data) and methods (functions) that the created objects will have. Classes encapsulate data for the object and provide methods to manipulate that data.
6)Explain various OOPS concepts?
ANS: Object-Oriented Programming (OOP) is a programming paradigm that uses “objects” to design software. OOP is based on several key concepts that allow developers to structure code in a modular, reusable, and maintainable way. The main concepts of OOP include:
- Classes and Objects
Class: A class is a blueprint or template for creating objects. It defines attributes (data) and methods (functions) that the created objects will have. Classes encapsulate data for the object and provide methods to manipulate that data.
Object: An object is an instance of a class. When a class is instantiated, it creates an object that can access the class’s attributes and methods.
EXAMPLE: class Car:
def init(self, make, model):
self.make = make # Attribute
self.model = model # Attribute
def display_info(self): # Method
return f"{self.make} {self.model}"
Creating an object of the Car class
my_car = Car(“Toyota”, “Corolla”)
print(my_car.display_info()) # Output: Toyota Corolla
7)Explain Inheritance?
ANS: Inheritance is one of the fundamental concepts of Object-Oriented Programming (OOP) that allows a new class (known as a derived or child class) to inherit attributes and methods from an existing class (known as a base or parent class). This mechanism promotes code reuse and establishes a hierarchical relationship between classes.
Key Features of Inheritance
Code Reusability: By inheriting from a parent class, the child class can use the methods and attributes of the parent class without having to rewrite the code.
Hierarchical Classification: Inheritance creates a natural hierarchy between classes, which can make it easier to understand relationships and organize code.
Method Overriding: A child class can provide a specific implementation of a method that is already defined in its parent class. This is known as method overriding.
EXAMPLE::
class Animal:
def speak(self):
return “Animal speaks”
class Dog(Animal): # Dog inherits from Animal
def bark(self):
return “Woof!”
my_dog = Dog()
print(my_dog.speak()) # Output: Animal speaks
print(my_dog.bark()) # Output: Woof!
8)Explain Normalization?
ANS: Normalization is a systematic approach to organizing data in a database to reduce redundancy and improve data integrity. The primary goal of normalization is to ensure that the data is stored efficiently and that relationships between the data are logically structured. This process involves dividing large tables into smaller, related tables and defining relationships between them.
Key Objectives of Normalization
Eliminate Redundancy: By organizing data into separate tables, normalization reduces duplicate data, which can save storage space and minimize the risk of inconsistencies.
Ensure Data Integrity: Normalization helps maintain the accuracy and consistency of data by enforcing rules about how data is stored and related.
Facilitate Data Maintenance: A well-normalized database is easier to maintain and update, as changes to data in one table can be automatically reflected in related tables.
EXAMPLE:-
StudentID | Name | Subjects |
---|---|---|
1 | Alice | Math, Science |
2 | Bob | English, History |
9)Explain Encapsulation?
ANS: Encapsulation is one of the four fundamental concepts of Object-Oriented Programming (OOP), along with inheritance, polymorphism, and abstraction. It refers to the bundling of data (attributes) and methods (functions) that operate on that data into a single unit, typically a class. Encapsulation restricts direct access to some of an object’s components, which helps prevent accidental interference and misuse of the methods and data.
Key Features of Encapsulation
1)Data Hiding: Encapsulation allows for the hiding of an object’s internal state and requires all interaction to occur through an object’s methods. This means that the internal representation of the object can be changed without affecting the code that uses the object.
2)Controlled Access: By using access modifiers, encapsulation controls how data and methods can be accessed. This ensures that the internal state of the object is only modified in controlled ways.
Access Modifiers
In many programming languages, encapsulation is implemented using access modifiers, which define the visibility of class members (attributes and methods):
Public: Members declared as public can be accessed from anywhere in the program.
Protected: Members declared as protected can be accessed within the class and by derived classes (subclasses).
EXAMPLE:-
class BankAccount:
def init(self, account_number, balance=0):
self.__account_number = account_number # Private attribute
self.__balance = balance # Private attribute
def deposit(self, amount):
if amount > 0:
self.__balance += amount
print(f"Deposited: {amount}")
else:
print("Deposit amount must be positive.")
def withdraw(self, amount):
if 0 < amount <= self.__balance:
self.__balance -= amount
print(f"Withdrew: {amount}")
else:
print("Invalid withdrawal amount.")
def get_balance(self):
return self.__balance
Usage
account = BankAccount(“123456789”)
account.deposit(1000) # Output: Deposited: 1000
account.withdraw(500) # Output: Withdrew: 500
print(account.get_balance()) # Output: 500
Attempting to access private attributes directly will raise an error
print(account.__balance) # AttributeError: ‘BankAccount’ object has no attribute ‘__balance’
10)Explain Polymorphism?
ANS: Polymorphism is one of the core concepts of Object-Oriented Programming (OOP) that allows objects of different classes to be treated as objects of a common superclass. The term “polymorphism” means “many shapes” or “many forms,” and it enables a single interface to represent different underlying forms (data types).
Key Features of Polymorphism
Method Overriding: This occurs when a subclass provides a specific implementation of a method that is already defined in its superclass. When the method is called on an object of the subclass, the overridden method is executed, allowing for specific behavior.
Method Overloading: This occurs when multiple methods in the same class have the same name but differ in the type or number of parameters. It allows a class to perform similar operations in different ways.
Dynamic Binding: Polymorphism allows for dynamic binding (or late binding), where the method that gets executed is determined at runtime based on the object’s actual type rather than its reference type.
EXAMPLE:-
class MathOperations:
def add(self, a, b):
return a + b
def add(self, a, b, c):
return a + b + c
math_ops = MathOperations()
print(math_ops.add(2, 3)) # This will raise an error in Python due to the method being overridden.
print(math_ops.add(2, 3, 4)) # Output: 9
11)How many keywords are there in Python?
ANS: As of Python 3.10, there are 35 keywords in Python. These keywords are reserved words that have special meaning in the language and cannot be used as identifiers (such as variable names, function names, etc.).
EXAMPLE;–
import keyword
print(keyword.kwlist)
print(“Number of keywords:”, len(keyword.kwlist))
12)Common built-in Data Types in Python?
ANS: Python provides several built-in data types that are used to store and manipulate data. These data types can be categorized into several groups. Here are the most common built-in data types in Python:
- Numeric Types
int: Represents integer values, e.g., 5, -3, 42.
float: Represents floating-point numbers (decimal values), e.g., 3.14, -0.001, 2.0.
complex: Represents complex numbers, which have a real part and an imaginary part, e.g., 2 + 3j. - Sequence Types
str: Represents a string, which is a sequence of characters, e.g., “Hello, World!”.
list: Represents an ordered, mutable collection of items, which can be of different types, e.g., [1, 2, 3], [‘apple’, ‘banana’, ‘cherry’].
tuple: Represents an ordered, immutable collection of items, e.g., (1, 2, 3), (‘apple’, ‘banana’, ‘cherry’). - Mapping Type
dict: Represents a collection of key-value pairs, where keys must be unique, e.g., {‘name’: ‘Alice’, ‘age’: 30}. - Set Types
set: Represents an unordered collection of unique items, e.g., {1, 2, 3}, {‘apple’, ‘banana’, ‘cherry’}.
frozenset: Represents an immutable version of a set, e.g., frozenset({1, 2, 3}). - Boolean Type
bool: Represents Boolean values, which can be either True or False. - None Type
NoneType: Represents the absence of a value or a null value, denoted by the keyword None.
13)Which is faster JAVA or Python?
ANS: The performance comparison between Java and Python can vary based on several factors, including the specific use case, the nature of the application, and how the code is written. However, there are some general observations regarding the speed and performance of both languages:
In summary, Java is generally faster than Python in terms of execution speed, particularly for CPU-bound applications. However, Python allows for faster development and is often chosen for its ease of use, readability, and extensive libraries, especially in fields like data science and web development.
14)What is break, continue and Pass in Python?
ANS: In Python, break, continue, and pass are control flow statements that are used to alter the flow of execution in loops and conditional statements. Here’s a detailed explanation of each:
15)What is slicing in Python?
ANS: _Slicing in Python is a powerful feature that allows you to extract a portion of a sequence (like a list, tuple, or string) by specifying a range of indices. This can be useful for accessing sub-parts of data structures without needing to loop through them manually.
16)What is a Decorator?
ANS: A decorator is essentially a function that takes another function as an argument, extends or alters its behavior, and returns a new function. Decorators are commonly used for logging, access control, instrumentation, caching, and more.
Syntax
The syntax for applying a decorator to a function is to use the @decorator_name syntax just above the function definition.