0% found this document useful (0 votes)
156 views22 pages

Python Answers

Python is an object-oriented, high-level programming language with dynamic semantics. It has built-in data structures, dynamic typing, and dynamic binding, which make it suitable for rapid application development and scripting. Python is easy to code, free and open source, supports object-oriented programming, and is portable across different platforms. It has a large standard library.

Uploaded by

Sahil Chauahan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
156 views22 pages

Python Answers

Python is an object-oriented, high-level programming language with dynamic semantics. It has built-in data structures, dynamic typing, and dynamic binding, which make it suitable for rapid application development and scripting. Python is easy to code, free and open source, supports object-oriented programming, and is portable across different platforms. It has a large standard library.

Uploaded by

Sahil Chauahan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 22

Mattie

1. What is Python? Explain features of Python.


Python is an object-oriented, high-level programming language with dynamic semantics.
Its high-level built in data structures, combined with dynamic typing and dynamic binding, make
it very attractive for Rapid Application Development, as well as for use as a scripting or glue
language to connect existing components together.

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

3. Comparison between c and Python.


4. Comparison between Java and Python.

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

6. What is the difference between list and tuple?

7. Explain variable in python with example.


Python is not “statically typed”. We do not need to declare variables before using them
or declare their type. A variable is created the moment we first assign a value to it. A
variable is a name given to a memory location. It is the basic unit of storage in a
program.
•The value stored in a variable can be changed during program execution.
•A variable is only a name given to a memory location, all the operations done on the
variable effects that memory location.
Rules for creating variables in Python:
•A variable name must start with a letter or the underscore character.
•A variable name cannot start with a number.
•A variable name can only contain alpha-numeric characters and underscores (A-z,
0-9, and _ ).
•Variable names are case-sensitive (name, Name and NAME are three different
variables).
•The reserved words(keywords) cannot be used naming the variable.

8. list out the rules for identifiers in python

• Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits


(0 to 9) or an underscore _ . ...
• An identifier cannot start with a digit. ...
• Keywords cannot be used as identifiers. ...
• We cannot use special symbols like !, @, #, $, % etc. ...
• An identifier can be of any length.

9. Explain keyword in python.


The keywords are some predefined and reserved words in python that have special
meanings. Keywords are used to define the syntax of the coding. The keyword cannot
be used as an identifier, function, and variable name. All the keywords in python are
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:

No.    Keywords                                                                              Description


This is a logical operator it returns true if both the operands are true else
1 and
return false.
This is also a logical operator it returns true if anyone operand is true else
2 Or
return false.
This is again a logical operator it returns True if the operand is false else
3 not
return false.
4 if This is used to make a conditional statement.
Elif is a condition statement used with if statement the elif statement is
5 elif
executed if the previous conditions were not true
Else is used with if and elif conditional statement the else block is
6 else
executed if the given condition is not true.

10. Explain type conversion with example.


A type cast is basically a conversion from one type to another. There are two types of
type conversion:
Implicit Type Conversion
Also known as ‘automatic type conversion’.
•Done by the compiler on its own, without any external trigger from the user.
•Generally takes place when in an expression more than one data type is present. In
such condition type conversion (type promotion) takes place to avoid loss of data.
•All the data types of the variables are upgraded to the data type of the variable with
largest data type

-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

// C program to demonstrate explicit type casting


#include<stdio.h>

int main()
{
double x = 1.2;

// Explicit conversion from double to int


int sum = (int)x + 1;

printf("sum = %d", sum);

return 0;
}

11. Explain arithmetic operator with example.


Arithmetic operators are used to perform mathematical operations like addition,
subtraction, multiplication and division.
There are 7 arithmetic operators in Python :
1.Addition
2.Subtraction
3.Multiplication
4.Division
5.Modulus
6.Exponentiation
Mattie

7.Floor division

1. Addition Operator : In Python, + is the addition operator. It is used to add 2 values

val1 = 2
val2 = 3

# using the addition operator


res = val1 + val2
print(res)

2. Subtraction Operator : In Python, – is the subtraction operator. It is used to subtract


the second value from the first value.
Example :
val1 = 2
val2 = 3

# using the subtraction operator


res = val1 - val2
print(res)

3. Multiplication Operator : In Python, * is the multiplication operator. It is used to find


the product of 2 values.
Example :
val1 = 2
val2 = 3

# using the multiplication operator


res = val1 * val2
print(res)

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

# using the division operator


res = val1 / val2
print(res)

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

# using the modulus operator


res = val1 % val2
print(res)
6. Exponentiation Operator : In Python, ** is the exponentiation operator. It is used to
raise the first operand to power of second.
Example :
val1 = 2
val2 = 3

# using the exponentiation operator


res = val1 ** val2
print(res)
7. Floor division : In Python, // is used to conduct the floor division. It is used to find the
floorof the quotient when first operand is divided by the second.
Example :
val1 = 3
val2 = 2

# using the floor division


res = val1 // val2
print(res)

12. Explain if loop with example.

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

# python program to illustrate If else statement


#!/usr/bin/python

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")

15. Explain for loop with example.

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

# Python program to illustrate


# Iterating over range 0 to n-1

n=4
for i in range(0, n):
print(i)

16. Explain while loop with example.


While Loop: 
1.In python, while loop is used to execute a block of statements repeatedly until a
given condition is satisfied. And when the condition becomes false, the line
immediately after the loop in the program is executed.

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. 

# Python program to illustrate


# while loop
count = 0
while (count < 3):
count = count + 1
print("Hello ")

17. How to use pass statement in python?


The pass statement is a null statement. But the difference between pass and comment
is that comment is ignored by the interpreter whereas pass is not ignored. 
The pass statement is generally used as a placeholder i.e. when the user does not know
what code to write. So user simply places pass at that line. Sometimes, pass is used
when the user doesn’t want any code to execute. So user can simply place pass where
empty code is not allowed, like in loops, function definitions, class definitions, or in if
statements. So using pass statement user avoids this error.
n = 10
Mattie

for i in range(n):

# pass can be used as placeholder


# when code is to added later
pass

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

19. How the python is interpreted the code?


Mattie

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.

20. How is memory managed in python?


In Python memory allocation and deallocation method is automatic as the Python
developers created a garbage collector for Python so that the user does not have to do
manual garbage collection.
Garbage Collection
Garbage collection is a process in which the interpreter frees up the memory when not
in use to make it available for other objects.
Assume a case where no reference is pointing to an object in memory i.e. it is not in use
so, the virtual machine has a garbage collector that automatically deletes that object
from the heap memory
Note: For more information, refer to Garbage Collection in Python
Mattie

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.

thislist = ["apple", "banana", "cherry"]


print(thislist)

Tuple: A Tuple is a collection of Python objects separated by commas. In some ways, a


tuple is similar to a list in terms of indexing, nested objects, and repetition but a tuple is
immutable, unlike lists that are mutable

thistuple = ("apple", "banana", "cherry")


print(thistuple).

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.

thisset = {"apple", "banana", "cherry"}


print(thisset)
Mattie

25. How to add and remove elements from List?

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.

# Define the list


listdata = ["Dell", "HP", "Leveno", "Asus"]

# Insert data using append method


listdata.append("Toshiba")

# Display the list after insert


print("The list elements are")

for i in range(0, len(listdata)):


print(listdata[i])

remove
# Define the list
list = ['Cake', 'Pizza', 'Juice', 'Pasta', 'Burger']

# Print the list before delete


print("List before delete")
print(list)

# Remove an item
list.remove('Juice')

# Print the list after delete


print("List after delete")
print(list)

26. What is array? What type of operations we can perform on array?


Array is a container which can hold a fix number of items and these items should
be of the same type. Most of the data structures make use of arrays to implement
Mattie

their algorithms. Following are the important terms to understand the concept of
Array.

•Element− Each item stored in an array is called an element.


•Index − Each location of an element in an array has a numerical index, which is used
to identify the element.

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.

27. What is function? Types of function with appropriate example


Python Functions is a block of related statements designed to perform a computational,
logical, or evaluative task. The idea is to put some commonly or repeatedly done tasks
together and make a function so that instead of writing the same code again and again
for different inputs, we can do the function calls to reuse code contained in it over and
over again. 
Functions can be both built-in or user-defined. It helps the program to be concise, non-
repetitive, and organized.

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

# A simple Python function to check


# whether x is even or odd

def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")
# Driver code to call the function
evenOdd(2)
evenOdd(3)

# A simple Python function

28. What is lambda function?

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.

Python program to demonstrate


# lambda functions
Mattie

x ="GeeksforGeeks"

# lambda gets pass to print


(lambda x : print(x))(x)

29. Explain __init__() function

__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

• Almost everything in Python is an object, with its properties and


methods.
• A Class is like an object constructor, or a "blueprint" for creating
objects.
• To create a class use class keyword.
• class MyClass:
x=5
print(MyClass)

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.

31. What is inheritance? Expain types of inheritance.

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

Single Inheritance: Single inheritance enables a derived class to inherit properties


from a single parent class, thus enabling code reusability and the addition of new
features to existing code.

 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.

Benefits of super() function:


Following are the benefits of using a super() function in 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.

33. What is method overriding? Explain with example.


Method overriding is an ability of any object-oriented programming language that allows
a subclass or child class to provide a specific implementation of a method that is already
provided by one of its super-classes or parent classes. When a method in a subclass
has the same name, same parameters or signature and same return type(or sub-type)
as a method in its super-class, then the method in the subclass is said to override the
method in the super-class.
The version of a method that is executed will be determined by the object that is used to
invoke it. If an object of a parent class is used to invoke the method, then the version in
the parent class will be executed, but if an object of the subclass is used to invoke the
method, then the version in the child class will be executed. In other words, it is the type
of the object being referred to (not the type of the reference variable) that determines
which version of an overridden method will be executed.

# Python program to demonstrate


# method overriding

# Defining parent class


class Parent():

# Constructor
def __init__(self):
self.value = "Inside Parent"

# Parent's show method


def show(self):
Mattie

print(self.value)

# Defining child class


class Child(Parent):

# Constructor
def __init__(self):
self.value = "Inside Child"

# Child's show method


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

# Driver's code
obj1 = Parent()
obj2 = Child()

obj1.show()
obj2.show()

34. What is Exception handling in python?

An exception can be defined as an unusual condition in a program resulting in the


interruption in the flow of the program.
Whenever an exception occurs, the program stops the execution, and thus the further code is
not executed. Therefore, an exception is the run-time errors that are unable to handle to
Python script. An exception is a Python object that represents an error

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.

1.ZeroDivisionError: Occurs when a number is divided by zero.

2.NameError: It occurs when a name is not found. It may be local or global.

3.IndentationError: If incorrect indentation is given.

4.IOError: It occurs when Input Output operation fails.

5.EOFError: It occurs when the end of the file is reached, and yet operations are being
performed.

In Python, exceptions can be handled using a try statement.


The critical operation which can raise an exception is placed inside the try clause.
The code that handles the exceptions is written in the except clause.

35. Explain Try,except and finally keyword with example


•Try: This block will test the excepted error to occur
•Except:  Here you can handle the error
•Else: If there is no exception then this block will be executed
•Finally: Finally block always gets executed either exception is generated or not

Let’s first understand how the try and except works –


•First try clause is executed i.e. the code between try and except clause.
•If there is no exception, then only try clause will run, except clause will not get
executed.
•If any exception occurs, the try clause will be skipped and except clause will run.
Mattie

•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.

36. Explain different types of file access modes.

43. What is break and continue statement?

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.

You might also like