ECESIS – 2024 – Fresher Interview Questions with Answers – Part 2
This blog explains about ECESIS Fresher Interview Questions with Answers – Part 2 is given below :
1.How do you reverse a string in Python?
There is no built-in function to reverse a String in Python. The fastest (and easiest?) way is to use a slice that steps backwards, -1
. Example code
txt = "Hello World"[::-1]
print(txt)
Output:
dlroW olleH
2. What is the role of a constructor in a class, and how do you define one in Python?
- In Python, a constructor is a special method that is called automatically when an object is created from a class.
- Its main role is to initialize the object by setting up its attributes or state.
The method new is the constructor that creates a new instance of the class while init is the initializer that sets up the instance’s attributes after creation. These methods work together to manage object creation and initialization.
__new__ Method:
This method is responsible for creating a new instance of a class. It allocates memory and returns the new object. It is called before init.
class ClassName:
def __new__(cls, parameters):
instance = super(ClassName, cls).__new__(cls)
return instance
Types of Constructors:
- Default Constructor
- Parameterized Constructor
3. How do you create an instance of a class (Object) in Python?
To create an instance of a class in Python, you simply call the class as if it were a function, passing any required arguments to the constructor (init method).
4. How do you create a custom python module and use in to your code?
To create a module just save the code you want in a file with the file extension. Python module involves two main steps:
1.Create the Custom Python Module:
A Python module is simply a Python file (with .py extension) that contains functions, classes, and variables that you can use in other Python files.
# mymodule.py
def greet(name):
return f"Hello, {name}!"
def add(a, b):
return a + b
def multiply(a, b):
return a * b
Step 2: Use the Custom Python Module in Your Code:
Import the module in another Python script: Let’s create another Python script (e.g., main.py) where you will use the functions defined in mymodule.py.
# main.py
import mymodule
# Using functions from mymodule
print(mymodule.greet("Alice"))
print(mymodule.add(3, 4))
print(mymodule.multiply(3, 4))
Output:
Hello, Alice,
7
12
Step 3: Run Your Code
To see it in action, ensure that both the mymodule.py and main.py files are in the same directory (or ensure the module is in the Python path if it’s located elsewhere). Then run main.py:
python main.py
Output:
Hello, Alice!
7
12
- Create a custom module by creating a .py file that contains reusable functions or classes.
- Import the module in other Python scripts using the import statement, and use its functions or classes.
- You can import the entire module, specific functions, or use an alias to simplify usage.
5. How do you create a new MYSQL database using Python MySQL Connector?
To create a new MySQL database using Python’s MySQL Connector, you need to connect to your MySQL server, then execute an SQL “CREATE DATABASE” statement using a cursor object; essentially, import the connector, establish a connection, create a cursor, and execute the database creation query with the desired database name.
import mysql.connector
# Connection details
mydb = mysql.connector.connect(
host="your_host_address",
user="your_username",
password="your_password",
database="your_existing_database" # Connect to an existing database to execute the CREATE DATABASE command
)
# Create a cursor object
mycursor = mydb.cursor()
# Execute the CREATE DATABASE statement
database_name = "new_database" # Replace with your desired database name
mycursor.execute(f"CREATE DATABASE {database_name}")
# Commit changes to the database
mydb.commit()
# Close the connection
mydb.close()
6. What is the difference between a list and tuple in Python?
Lists and Tuples in Python are two different implementations of array data structure.
List is Mutable and Tuple is not (Cannot update an element, insert and delete elements)
Tuples are faster because of read only nature. Memory can be efficiently allocated and used for tuples.
S.No | LIST | TUPLE |
1 | Lists are mutable. | Tuples are immutable. |
2 | The implication of iterations is Time-consuming | The implication of iterations is comparatively Faster |
3 | The list is better for performing operations, such as insertion and deletion. | A Tuple data type is appropriate for accessing the elements |
4 | Unexpected changes and errors are more likely to occur | Because tuples don’t change they are far less error-prone. |
7. How do you update an existing record in a MySQL table using a Python script?
- A connector is employed when we have to use MySQL with other programming languages. The work of MySQL-connector is to provide access to MySQL Driver to the required language.
- Thus, it generates a connection between the programming language and the MySQL Server.
- The update is used to change the existing values in a database. By using update a specific value can be corrected or updated. It only affects the data and not the structure of the table.
- The basic advantage provided by this command is that it keeps the table accurate.
Syntax:
UPDATE tablename
SET ="new value"
WHERE ="old value";
Example Program:
import mysql.connector
# Connecting to the Database
mydb = mysql.connector.connect(
host ='localhost',
database ='College',
user ='root',
)
cs = mydb.cursor()
# drop clause
statement ="UPDATE STUDENT SET AGE = 23 WHERE Name ='Rishi Kumar'"
cs.execute(statement)
mydb.commit()
# Disconnecting from the database
mydb.close()
Output:
8.How can you find the length of a string in Python?
To get the length of a string, use the len() function. The len() function returns the length of a string
a = "Jothy"
print(len(a))
Output:
5
9.How do you declare and initialize a variable in Python?
Python is a dynamic-typed language, which means we don’t need to mention the variable type or declare before using it.
It makes to Python the most efficient and easy to use language. Every variable is treated as an object in Python.
- Before declaring a variable, we must follow the given rules.
- The first character of the variable can be an alphabet or (_) underscore.
- Special characters (@, #, %, ^, &, *) should not be used in variable name.
- Variable names are case sensitive. For example – age and AGE are two different variables.
- Reserve words cannot be declared as variables
Syntax:
variable_name = value
Example:
# Declaring and initializing a variable
age = 25
name = "John"
is_active = True
height = 5.9
- age is assigned an integer value 25.
- name is assigned a string value “John”.
- is_active is assigned a boolean value True.
- height is assigned a float value 5.9.
10. What is object oriented programming(oop), and what are its core principles?
Object-Oriented Programming (OOP) is a programming paradigm that organizes and models software around objects rather than functions or logic. An object is an instance of a class, which is a blueprint that defines its structure (attributes) and behavior (methods). OOP is widely used in many modern programming languages, including Python, Java, C++, and C#.
In OOP, objects interact with each other by sending messages (method calls), and the data associated with these objects is encapsulated within them, promoting a more modular, flexible, and scalable approach to software development.
Core Principles of OOP
There are four core principles of Object-Oriented Programming.
Encapsulation:
Encapsulation is the concept of bundling data (attributes) and methods (functions) that operate on the data into a single unit, or class. It restricts direct access to some of the object’s components, which helps protect the integrity of the data.
Purpose:
The main goal is to hide the internal state of an object and only expose a controlled interface to interact with that state.
Example:
In Python, you can make attributes private by using an underscore _ or double underscore __, which prevents direct access to them from outside the class.
class Car:
def __init__(self, make, model):
self.make = make
self.model = model
self.__speed = 0 # private attribute
def accelerate(self):
self.__speed += 5
def get_speed(self):
return self.__speed
Abstraction:
Abstraction involves simplifying complex systems by providing a clear and simple interface while hiding the internal workings of an object. It allows the user to focus on what an object does, not how it does it.
Purpose: The purpose of abstraction is to reduce complexity by hiding unnecessary details and showing only the relevant features.
Example: A class Car might expose a method drive(), but the inner mechanics of how the car moves (engine, gears, etc.) are hidden from the user.
class Car:
def drive(self):
print("Car is driving")
Inheritance:
Inheritance allows a new class (called a subclass or derived class) to inherit properties and methods from an existing class (called a superclass or base class). It enables code reuse and establishes a relationship between different classes.
Purpose: It helps to create a hierarchical classification of objects. Subclasses can extend or override behaviors defined in the superclass.
Example: A SportsCar class can inherit from the Car class and extend its behavior.
class Car:
def start(self):
print("Car started")
class SportsCar(Car):
def turbo_boost(self):
print("Turbo boost activated!")
Create an Instance of SportsCar
sc = SportsCar()
sc.start()
sc.turbo_boost()
Example Code:
class Car:
def start(self):
print("Car started")
class SportsCar(Car):
def turbo_boost(self):
print("Turbo boost activated!")
# Create an instance of SportsCar
sc = SportsCar()
sc.start() # Inherited method from Car
sc.turbo_boost() # Method specific to SportsCar
Polymorphism:
Polymorphism means “many shapes”. It allows objects of different classes to be treated as instances of the same class through a common interface, typically through method overriding or method overloading. In essence, polymorphism allows different objects to respond to the same method call in different ways.
Purpose: It promotes flexibility and the ability to use a unified interface, making it easier to extend and maintain code.
Example: A method make_sound() can be implemented differently for different types of animals, even though they all share the same method name.
Syntax:
class Animal:
def make_sound(self):
pass
class Dog(Animal):
def make_sound(self):
print(“Bark!”)
class Cat(Animal):
def make_sound(self):
print(“Meow!”)
# Using polymorphism
animals = [Dog(), Cat()]
for animal in animals:
animal.make_sound() # Calls the appropriate method based on object type
11. How do you iterate over the elements of a list in Python?
Using a for loop:
The most common way to iterate over the elements of a list is by using a for loop.
my_list = [10, 20, 30, 40, 50]
# Iterate through the list using a for loop
for item in my_list:
print(item)
Output:
10
20
30
40
50
Using for loop with range():
If you need to access the index of each element, you can use the range() function to loop over the indices of the list.
my_list = ['a', 'b', 'c', 'd']
# Iterate over the list using range to access the index
for i in range(len(my_list)):
print(i, my_list[i])
Output:
0 a
1 b
2 c
3 d
Using enumerate():
The enumerate() function provides both the index and the element at the same time. This is particularly useful when you need both the index and the value in a loop.
Exampel Code:
my_list = [100, 200, 300, 400]
# Iterate with enumerate to get index and value
for index, value in enumerate(my_list):
print(f"Index: {index}, Value: {value}")
Output:
Index: 0, Value: 100
Index: 1, Value: 200
Index: 2, Value: 300
Index: 3, Value: 400
12.What is the Purpose of the commit() method when working with MySQL database in Python?
A COMMIT means that the changes made in the current transaction are made permanent and become visible to other sessions. A ROLLBACK statement, on the other hand, cancels all modifications made by the current transaction. Both COMMIT and ROLLBACK release all InnoDB locks that were set during the current transaction.
13. What is a Python dictionary and How do you access values based on keys?
Values in a Python dictionary can be accessed by placing the key within square brackets next to the dictionary. Values can be written by placing key within square brackets next to the dictionary and using the assignment operator ( = ). Example Program
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
Output:
Mustang
14. How can you insert data into a MySQL table using Python?
Insert Into Table:
To fill a table in MySQL, use the “INSERT INTO” statement.
Example:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
Output:
1 record inserted.
Reference:
www.tutorialspoint.com
www.w3schools.com
chatgpt.com