Python Answers
Python Answers
Easy to code:
Python is a high-level programming language. Python is very easy to learn the language as
compared to other languages like C, C#, Javascript, Java, etc. It is very easy to code in python
language and anybody can learn python basics in a few hours or days. It is also a developer-
friendly language.
Free and Open Source:
Python language is freely available at the official website and you can download it from the
given download link below click on the Download Python keyword.
Object-Oriented Language:
One of the key features of python is Object-Oriented programming. Python supports object-
oriented language and concepts of classes, objects encapsulation, etc.
Python is Portable language:
Python language is also a portable language. For example, if we have python code for windows
and if we want to run this code on other platforms such as Linux, Unix, and Mac then we do not
need to change it, we can run this code on any platform.
Large Standard Library;
Python has a large standard library which provides a rich set of module and functions so you do
not have to write your own code for every single thing. There are many libraries present in
python for such as regular expressions, unit-testing, web browsers, etc.
2. Explain PVM.
Python Virtual Machine (PVM) is a program which provides programming environment.
The role of PVM is to convert the byte code instructions into machine code so the
computer can execute those machine code instructions and display the output
5. List out datatypes in python explain any two datatypes with example.
Text Type:str
Numeric
Types:int, float, complex
Sequence
Types:list, tuple, range
Mapping
Type:dict
Set Types:set, frozenset
Boolean
Type:bool
Binary Types: bytes, bytearray, memoryview
Mattie
written in lower case except True and False. There are 33 keywords in Python 3.7 let’s
go through all of them one by one.
Examples:
-It is possible for implicit conversions to lose information, signs can be lost (when signed
is implicitly converted to unsigned), and overflow can occur (when long long is implicitly
converted to float).
Explicit Type Conversion–
This process is also called type casting and it is user defined. Here the user can type
cast the result to make it of a particular data type.
Mattie
int main()
{
double x = 1.2;
return 0;
}
7.Floor division
1. Addition Operator : In Python, + is the addition operator. It is used to add 2 values
val1 = 2
val2 = 3
4. Division Operator : In Python, / is the division operator. It is used to find the quotient
when first operand is divided by the second.
Example :
val1 = 3
val2 = 2
Mattie
5. Modulus Operator : In Python, % is the modulus operator. It is used to find the
remainder when first operand is divided by the second.
Example :
val1 = 3
val2 = 2
There comes situations in real life when we need to make some decisions and based on
these decisions, we decide what should we do next. Similar situations arise in
Mattie
programming also where we need to make some decisions and based on these
decisions we will execute the next block of code. Decision-making statements in
programming languages decide the direction of the flow of program execution.
In Python, if else elif statement is used for decision making.
if statement
if statement is the most simple decision-making statement. It is used to decide whether
a certain statement or block of statements will be executed or not
i = 20
if (i < 15):
print("i is smaller than 15")
print("i'm in if Block")
else:
print("i is greater than 15")
print("i'm in else Block")
print("i'm not in if and not in else Block")
The for loop in Python is used to iterate over a sequence, which could be a list, tuple, array, or
string. The program operates as follows: We have assigned a variable, x, which is going to be
a placeholder for every item in our iterable object.
for in Loop: For loops are used for sequential traversal. For example: traversing a list or
string or array etc. In Python, there is no C style for loop, i.e., for (i=0; i<n; i++).
Mattie
n=4
for i in range(0, n):
print(i)
All the statements indented by the same number of character spaces after a
programming construct are considered to be part of a single block of code. Python uses
indentation as its method of grouping statements.
for i in range(n):
18. How to declare function in python? Explain with example.A function is a block of organized,
reusable code that is used to perform a single, related action. Functions provide better
modularity for your application and a high degree of code reusing.
As you already know, Python gives you many built-in functions like print(), etc. but you can
also create your own functions. These functions are called user-defined functions.
Defining a Function
You can define functions to provide the required functionality. Here are simple rules to define
a function in Python.
•Function blocks begin with the keyword def followed by the function name and
parentheses ( ( ) ).
•Any input parameters or arguments should be placed within these parentheses. You
can also define parameters inside these parentheses.
•The first statement of a function can be an optional statement - the documentation
string of the function or docstring.
•The code block within every function starts with a colon (:) and is indented.
•The statement return [expression] exits a function, optionally passing back an
expression to the caller. A return statement with no arguments is the same as return
None.
def printme( str ):
"This prints a passed string into this function"
print str
return
An interpreter is a kind of program that executes other programs. When you
write Python programs , it converts source code written by the developer
into intermediate language which is again translated into the native
language / machine language that is executed.
The python code you write is compiled into python bytecode, which creates
file with extension .pyc . The bytecode compilation happened internally, and
almost completely hidden from developer. Compilation is simply a translation
step, and byte code is a lower-level, and platform-independent ,
representation of your source code. Roughly, each of your source statements is
translated into a group of byte code instructions. This byte code translation is
performed to speed execution byte code can be run much quicker than the
original source code statements.
The .pyc file , created in compilation step, is then executed by appropriate
virtual machines. The Virtual Machine just a big loop that iterates through
your byte code instructions, one by one, to carry out their operations.
The Virtual Machine is the runtime engine of Python and it is always present
as part of the Python system, and is the component that truly runs the Python
scripts . Technically, it's just the last step of what is called the Python
interpreter.
Reference Counting
Reference counting works by counting the number of times an object is referenced by
other objects in the system. When references to an object are removed, the reference
count for an object is decremented. When the reference count becomes zero, the object
is deallocated.
21. Explain flavors of python
1. CPython : CPython is the Python compiler implemented in C
programming language. In this, Python code is internally converted into
the byte code using standard C functions. Additionally, it is possible to run
and execute programs written in C/C++ using CPython compiler.
2. Jython : Earlier known as JPython. Jython is an implementation of the
Python programming language designed to run on the Java platform.
Jython is extremely useful because it provides the productivity features of
a mature scripting language while running on a JVM.
3. PyPy : This is the implementation using Python language. PyPy often
runs faster than CPython because PyPy is a just-in-time compiler while
CPython is an interpreter.
4. IronPython : IronPython is an open-source implementation of the
Python programming language which is tightly integrated with the .NET
Framework.
5. RubyPython : RubyPython is a bridge between the Ruby and Python
interpreters. It embeds a Python interpreter in the Ruby application’s
process using FFI (Foreign Function Interface).
Mattie
6. Pythonxy : Python(x,y) is a free scientific and engineering development
software for numerical computations, data analysis and data visualization
based on Python.
7. StacklessPython : Stackless Python is a Python programming language
interpreter. In practice, Stackless Python uses the C stack, but the stack is
cleared between function calls
8. AnacondaPython : Anaconda is a free and open-source distribution of
the Python and R programming languages for scientific computing, that
aims to simplify package management and deployment. Package versions
are managed by the package management system conda.
22. Explain the following terms with example: Tuple, List, set
Lists: are just like dynamic sized arrays, declared in other languages (vector in C+
+ and ArrayList in Java). Lists need not be homogeneous always which makes it the
most powerful tool in Python.
Set: A Set is an unordered collection data type that is iterable, mutable, and has no
duplicate elements. Python’s set class represents the mathematical notion of a set.
append (item): This method is used to add new element at the end of the list.
insert (index,item): This method is used to insert any item in the particular index of
the list and right shift the list items.
remove (item): This method is used to remove particular item from the list.
remove
# Define the list
list = ['Cake', 'Pizza', 'Juice', 'Pasta', 'Burger']
# Remove an item
list.remove('Juice')
their algorithms. Following are the important terms to understand the concept of
Array.
Basic Operations
Following are the basic operations supported by an array.
•Traverse − print all the array elements one by one.
•Insertion − Adds an element at the given index.
•Deletion − Deletes an element at the given index.
•Search − Searches an element using the given index or by the value.
•Update − Updates an element at the given index.
Creating a Function
We can create a Python function using the def keyword.
Calling a Function
After creating a function we can call it by using the name of the function followed by
parenthesis containing parameters of that particular function.
Arguments of a Function
Arguments are the values passed inside the parenthesis of the function. A function can
have any number of arguments separated by a comma.
Mattie
def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")
# Driver code to call the function
evenOdd(2)
evenOdd(3)
Python Lambda Functions are anonymous function means that the function is without a
name. As we already know that the def keyword is used to define a normal function in
Python. Similarly, the lambda keyword is used to define an anonymous function in
Python.
Lambda functions can have any number of arguments but only one expression. The
expression is evaluated and returned. Lambda functions can be used wherever
function objects are required.
x ="GeeksforGeeks"
__init__
The __init__ method is similar to constructors in C++ and Java. Constructors are used to
initialize the object’s state. The task of constructors is to initialize(assign values) to the
data members of the class when an object of class is created. Like methods, a
constructor also contains collection of statements(i.e. instructions) that are executed at
time of Object creation. It is run as soon as an object of a class is instantiated. The
method is useful to do any initialization you want to do with your object.
in __init__() function.
• All classes have a function called __init__(), which is always executed
when the class is being initiated.
• Use the __init__() function to assign values to object properties, or
other operations that are necessary to do when the object is being
created:
Person, use the __init__() function to assign values
for name and age:
• class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
Class/ object
• Python is an object oriented programming language.
Mattie
class Employee:
1. id = 10
2. name = "Devansh"
3. def display (self):
4. print(self.id,self.name)
5.
An object is simply a collection of data (variables) and methods (functions) that act on those data.
Similarly, a class is a blueprint for that object.
Inheritance is defined as the capability of one class to derive or inherit the properties
from some other class and use it whenever needed. Inheritance provides the following
properties:
•It represents real-world relationships well.
•It provides reusability of code. We don’t have to write the same code again and
again. Also, it allows us to add more features to a class without modifying it.
•It is transitive in nature, which means that if class B inherits from another class A,
then all the subclasses of B would automatically inherit from class A.
Mattie
Multiple Inheritance: When a class can be derived from more than one base class
this type of inheritance is called multiple inheritance. In multiple inheritance, all the
features of the base classes are inherited into the derived class.
Multilevel Inheritance
In multilevel inheritance, features of the base class and the derived class are further
inherited into the new derived class. This is similar to a relationship representing a child
and grandfather.
Hierarchical Inheritance: When more than one derived classes are created from a single
base this type of inheritance is called hierarchical inheritance. In this program, we have
a parent (base) class and two child (derived) classes.
32. What is the use of super keyword?
As we all know that, Python is an object-oriented programming language. Therefore,
Python follows all the concepts of OOPs, and one of such concepts is inheritance.
While using the inheritance concept, we can refer to a parent class with the use of super()
function inside the inherited or child class. The super() function we use in the child class
returns a temporary created object of the superclass, that allow us to access all of its method
present in the child class.
We don't need to remember the parent's class name while using the super() function.
This is because we don't have to specify the name of the parent class to access the
methods present in it.
Mattie
We can use the super() function with the single inheritance and multiple inheritances.
The super() function in Python implements code reusability and modularity as there is
no need for us to rewrite the whole function again and again.
The super() function in Python is known as dynamical function, as we all know that
Python is a dynamically typed programming language.
# Constructor
def __init__(self):
self.value = "Inside Parent"
print(self.value)
# Constructor
def __init__(self):
self.value = "Inside Child"
# Driver's code
obj1 = Parent()
obj2 = Child()
obj1.show()
obj2.show()
Python provides a way to handle the exception so that the code can be executed without any
interruption. If we do not handle the exception, the interpreter doesn't execute all the code
that exists after the exception.
Python has many built-in exceptions that enable our program to run without interruption
and give the output. These exceptions are given below:
Mattie
Common Exceptions
Python provides the number of built-in exceptions, but here we are describing the common
standard exceptions. A list of common exceptions that can be thrown from a standard Python
program is given below.
5.EOFError: It occurs when the end of the file is reached, and yet operations are being
performed.
•If any exception occurs, but the except clause within the code doesn’t handle it, it is
passed on to the outer try statements. If the exception is left unhandled, then the
execution stops.
•A try statement can have more than one except clause.
Python provides a keyword finally, which is always executed after try and except blocks.
The finally block always executes after normal termination of try block or after try block
terminates due to some exception.
Break statement
The break statement is used to terminate the loop or statement in which it is present.
After that, the control will pass to the statements that are present after the break
statement, if available. If the break statement is present in the nested loop, then it
terminates only those loops which contains break statement.
Continue statement
Continue is also a loop control statement just like the break statement. continue statement
is opposite to that of break statement, instead of terminating the loop, it forces to
execute the next iteration of the loop.
As the name suggests the continue statement forces the loop to continue or execute the
next iteration. When the continue statement is executed in the loop, the code inside the
loop following the continue statement will be skipped and the next iteration of the loop
will begin.