0% found this document useful (0 votes)
29 views13 pages

Python Programming Concepts Explained

The document outlines key concepts in Python programming, including the differences between lists and tuples, abstraction vs encapsulation, class and object definitions, lambda functions, and exception handling. It also covers advanced topics such as inheritance types, operator overloading, and the use of *args and **kwargs for variable arguments. Additionally, it provides examples and explanations of decorators, Python's Global Interpreter Lock, and the method resolution order in multiple inheritance scenarios.

Uploaded by

ALINA SOY
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views13 pages

Python Programming Concepts Explained

The document outlines key concepts in Python programming, including the differences between lists and tuples, abstraction vs encapsulation, class and object definitions, lambda functions, and exception handling. It also covers advanced topics such as inheritance types, operator overloading, and the use of *args and **kwargs for variable arguments. Additionally, it provides examples and explanations of decorators, Python's Global Interpreter Lock, and the method resolution order in multiple inheritance scenarios.

Uploaded by

ALINA SOY
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1. What is difference between List and tuples?

List and tuples are both are sequence data types can have different data types. The
difference between them is:
List is mutable but tuple is immutable
List can be modified, sliced, append but tuples can’t be modified, sliced, append.
List consume more memory and tuple consume less memory
List represent by sq bracket and tuple is represent in parenthesis.
2. What is difference between abstraction and encapsulation?
Abstraction means showing only required things and hide the
background/implementation details.
Encapsulation means wrapping of data and method into a single unit. So that data
remains hidden and only be accessed by properties only.

3. Class in python is a blue print for creating object. It binds a data member and function in
a single unit. Any varible declared in class called data members any function is declare is
called member function. Class properties can be resented by a member variable and in
class action is done by member function.
For example, a class can represent a real-world entity like a Car — where its properties
like color, brand, or speed are represented by member variables, and actions like start(),
stop() are implemented as member functions.

Object is instance of class. It is basic runtime entity of an object-oriented system. So by


using object we can communicate data member and member function of a class.
4. Lambda Function: Lambda function is an anonymous function. This function can have
number of parameters but can have just one statement.
Anonymous function: Anonymous function is a function without name it is define using
lambda keyword.

5. Global Interpreter lock is a mutex that protect access to python objects, preventing
multiple native threads from executing python bytecodes simultaneously. This can limit
the concurrency in python for multi-threading programs.

6. What are decorators?


Decorators is a just function, that takes another function as parameter add some
functionality and then return another function. All of this without altering of source
code of original function that you passed in.
FOLLOW-UP QUESTION:
Can one function can return another function – yes
Can one function return multiple values, comma – separated =yes
When one function returning comma separated multiple values then where it stores =
tuple

7. Difference between List and dictionary comprehension?


The fundamental difference between list and comprehension in python lies in the type
of data structure they produce and their respective syntax.
List comprehension:
Creates a new list. The result is in ordered sequence of elements, where each element
derived from expression applied to items in iterable.
Dictionary Compreshion:
Creates a new dictionary. The result is in key value pair, where both key and value
derived from expression applied to items in an iterable.
Syntax:
8. What are in-built function data types in python?
In python, data types are broadly categorized into primitive and non-primitive data
types.
In primitive datatype it contains Int which store interger value, folat store number with
decimalpoints , str store sequence of chatraters, and Boolean stores logical values eith t
or f.
In non-primitive data type it contains list which ordered, mutalbel collection of items,
tuples stores orderd , immutable collection of items, set unorderd , mutable of unique
elemts, dictionary store unorede , mutabl collection of key-value pair.
9. What is break, continue and pass statement/
Break: Break statement terminates the loop immediately and control flows to the
statements after the body of loop
Continue: Continue statement terminates the current iteration of the loop and skip the
rest code in current iteration and control flows to the next iteration of the loop.
Pass statement is null statement. When python interpreter come across pass statement
it does nothing and ignored.
10. How exceptional handling is done in python?
Exception handling in Python is managed primarily using try, except, and finally blocks,
along with the raise statement for custom exception raising.
1. The try block:
 Code that might cause an exception is enclosed within the try block.
 If an exception occurs in this block, the remaining statements in the try block are
skipped, and control is transferred to an appropriate except block.
2. The except block(s):
 The except block is used to catch and handle specific exceptions that might occur within
the try block.
 You can specify the type of exception to catch (e.g., except ValueError:) or catch multiple
exception types in one except block.
 If the exception type matches, the code within the except block is executed.
 You can also have a general except block (except:) to catch any unhandled exceptions,
though this is generally discouraged for debugging purposes as it can mask specific
errors.
3. The finally block (optional):
 The finally block contains code that will always be executed, regardless of whether an
exception occurred in the try block or was handled by an except block.
 It is commonly used for cleanup operations, such as closing files or releasing resources,
ensuring they are performed even if errors occur.

11. What is pythonpath?


Python path is an environment variable which is used when model is impoeted.
Whenever module is imported, pythonpath is also lookup to check for the presence of
the imported module in various dictionary. The interpreter uses it to determine which
module is to load.
12. What is *args and **kwargs/
*args and **kwargs are special syntax in python that allows function to accept variable
number of arguments. This means you can define function without knowing beforehand
how many arguments will passed to it during its call.
*args stands for arbitrary positional argument
**kwargs stands for arbitrary keyword argument
*args used to passed non-keyword, variable-length argument of list in a function. will
collect all extra positional arguments into a tuple.
*kwargs used to passed keyworded, variable-length argument of list to a function. it
will collect all extra keyword arguments into a dictionary.
13. What is operator overloading?
Operator overloading is a key concept object-oriented programming. It allows you to
define how standard operator behave when applied to instance of customs classes. In
python is achieved by implementing special methods, often called "dunder methods"
(short for "double underscore methods"), within your class. When you use an operator
with your class's objects, Python internally calls the corresponding dunder method.
14. What is Namespace and its Type?
In python namespace ensure that the object name in a program are unique and can be
used without any conflict. Python implemented this namespace as dictionaries with
name as key map with corresponding object as value. This allows for multiple
namespaces to use the same name and map it to a separate object.
15. What is Inheritance?
Inheritance is a mechanism where a new class i.e a child class or subclass is created
based on existing class i.e parent class or superclasss. The child class inherits attribute
and method of parent class and can also add its own attribute and methods or modify
existing ones. This promotes code resuseability and allow creation of hierarchy of
classes.
How to implement Inheritance in python
Types of Inheritance in Python:
1. Single Inheritance: A child class inherits from only one parent class. This is the most
common and straightforward type.
Python
class Animal:
def speak(In):
print("Animal makes a sound")

class Dog(Animal): # Dog inherits from Animal


def speak(self): # Method overriding
print("Woof!")

def fetch(self):
print("Fetching the ball!")

my_dog = Dog()
my_dog.speak() # Output: Woof!
my_dog.fetch() # Output: Fetching the ball!
2. Multiple Inheritance: A child class inherits from multiple parent classes. This allows the
child class to combine functionalities from various sources.
Python
class Flyer:
def fly(self):
print("I can fly!")

class Swimmer:
def swim(self):
print("I can swim!")

class Duck(Flyer, Swimmer): # Duck inherits from Flyer and Swimmer


def quack(self):
print("Quack!")

donald = Duck()
[Link]() # Output: I can fly!
[Link]() # Output: I can swim!
[Link]() # Output: Quack!
3. Multilevel Inheritance: A child class inherits from another child class, creating a chain of
inheritance.
Python
class Grandparent:
def get_wisdom(self):
print("I have gained much wisdom.")

class Parent(Grandparent):
def teach(self):
print("I teach my children.")

class Child(Parent): # Child inherits from Parent, which inherits from Grandparent
def play(self):
print("I love to play!")

kid = Child()
kid.get_wisdom() # Output: I have gained much wisdom.
[Link]() # Output: I teach my children.
[Link]() # Output: I love to play!
4. Hierarchical Inheritance: Multiple child classes inherit from a single parent class.
Python
class Vehicle:
def __init__(self, make, model):
[Link] = make
[Link] = model

def start(self):
print(f"{[Link]} {[Link]} is starting.")

class Car(Vehicle):
def drive(self):
print("Driving the car.")

class Bicycle(Vehicle):
def pedal(self):
print("Pedaling the bicycle.")

my_car = Car("Toyota", "Camry")


my_bike = Bicycle("Giant", "Escape")

my_car.start() # Output: Toyota Camry is starting.


my_car.drive() # Output: Driving the car.

my_bike.start() # Output: Giant Escape is starting.


my_bike.pedal() # Output: Pedaling the bicycle.
5. Hybrid Inheritance: A combination of two or more types of inheritance.

How to Implement Interview Questions on Inheritance


When preparing for Python interviews, you should be ready to answer both theoretical
questions and solve coding problems related to inheritance.
Common Interview Questions (Theoretical):
1. What is inheritance in Python? Explain with an example. (As explained above)
2. What are the benefits of using inheritance? (Code reusability, modularity, extensibility,
"is-a" relationships)
3. Explain the different types of inheritance in Python. (Single, Multiple, Multilevel,
Hierarchical, Hybrid)
4. What is method overriding? Provide an example.
o Answer: Method overriding occurs when a subclass provides its own specific
implementation for a method that is already defined in its superclass. This allows
the subclass to change the behavior of the inherited method.
o Example: (See Dog class in Single Inheritance example above)
5. What is the purpose of the super() function in inheritance?
o Answer: The super() function is used to call methods from the parent class
(superclass) within a child class. It's most commonly used in the __init__ method
of the child class to ensure that the parent class's constructor is properly called
and inherited attributes are initialized. It helps in maintaining the correct Method
Resolution Order (MRO) in complex inheritance hierarchies.
o Example:
Python
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age

def display_info(self):
print(f"Name: {[Link]}, Age: {[Link]}")

class Student(Person):
def __init__(self, name, age, student_id):
super().__init__(name, age) # Call parent's __init__
self.student_id = student_id

def display_info(self): # Overriding


super().display_info() # Call parent's display_info
print(f"Student ID: {self.student_id}")

s1 = Student("Alice", 20, "S123")


s1.display_info()
6. Does Python support multiple inheritance? If so, what is the Method Resolution Order
(MRO)?
o Answer: Yes, Python supports multiple inheritance. The MRO is the order in
which Python searches for a method in a hierarchy of classes, especially crucial in
multiple inheritance to resolve potential conflicts (like the "diamond problem").
Python uses the C3 linearization algorithm to determine the MRO. You can see
the MRO using [Link]() or ClassName.__mro__.
o Example:
Python
class A:
def method(self):
print("Method from A")

class B(A):
def method(self):
print("Method from B")

class C(A):
def method(self):
print("Method from C")

class D(B, C):


pass

d_obj = D()
d_obj.method() # Output: Method from B (due to MRO)
print([Link]()) # Output will show the resolution order
# [<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class
'__main__.A'>, <class 'object'>]
7. What is the "diamond problem" in multiple inheritance, and how does Python handle
it?
o Answer: The "diamond problem" occurs when a class inherits from two classes
that both inherit from a common ancestor, creating a diamond shape in the
inheritance hierarchy. If a method is defined in the common ancestor and
overridden in both intermediate classes, it becomes ambiguous which version of
the method the final child class should inherit. Python handles this using the C3
linearization algorithm to determine a consistent Method Resolution Order
(MRO), ensuring that each method is called only once and in a predictable order.
8. Differentiate between inheritance and composition.
o Inheritance: Models an "is-a" relationship (e.g., a Dog is an Animal). It signifies a
strong, hierarchical relationship.
o Composition: Models a "has-a" relationship (e.g., a Car has an Engine). It
involves one class containing an object of another class. It promotes flexibility
and loose coupling.
Coding Interview Questions (Practical):
1. Implement a class hierarchy for Shape, Rectangle, and Circle. Each shape should have a
method to calculate its area.
Python
import math

class Shape:
def area(self):
raise NotImplementedError("Subclasses must implement this method")
class Rectangle(Shape):
def __init__(self, width, height):
[Link] = width
[Link] = height

def area(self):
return [Link] * [Link]

class Circle(Shape):
def __init__(self, radius):
[Link] = radius

def area(self):
return [Link] * [Link]**2

rect = Rectangle(5, 10)


circ = Circle(7)

print(f"Rectangle area: {[Link]()}")


print(f"Circle area: {[Link]()}")
2. Create a simple employee management system using inheritance. Have a base
Employee class and specialized Manager and Developer classes.
Python
class Employee:
def __init__(self, name, employee_id, salary):
[Link] = name
self.employee_id = employee_id
[Link] = salary

def get_details(self):
return f"Name: {[Link]}, ID: {self.employee_id}, Salary: ${[Link]}"

def calculate_payroll(self):
return [Link] / 12 # Simple monthly payroll

class Manager(Employee):
def __init__(self, name, employee_id, salary, department):
super().__init__(name, employee_id, salary)
[Link] = department

def get_details(self):
base_details = super().get_details()
return f"{base_details}, Department: {[Link]}"

def conduct_meeting(self):
print(f"{[Link]} is conducting a team meeting in {[Link]}.")

class Developer(Employee):
def __init__(self, name, employee_id, salary, programming_language):
super().__init__(name, employee_id, salary)
self.programming_language = programming_language

def get_details(self):
base_details = super().get_details()
return f"{base_details}, Language: {self.programming_language}"

def write_code(self):
print(f"{[Link]} is writing code in {self.programming_language}.")

manager = Manager("Alice Brown", "M001", 90000, "HR")


developer = Developer("Bob Green", "D001", 75000, "Python")

print(manager.get_details())
manager.conduct_meeting()
print(f"Manager's monthly payroll: ${manager.calculate_payroll():.2f}")

print(developer.get_details())
developer.write_code()
print(f"Developer's monthly payroll: ${developer.calculate_payroll():.2f}")
3. Demonstrate multiple inheritance with a class that inherits from two different sources,
each having a common method name, and observe the MRO. (See example under
"Multiple Inheritance" in theoretical questions).
Python and Data Handling:

1. Numpy Basic – Amazon ML Intern – 3Times (Reshape the Matrix) – Leetcode


2. Pandas Operation – Flipkart Analytics – 2 times (Merge Intervals) – Leetcode
3. Data Cleaning and Processing – Zomato ML round- 2Times(Missing Numbers) – Leetcode

Probability and Statistics:

4. Bayes Theorem Intuition – Bayesian Learning Basic Tutorial - kaggle


5. Hypothesis Testing- A/B Testing: Step by step and hypothesis testing
6. Normal Distribution- understanding the central limit

Machine learning Algorithm:

7. Linear Regression- linear regression from scratch


8. Logistic Regression-logistic regression classifier
9. Decision Tree-decision tree classifier
10. Random Forest- Random forest classifier
11. K-Means clustering- K-means clustering
12. PCA-

DEEP LEARNING:

13. Neural Network


14. Activation Function
15. CNN for Image Classification
16. RNN/LSTM

Difference between List and Dictionary comprehension

The fundamental difference between list and dictionary comprehension in Python lies in the
type of data structure they produce and their respective syntax.

1. Output Data Structure:

 List Comprehension:

Creates a new list. The result is an ordered sequence of elements, where each element is
derived from an expression applied to items in an iterable.

 Dictionary Comprehension:
Creates a new dictionary. The result is a collection of key-value pairs, where both the key and
the value are derived from expressions applied to items in an iterable.

2. Syntax:

 List Comprehension: Uses square brackets [] and defines a single expression for the
elements of the list.

Python

[expression for item in iterable if condition]

 Dictionary Comprehension: Uses curly braces {} and defines both a key and a value
expression, separated by a colon, for each key-value pair in the dictionary.

Python

{key_expression: value_expression for item in iterable if condition}

3. Purpose:

 List Comprehension:

Best suited for transforming or filtering elements from an existing iterable into a new list.

 Dictionary Comprehension:

Ideal for creating dictionaries from iterables, often by mapping elements to specific keys or
transforming existing key-value pairs.

Decorators”

In this example:

 log_function_call is our decorator function. It takes another function (func) as an


argument.

 Inside log_function_call, we define a nested function called wrapper. This wrapper


function is what will actually replace the original add or multiply function.

 The wrapper function takes *args and **kwargs to ensure it can accept any arguments
that the decorated function might take.

 Inside wrapper, we add our logging logic before calling the original func(*args,
**kwargs). We also log after the function finishes.

 Finally, the log_function_call decorator returns the wrapper function.


 The @log_function_call syntax above add and multiply is equivalent to saying add =
log_function_call(add) and multiply = log_function_call(multiply).

When you run this code, you'll see the logging messages before and after add and multiply are
executed, demonstrating how the decorator has 'wrapped' their behavior."

You might also like