python
python
PEP 8 is a coding convention for Python code. It is a set of guidelines for writing clear, readable code.
A Python module is a file containing Python definitions and statements. It can be imported and used in other
Python codes.
A Python package is a collection of modules. It can be imported and used in other Python codes.
Python 2 is the legacy, while Python 3 is the present and future of the language. Python 3 has better support for
Unicode and is more consistent in syntax.
A lambda function is an anonymous function in Python. It can take any number of arguments but can only have
one expression.
Python allows a user to add new functionality to an existing object without modifying its structure. This is
known as a decorator. It is a design pattern.
Q10. What is the use of the “if name == ‘main’:” statement in Python?
The “if name == ‘main’:” statement ensures that the code inside the block is only executed if the script is run as
the main program and not when it is imported as a module.
A virtual environment is an isolated Python environment that allows you to work on a specific project with its
dependencies and configurations without interfering with other projects on the same machine.
A module is a single file containing Python code, whereas a package is a directory containing multiple modules.
“is” checks if two objects refer to the same memory location, whereas “==” checks if the values of the two
objects are equal.
It is a programming paradigm that uses objects and classes to organize and structure code.
A class is a blueprint for creating objects in Python. It defines a set of attributes and methods that the objects
will have.
Inheritance is a feature of OOPs in Python. It allows a new class to be based on an existing class, inheriting all
its attributes and methods.
OOPs provides a way to organize code into reusable modules that can be used across multiple projects. It also
promotes modularity, making code easier to maintain and update. Additionally, OOPs provide encapsulation,
allowing data to be hidden and protected, and abstraction, allowing developers to focus on the interface of an
object rather than its implementation details.
Q18. What is encapsulation in Python?
Encapsulation is a feature of OOPs that allows data to be hidden and protected from the outside world. In
Python, encapsulation is achieved through the use of private and protected attributes and methods.
Polymorphism is a feature of OOPs that allows objects to take on different forms. In Python, polymorphism can
be achieved through method overloading or method overriding.
Method overloading is a feature of OOPs that allows a class to have multiple methods with the same name but
different parameters. In Python, method overloading can be achieved through the use of default arguments.
Method overriding is a feature of OOPs that allows a subclass to provide its implementation of a method that is
already defined in its superclass. In Python, method overriding is achieved by defining a method in the subclass
with the same name as the method in the superclass.
The “try” and “catch” blocks are used to deal with exceptions that are thrown while the program is running. It
happens due to coding or data mistakes. The “Try” block is the section of code where an exception occurs.
These exceptions are then caught and handled by the “catch” block.
Finally block is used to specify the code that is to be always executed before the method is finished. It is used
after the Try and Catch blocks and is executed regardless of whether an exception is thrown or caught.
A metaclass is a class that defines the behavior of other classes. It can be used to customize the creation and
behavior of classes.
A closure is a nested function that has access to the variables of its enclosing function, even after the enclosing
function has returned.
Q26. Explain split() and join() functions in Python.
The split() function is used to split a single string into a list of strings using a delimiter. The join() function is
used to join a list of strings based on a delimiter to give a single string.
During compile-time, the code is converted into executable code, and during run-time, the executable code runs.
A portion of code is checked during compile-time while other checks such as name and type happen during
execution. A non-existent function in the code will not affect the compilation process but it will lead to errors in
tests during execution or run-time.
A literal is a fixed value for primitive data types. There are five types of literals- String, Character, Numeric,
Boolean, and Literal collection.
A string literal is a text enclosed in single or double quotes and assigned to a variable.
A character literal is a single character enclosed in double quotes and assigned to a variable.
A numeric literal is a numeric value that can be an integer or a complex number or a floating point number and
assigned to a variable.
Boolean literals are two values true and false assigned to a variable.
Literal collections are of four types- list, tuple, dictionary, and set.
Indentation is a block of code within which code in loops, classes and functions, etc. Are specified. It is
specified using four space characters. Indentation is important for Python because if it is not specified, the code
will not execute properly and throw an error.
Comments in Python are written while starting with a “#” character. But we can also use docstrings or strings
enclosed within triple quotes.
Q31. Explain the function of the ‘is’, ‘not’, and ‘in’ operators.
The ‘is’ operator returns true when two operands are true. The ‘not’ operator returns the inverse of the boolean
value. The ‘in’ operator is used to check if some element is present in any sequence.
The “break” is used to allow loop termination when a condition is met and the control is passed on to the next
statement. With ‘continue’ we can allow some part of the loop to be skipped when a condition is met and the
control is passed on to the beginning of the loop.
Although same in their function, it is the result or the output that differs in range and xrange. The range function
returns a Python list object, whereas the xrange function returns an xrange object. Instead of creating a static list,
xrange creates the values as you need them.
A generator is a type of iterable in Python that generates values on the fly. It saves memory as it generates
values one at a time rather than storing them all in memory at once. You can learn Python programming online
to understand the subject matter better and to ace all your interviews.
Monkey patching is a technique in Python where a programmer modifies or extends the code of an existing
module, class, or function at runtime.
Docstrings in Python are the string literals that are enclosed in triple quotes. They are used for describing the
functionality of a function, method, class, or module. To access them, we can use the “__doc__” attribute.
Pickling, also known as serialisation, is a process where a Python object hierarchy is converted into a byte
stream to store it in a database. In unpickling, the byte stream is converted back into the object hierarchy.
In Python, slicing means accessing parts of a sequence. The sequence can be any mutable and iterable object.
We use the slice() function for slicing or dividing the sequence into required sections.
Namespaces in Python ensure that the object names in the program are unique and can be used without any
conflict. They are implemented as dictionaries, where ‘name as key’ corresponds to ‘object as value’. It helps in
multiple namespaces to use the same name and map it to separate objects.
PYTHONPATH is an environment variable that can be used to add additional directories where Python will
look for modules and packages.
The dir() function in Python is used to return a list of attributes and methods of an object. Since the aim of this
function is to return relevant information instead of complete information, its behavior varies from object to
object.
Os.remove(file_name)
The GIL (Global Interpreter Lock) is a mechanism in Python that ensures that only one thread executes Python
bytecode at a time. It can cause performance issues in multithreaded applications.
A list is an ordered collection of items, while a set is an unordered collection of unique items.
The “pass” keyword in Python is used as a placeholder to indicate that no code needs to be executed in a certain
block. It is often used to write empty functions or classes that will be filled in later.
The “map” function in Python is used to apply a function to each element of an iterable and return a new iterable
with the results. It is often used to transform one sequence into another.
The “filter” function in Python is used to create a new iterable by filtering out elements from an existing iterable
that do not meet a certain condition. It is often used to select a subset of items from a sequence.
The “reduce” function in Python is used to apply a function to each element of an iterable in succession,
reducing the sequence to a single value. It is often used to calculate a cumulative result over a sequence of
values.
The “zip” function in Python is used to combine two or more iterables into a single iterable by creating a tuple
of corresponding elements from each iterable. It is often used to iterate over multiple sequences simultaneously.
The “super” function in Python is used to call a method in a parent class from a subclass. It is often used to
extend the behavior of a parent class without modifying its code directly.
Some of the data types in Python are integers, floats, strings, lists, tuples, and dictionaries.
Q54. What is the use of “self” in Python?
“Self” is a reference to the instance of the class in Python. It is used to access the attributes and methods of the
class within the class itself.
Q55. What is the difference between a shallow copy and a deep copy in Python?
A shallow copy creates a new object that points to the same memory location as the original object, whereas a
deep copy creates a new object with its own memory space.
Model: It is the logical data structure that manages the whole program and is represented by a database.
View: It is the user interface or the website that we access in the browser. HTML/CSS/Javascript files represent
them.
Controller: It acts as the link between the model and the view by transferring data between them.
Scope in Python is a block of code that can contain many objects and still, all of them remain relevant. Some
examples of scope are:
Local Scope: A variable created inside a function and used within that function only is local scope.
Global Scope: A variable created inside the main body of the Python code and accessible within any part of the
code is known as a global scope.
Public Attribute: It makes a variable accessible everywhere, be it inside the class or outside it.
Private Attribute: It makes a variable accessible only within the current class.
Protected Attribute: It makes a variable accessible only within the current package.
Pandas is an open-source Python library consisting of a rich set of data structures to perform data-based
operations.
It is a one-dimensional data structure of Pandas which can store any type of data. It looks like an Excel column.
Q61. How to merge data frames in Pandas?
If the data that we want to merge consists of similar fields then it is merged along axis 0 otherwise they are
merged along axis 1.
NumPy or Numerical Python is a basic library for defining arrays and simple mathematical problems. SciPy or
Scientific Python is used for more complex problems, such as machine learning, numerical integration,
optimization, etc.
Def reverse_string(string):
Return string[::-1]
Def factorial(number):
If number == 0:
Return 1
Else:
Def is_palindrome(string):
Return string == string[::-1]
A: stg=’XYZ’
Print(stg.lower())
Print(my_tuple)
Global_var = 10
Def my_function():
Global global_var
Global_var += 10
My_function()
Print(global_var)
Def reverse_number(number):
Reverse = 0
While number > 0:
Remainder = number % 10
Number = number // 10
Return reverse
Number = 12345
Reversed_number = reverse_number(number)
Def is_prime(number):
If number <= 1:
Return False
If number % i == 0:
Return False
Return True
Number = 17
If is_prime(number):
Else:
Q71. Write the code to calculate the HCF of given numbers in Python.
While number2 != 0:
Return number1
Num1 = 48
Num2 = 60
Hcf_result = calculate_hcf(num1, num2)
Q72. Write the code to randomize the elements of the list while it’s running.
Import random
My_list = [1, 2, 3, 4, 5]
While True:
Random.shuffle(my_list)
If user_input == ‘exit’:
Break
Q73. Write a code to check if there are unique characters in a string in Python.
Def has_unique_characters(string):
Char_set = set()
If char in char_set:
Return False
Char_set.add(char)
Return True
If has_unique_characters(string):
Else:
Q74. Write a Python program to find the sum of all the even numbers in a list.
Def sum_of_evens(lst):
Def Fibonacci(n):
If n <= 1:
Return n
Else:
Return fibonacci(n-1) + fibonacci(n-2)
Class Node:
Self.data = data
Self.next = None
Def reverse_list(head):
Prev = None
Current = head
Next = current.next
Current.next = prev
Prev = current
Current = next
Return prev