Important Interview Questions and Answere in Python.

                                                Python Interview Questions and Answere:


1. What is the Difference Between a Shallow Copy and Deep Copy ?
         The copy module in Python provides two functions: copy() and deepcopy(). 
         The copy() function creates a shallow copy of an object, while deepcopy() creates a deep copy.
Deep Copy (copy.deepcopy()):
        A deep copy makes the copying process recursive. It means that constructing a new collection object and then, recursively, inserting copies into it of the objects found in the original.
Shallow Copy (copy.copy()):
        A shallow copy means constructing a new collection object and then populating it with references to the child objects found in the original. And the shallow copy is only one level deep. The copying process does not recurse and therefore won't create copies of the child objects themselves.
Example :
 import copy
original_list = [[1, 2, 3], [4, 5, 6]]
shallow_copy = copy.copy(original_list)
deep_copy = copy.deepcopy(original_list)
original_list[0][0] = 'changed'
print("Original:", original_list)
print("Shallow Copy:", shallow_copy)
print("Deep Copy:", deep_copy)
Output :
Original: [['changed', 2, 3], [4, 5, 6]]
Shallow Copy: [['changed', 2, 3], [4, 5, 6]]
Deep Copy: [[1, 2, 3], [4, 5, 6]]

2.What are Python decorators and how do they work ?
          Decorators in Python are a powerful and useful tool that allows for adding functionality to an existing code.
          Decorators allow you to wrap another function in order to extend the behavior of the wrapped function, without permanently modifying it.
Example:
def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper
@my_decorator
def say_hello():
    print("Hello!")
say_hello()
Output :
Something is happening before the function is called.
Hello!
Something is happening after the function is called.

3.What is the difference between __init__ and __new__methods?
       __init__ :
                   It is the initializer method in Python. It is called after the instance has been created to initialize the instance's attributes.
       __new__ :
                   It is the constructor method. It is called before __init__ and is responsible for creating and returning a new instance of the class.
Example:
class MyClass:
    def __new__(cls, *args, **kwargs):
        print("Creating instance")
        instance = super().__new__(cls)
        return instance
    def __init__(self, value):
        print("Initializing instance")
        self.value = value
obj = MyClass(10)
Output:
Creating instance
Initializing instance

4. How will you Merge Elements in a Sequence ?
          There are three types of sequences in Python:  "List , Tuples , Strings".
Lists :
           A list in Python is a mutable, ordered collection of items. Lists can contain items of different data types, and they allow duplicate elements.
Example : 
>>l1=[1,2,3]
>>l2=[4,5,6]
>>l1+l2
Output : [1,2,3,4,5,6]
Tuples :
             A tuple in Python is an immutable, ordered collection of items. Tuples can contain items of different data types, and they allow duplicate elements.
Example :  
>>t1=(1,2,3)
>>t2=(4,5,6)
>>t1+t2
Output :  (1,2,3,4,5,6)
Strings :
          A string in Python is an immutable, ordered sequence of characters. Strings are used to represent text.
Example :  
>>s1=“Simpli”
>>s2=“learn”
>>s1+s2
Output : ‘Simplilearn’

5. How would you Remove all leading Whitespace in a string ?
             Python provides the inbuilt function lstrip() to remove all leading spaces from a string.
Example:
>>“      Python”.lstrip
Output: Python

6. What are keywords in Python ?
                      keywords are reserved words with a specific meaning. They are commonly used to specify the type of variables.
                     Variable and function names cannot contain keywords.
List of Keywords :
False      await      else       import     pass
None       break      except     in         raise
True       class      finally    is         return
and        continue   for        lambda     try
as         def        from       nonlocal   while
assert     del        global     not        with
async      elif       if         or         yield
1. False /True : Boolean Values. 
(Example)
is_raining = False
is_sunny = True
if is_sunny:
    print("It's sunny!")
2. None : Represents the absence of a value. 
( Example)
result = None
if result is None:
    print("No result")
3. and ,or , not : Logical operators. 
(Example)
a = True
b = False
if a and not b:
    print("a is True and b is False")
4. if, elif , else :Conditional statements.  
(Example)
temperature = 25
if temperature > 30:
    print("It's hot!")
elif temperature < 10:
    print("It's cold!")
else:
    print("It's moderate.")
5. for , while : Looping constructs. 
(Example)
for i in range(5):
    print(i)

count = 0
while count < 5:
    print(count)
    count += 1
6. break , continue : Control the flow of loops.
 (Example)
for i in range(5):
    if i == 3:
        break
    print(i)

for i in range(5):
    if i == 3:0
        continue
    print(i)
7. def , return :Define functions and return values. 
(Example)
def add(a, b):
    return a + b

print(add(2, 3))  # Output: 5
8. class : Define classes.
(Example)
class MyClass:
    def __init__(self, value):
        self.value = value

    def display(self):
        print(self.value)

obj = MyClass(10)
obj.display()  # Output: 10
9. try, except , finally : Exception handling 
(Example)
try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")
finally:
    print("This will run no matter what")
10. import , from, as :Import modules and aliasing.
Example :
import math
print(math.sqrt(16))  # Output: 4.0

from datetime import datetime as dt
print(dt.now())
11. with :Context manager for resource management.
Example :
with open('example.txt', 'r') as file:
    content = file.read()
    print(content)
12. global, nonlocal :Declare variables with broader scope.
Example :
x = 5

def func():
    global x
    x = 10

func()
print(x)  # Output: 10

def outer():
    y = 5
    def inner():
        nonlocal y
        y = 10
    inner()
    print(y)  # Output: 10

outer()
13. lambda :Define anonymous functions.
Example :
add = lambda x, y: x + y
print(add(2, 3))  # Output: 5
14. assert: 
      The assert statement is used for debugging purposes. It tests if a condition is true, and if not, it raises an Assertion Error with an optional message.
Example :
def test_assert(x):
    assert x > 0, "x should be positive"
    return x

print(test_assert(5))  # Output: 5
# print(test_assert(-5))  # AssertionError: x should be positive
15. del :  The del statement is used to delete objects, such as variables, list items, or dictionary entries.
Example :
# Deleting a variable
a = 10
del a
# print(a)  # Raises NameError because 'a' is deleted

# Deleting a list item
lst = [1, 2, 3]
del lst[1]
print(lst)  # Output: [1, 3]

# Deleting a dictionary entry
d = {'a': 1, 'b': 2}
del d['b']
print(d)  # Output: {'a': 1}
16. yield : 
The yield statement is used in a function to make it a generator. It allows the function to return a value and later resume where it left off.
Example :
def simple_generator():
    yield 1
    yield 2
    yield 3

gen = simple_generator()
for value in gen:
    print(value)
# Output:
# 1
# 2
# 3
17. async and await : 
                      async - The async and await keywords are used to write asynchronous code. async defines an asynchronous function.
                       await - await is used to pause the function execution until the awaited result is available.
Example :
import asyncio

async def main():
    print("Hello")
    await asyncio.sleep(1)
    print("World")

asyncio.run(main())

7. How do you mock external services during testing in Python ?
         Use the unittest.mock module to replace parts of your system under test and make assertions about how they are used.
Example :
from unittest.mock import patch

@patch('requests.get')
def test_fetch_data(mock_get):
    mock_get.return_value.status_code = 200
    # Your test code here







 





Comments

Popular posts from this blog

Road Map for Devops - Entry Level , Intermediate Level and Expert Level.

Source Code Management --- GIT - Global Information Tracker