0% found this document useful (0 votes)
16 views

PYTHON QUESTION BANK (1)

The document outlines the benefits and features of Python, highlighting its ease of use, dynamic typing, and extensive libraries. It also discusses control statements, data structures, and memory management in Python, along with key programming concepts such as inheritance and modules. Additionally, it provides examples and explanations of various programming constructs and their applications.

Uploaded by

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

PYTHON QUESTION BANK (1)

The document outlines the benefits and features of Python, highlighting its ease of use, dynamic typing, and extensive libraries. It also discusses control statements, data structures, and memory management in Python, along with key programming concepts such as inheritance and modules. Additionally, it provides examples and explanations of various programming constructs and their applications.

Uploaded by

Keerthivasan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

PYTHON

1. What are the benefits of using Python?

1. Easy to use– Python is a high-level programming language that is easy to


use, read, write and learn.
2. Interpreted language– Since python is interpreted language, it executes
the code line by line and stops if an error occurs in any line.
3. Dynamically typed– the developer does not assign data types to
variables at the time of coding. It automatically gets assigned during
execution.
4. Free and open source– Python is free to use and distribute. It is open
source.
5. Extensive support for libraries– Python has vast libraries that contain
almost any function needed. It also further provides the facility to import
other packages using Python Package Manager(pip).
6. Portable– Python programs can run on any platform without requiring
any change.
7. The data structures used in python are user friendly.
8. It provides more functionality with less coding.

2. What are Keywords in Python?

Keywords in python are reserved words that have special meaning. They are
generally used to define type of variables. Keywords cannot be used for variable
or function names. There are following 33 keywords in python-

E.g..,

• And
• Or
• Not
• If
• Elif
• Else
• For
• While

www.imageconindia.com/academy
3. Why is Python considered to be a highly versatile programming
language?
Answer:
Python is considered to be a highly versatile programming language
because it supports multiple models of programming such as:

• OOP
• Functional
• Imperative
• Procedural

4. What are the advantages of choosing Python over any other


programming language?
Answer:
The advantages of selecting Python over other programming languages
are as follows:

• Extensible in C and C++.


• It is dynamic in nature.
• Easy to learn and easy to implement.
• Third-party operating modules are present: As the name
suggests a third-party module is written by a third party which
means neither you nor the python writers have developed it.
However, you can make use of these modules to add
functionality to your code.

5. What do you mean when you say that Python is an interpreted


language?
Answer:
When we say that Python is an interpreted language it means that python
code is not compiled before execution. Code written in compiled
languages such as Java can be executed directly on the processor because
it is compiled before runtime and at the time of execution it is available in
the form of machine language that the computer can understand. This is
not the case with Python. It does not provide code in machine language

www.imageconindia.com/academy
before runtime. The translation of code to machine language occurs while
the program is being executed.

6. Are there any other interpreted languages that you have heard of?
Answer:
Some frequently used interpreted programming languages are as follows:

• Python
• Pearl
• JavaScript
• PostScript
• PHP
• PowerShell

7. Is Python dynamically typed?


Answer:
Yes, Python is dynamically typed because in a code we need not specify
the type of variables while declaring them. The type of a variable is not
known until the code is ‘executed.

8. Python is a high-level programming language? What is a need for


high-level programming languages?
Answer:
High-level programming languages act as a bridge between the machine
and humans. Coding directly in machine language can be a very time-
consuming and cumbersome process and it would definitely restrict
coders from achieving their goals. High-level programming languages like
Python, JAVA, C++, etc are easy to understand. They are tools that
programmers can use for advanced-level programming. High-level
languages allow developers to code complex code that is then translated
to machine language so that the computer can understand what needs to
be done.

9. Is it true that Python can be easily integrated with C, C++, COM,


ActiveX, CORBA, and Java?
Answer:
Yes

www.imageconindia.com/academy
10. What are the different modes of programming in Python?
Answer:
There are two modes of programming in Python:
1. Interactive Mode Programming:
In this, we invoke the interpreter without passing any script or python file.
We can start the Python command-line interpreter or the Python shell in
IDLE and start passing instructions and get instant results.
2. Script Mode of Programming:
Saving code in a Python file. When the script is executed the interpreter is
invoked and it is active as long as the script is running. Once all the
instructions of the script are executed the interpreter is no longer active.

11. Once Python is installed, how can we start working on code?


Answer:
After Python is installed there are three ways to start working on code:

1. You can start an interactive interpreter from the command line and
start writing the instructions after the »> prompt.

2. If you intend to write a code of several lines then it would be a wise


decision to save your file or script with the .py extension and you can
execute these files from the command line. Multiline programs can be
executed on an interactive interpreter, also but it does not save the work.

3. Python also has its own GUI environment known as Integrated


Development Environment (IDLE). IDLE helps programmers write code
faster as it helps with automatic indenting and highlights different
keywords in different colors. It also provides an interactive environment. It
has two windows: the shell provides an interactive environment whereas
the editor allows you to save your scripts before executing the code
written in it.

www.imageconindia.com/academy
12. What is the function of the interactive shell?
Answer:
The interactive shell stands between the commands given by the user and
the execution done by the operating system. It allows users to use easy
shell commands and the user need not be bothered about the
complicated basic functions of the Operating System. This also protects
the operating system from incorrect usage of system functions.

13. How to exit interactive mode?


Answer:
Ctrl+D or exit( ) can be used to quit interactive mode.

14. Which character set does Python use?


Answer:
Python uses a traditional ASCII character set.

15. What is the purpose of indentation in Python?


Answer:
Indentation is one of the most distinctive features of Python. While in
other programming languages, developers use indentation to keep their
code neat but in the case of Python, indentation is required to mark the
beginning of a block or to understand which block the code belongs to. No
braces are used to mark blocks of code in Python. Blocks in code are
required to define functions, conditional statements, or loops. These
blocks are created simply by the correct usage of spaces. All statements
that are the same distance from the right belong to the same block.

www.imageconindia.com/academy
Remember:

• The first line of the block always ends with a semicolon (:).
• Code under the first line of the block is indented. The
preceding diagram depicts a scenario of indented blocks.
• Developers generally use four spaces for the first level and
eight spaces for a nested block, and so on.

16. Explain Reference counting and Garbage collection in Python.


Answer:
Unlike languages like C/ C++, the process of allocation and deallocation of
memory in Python is automatic. This is achieved with the help of reference
counting and garbage collection.

As the name suggests, reference counting counts the number of times an


object is referred to by other objects in a program. Every time a reference
to an object is eliminated, the reference count decreases by 1. As soon as
the reference count becomes zero, the object is deallocated. An object’s
reference count decreases when an object is deleted, the reference is
reassigned or the object goes out of scope. The reference count increases
when an object is assigned a name or placed in a container.

Garbage collection on the other hand allows Python to free and reclaim
blocks of memory that are no longer of any use. This process is carried out
periodically. The garbage collector runs while the program is being

www.imageconindia.com/academy
executed and the moment the reference count of an object reaches zero,
the garbage collector is triggered.

17. What are multi-line statements?


Answer:
All the statements in Python end with a newline. If there is a long
statement, then it is a good idea to extend it over multiple lines. This can
be achieved using the continuation character (\).

Explicit line continuation is when we try to split a statement into multiple


lines whereas in the case of implicit line continuation we try to split
parentheses, brackets, and braces into multiple lines.
Example for multiple line statements:

Explicit:

>>> first_num = 54
>>> second_num = 879
>>> third__num = 8 76
>>> total = first_num +\
second_num+\
third_num
>>> total
1809
>>>
Implicit:
>>> weeks=['Sunday' ,
'Monday',
'Tuesday',
'Wednesday',
'Thursday' ,
'Friday',
'Saturday']
>>> weeks
['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursdy', 'Friday', 'Saturday']
>>>

18. Who created python and when?

Answer: Python was created by Guido van Rossum, and released in 199

www.imageconindia.com/academy
CONTROL STATEMENTS
1. Python executes one statement after another from beginning
to the end of the program. This is a ________________

Ans. Sequential Construct

2. The order of execution of the statements in a program is


known as ______

Ans. flow of control

3.Python supports _____________ types of control structures.

Ans. 2

4. Which of the following are control structure in python?

Ans. a. Selection
b. Iteration

5. In programming, the concept of decision making or selection


is implemented with the help of ___________ statement

Ans. if else

6. Execution of statements in _________________ construct depend


on a condition test.

Ans. Selection

www.imageconindia.com/academy
8. ______ statements can be written in if block.

Ans. Any number of

9. An ‘if’ condition inside another ‘if’ is called ___

Ans. Nested if

10. Write the output of the following code :

if True:
print("Hello")
else:
print("Bye")

Ans. Hello

11. Write the output of the following code :

y=2
if 2!=y:
print("H")
else :
print("K")

Ans. K

12 . ____ is an empty statement in Python.

Ans. Pass

www.imageconindia.com/academy
13. Write the output of the following :

x = 10
if x > 7:
print("Hello")
print("Bye")
Ans. Hello, Bye

14. Ravi wants to display “Hello”, if the condition is True,


otherwise, “Pass” if the condition is False. Which of the following
help to implement the same?

Ans. if .. else statement

15. Ram wants to create a program to check whether an year is


leap year or not. For this he should have a good understanding
of ____________

Ans. Conditional Statement

16. What is the purpose of ‘else’ statement in if-elif ladder?

Ans. else statement in if-elif will execute, if none of the condition is


True.

17. To write else statement in if-elif ladder is mandatory? (T/F)

Ans. false

18. Number of elif in if-elif ladder depends on ____


a. number of conditions to be checked in program.

www.imageconindia.com/academy
19. Write the output of the following :

x = 10
if x > 7 and x <= 10:
print("Pass", end="")
print("Fail")

Ans. Pass Fail

20. Write the output of the following :

if 'i' == "i" :
print(True)
else:
print("False")
Ans. True

www.imageconindia.com/academy
DATA STRUCTURES

1. Enumerate differences between a list and a tuple in Python


This is one of the basic Python data structures interview questions. Here’s how
you can answer it:

The key differences between a list and a tuple are:

2. How is a list different from an array?


The differences between lists and arrays are:

www.imageconindia.com/academy
3. Describe three advantages of NumPy arrays over Python lists
This is yet another popular Python data structure interview question. The three
advantages of NumPy arrays over Python lists are:

• NumPy array is faster. The size of the NumPy arrays increases. It can
become thirty times faster than Python lists.

• NumPy is more efficient and convenient. It comes with several vector and
matrix operations for free, which helps avoid unnecessary work.
Moreover, they can be efficiently implemented.

• Lastly, Python lists have certain limitations, like they don’t support
element-wise addition, multiplication, and other vectorized operations. In
addition, since lists contain heterogeneous objects, Python must store
type information for every element. Contrastingly, arrays have
homogeneous objects and thus escape these limitations

4. Why is Python a dynamically typed language?


Dynamic type checking means data types are checked during execution. Python
is an interpreted language. It executes each statement line by line. So, type-
checking is done during execution, making Python a dynamically typed language.

5. What do you understand about inheritance in Python?


To answer this Python, you should know that inheritance is the property of one
class to attain all the members (attributes and methods) of another class.
Inheritance allows the reusability of code and makes it easier to create an
application. It gives rise to two types of classes:

• Superclass is the class from which we are inheriting. It is also called the
base class.

• Derived Class is the class that is inherited. It is also called the child class.
The various types of inheritance in Python are:

• Single Inheritance is when a derived class takes the members of a single


superclass.

www.imageconindia.com/academy
• Multi-level inheritance is when a derived class d1 is inherited from the
base class- base1, and another derived class d2 is inherited from base2.

• Hierarchical inheritance allows the inheritance of a number of child


classes from a single base class.

• Multiple inheritances are when a child class is inherited from more than
one superclass.

6. What do you understand about the join method in Python?


In Python, the join method is a string method. It takes elements of an iterable
data structure (array, lists, and more) and connects them together using a string
connector value.

7. What are control flow statements in Python?


This is a common Python data structure interview question asked in tech
interviews. This is how you can answer this particular question:

A program’s control flow refers to the order in which the program’s code
executes. In Python, the control flow is regulated by conditional loops,
statements, and function calls.

It has three main types of control structures:

• Sequential is the default mode

• Selection is used for decisions and branching

• Repetition helps in looping

8. Explain memory management in Python.


Python private heap space manages memory, i.e., all objects and data structures
of Python are located in a private heap. The python interpreter executes this
heap, and no programmer has access to it. Python's memory manager allocates
heap space for Python objects. Additionally, Python has an inbuilt garbage
collector. It recycles all the unused memory.

www.imageconindia.com/academy
9. What are modules in Python? State a few benefits of modules.
This Python data structure interview question tests your basic understanding of
the language. A Python module is a file containing a set of variables and
functions that can be used in an application. The variables can be in the form of
arrays, dictionaries, and objects.

Modules fall into two main categories:

• Built-in

• User-defined

Some key benefits of Python modules are:

• It allows structured code organization wherein code is logically grouped


into a Python file. Thus, making development easier and less error-prone.

• Reusability of code as functionality in a single module can easily be


reused. There is no need to recreate duplicate code.

10. Explain slicing in Python.


Slicing is the mechanism to choose a range of items from sequence types such
as lists, tuples, and strings. For example, slicing a list refers to selecting a specific
portion or a subset of the list for some function, and the rest of the list remains
unaffected. So, you remove a piece with

11. What is a stack? What are the applications of stack?

▪ Stack is a linear data structure that follows LIFO (Last In First Out) approach
for accessing elements.
▪ Push, pop, and top (or peek) are the basic operations of a stack.
▪ Following are some of the applications of a stack:
o Check for balanced parentheses in an expression
o Evaluation of a postfix expression
o Problem of Infix to postfix conversion
o Reverse a string

www.imageconindia.com/academy
12. What is a queue? What are the applications of queue?

▪ A queue is a linear data structure that follows the FIFO (First In First Out)
approach for accessing elements.
▪ Dequeue from the queue, enqueue element to the queue, get front
element of queue, and get rear element of queue are basic operations that
can be performed.
▪ Some of the applications of queue are:
o CPU Task scheduling
o BFS algorithm to find shortest distance between two nodes in a
graph.
o Website request processing
o Used as buffers in applications like MP3 media player, CD player, etc.
o Managing an Input stream

13. How is a stack different from a queue?

▪ In a stack, the item that is most recently added is removed first whereas in
queue, the item least recently added is removed first.

14. Write a Python program to sum all the items in a list.


def sum_list(items):

sum_numbers = 0

for x in items:

sum_numbers += x

return sum_numbers

print(sum_list([1,2,-8]))

www.imageconindia.com/academy
15. Write a Python program to multiply all the items in a list.
def multiply_list(items):

tot = 1

for x in items:

tot *= x

return tot

print(multiply_list([1,2,-8]))

16. Write a Python program to get the largest number from a


list.

def max_num_in_list( list ):


max = list[ 0 ]
for a in list:
if a > max:
max = a
return max
print(max_num_in_list([1, 2, -8, 0]))

17. Write a Python program to get the smallest number from a


list.

def smallest_num_in_list( list ):

min = list[ 0 ]

for a in list:

if a < min:

min = a

return min

print(smallest_num_in_list([1, 2, -8, 0]))

www.imageconindia.com/academy
18. Write a Python program to remove duplicates from a list.

a = [10,20,30,20,10,50,60,40,80,50,40]

dup_items = set()

uniq_items = []

for x in a:

if x not in dup_items:

uniq_items.append(x)

dup_items.add(x)

print(dup_items)

Functions

1. What are functions in Python?


Ans: A function is a block of code which is executed only when it is called. To

define a Python function, the def keyword is used.

2. What is __init__?
Ans: __init__ is a method or constructor in Python. This method is automatically

called to allocate memory when a new object/ instance of a class is created. All

classes have the __init__ method.

3. What is a lambda function?


Ans: A n anonymous function is known as a lambda function. This function can
have any number of parameters but, can have just one statement.

www.imageconindia.com/academy
4. What is self in Python?
Ans: Self is an instance or an object of a class. In Python, this is explicitly included
as the first parameter. However, this is not the case in Java where it’s optional. It

helps to differentiate between the methods and attributes of a class with local

Variables.

5. How many types of arguments in python ?


Ans:

1. default arguments

2. keyword arguments

3. positional arguments

4. arbitrary positional arguments

5. arbitrary keyword arguments

6. What is Default Arguments in python?


Ans: Default arguments in Python functions are those arguments that take
default

values if no explicit values are passed to these arguments from the function call.

7. Lambda Function used for?


Ans: We use lambda functions when we require a nameless function for a short

period of time. we generally use it as an argument to a higher-order function (a

Function that takes in other functions as arguments).Lambda functions are used


along with built-in functions like filter() , map() etc.

www.imageconindia.com/academy
8. What is Recursion?
Ans: Python also accepts function recursion, which means a defined function can
call itself. Recursion is a common mathematical and programming concept. It

means that a function calls itself. This has the benefit of meaning that you can
loop through data to reach a result.

9. What is main function ?


Ans: The main function in Python acts as the point of execution for any program

Defining the main function in Python programming is a necessity to start the

execution of the program as it gets executed only when the program is run
directly

and not executed when imported as a module

10. What is __main__ in Python?


Ans:Python Main Function is the beginning of any Python program. When we run
a program, the interpreter runs the code sequentially and will not run the main

function if imported as a module, but the Main Function gets executed only
when it is run as a Python program.

11. What is Keyword Arguments?


Ans: If you want to make sure that you call all the parameters in the right order,

you can use the keyword arguments in your function call. You use these to
identify the arguments by their parameter name.

12. What is Anonymous Functions in Python


Ans: Anonymous functions are also called lambda functions in Python because

instead of declaring them with the standard def keyword, you use the lambda

Keyword.

www.imageconindia.com/academy
13. What is Self Parameter ?
Ans: The self parameter is a reference to the current instance of the class, and is

used to access variables that belongs to the class.

14. How to Identify Arbitrary Arguments in python?


Ans: An arbitrary argument list is a Python feature to call a function with an

arbitrary number of arguments. It's based on the asterisk “unpacking” operator *


.

To catch an arbitrary number of function arguments in a tuple args , use the

asterisk syntax *args within your function definition.

15. Difference Between *args and *kwargs?


Ans:

*args passes variable number of non-keyworded arguments and on which

operation of the tuple can be performed.

**kwargs passes variable number of keyword arguments dictionary to function


on

which operation of a dictionary can be performed.

16. What is return type in python?


Ans: The Python return keyword exits a function and instructs Python to
continue

executing the main program. The return keyword can send a value back to the
main program. A value could be a string, a tuple, or any other object.

www.imageconindia.com/academy
17. Difference Between parameter and arguments?
Ans:

A parameter is the variable listed inside the parentheses in the function


definition.

An argument is the value that are sent to the function when it is called.

18. Difference Between print and return?

Ans: With print() you will display to standard output the value of param1 , while

with return you will send param1 to the caller. The two statements have a very

different meaning, and you should not see the same Behaviour.

19. Types of function in python?


Ans:

✓With no argument and no return value.

✓With no argument and with a Return value.

✓With argument and No Return value.

✓With argument and return value.

20. Explain about no arguments no return value?

Ans: In this type of function in Python, While defining, declaring, or calling them,

We won’t pass any arguments to them. This type of Python function won’t return

any value when we call them

www.imageconindia.com/academy
Modules and Packages

1. What is Module in python ?


Ans: It contain Set of Functions. A Python module is a file containing Python
definitions and statements. A module can define functions, classes, and
variables. A module can also include runnable code.

2. How to use module?


Ans: Modules are simply files with the “. py” extension containing Python code
that can be imported inside another Python Program using import file name.

3. What is package?
Ans: A Python module may contain several classes, functions, variables, etc.
whereas a Python package can contains several module. In simpler terms a
package is folder that contains various modules as files.

4. Difference between module and package?


Ans:

www.imageconindia.com/academy
5. Why we want to create __init__ file for package?
Ans: The __init__.py file makes Python treat directories containing it as modules.
Furthermore, this is the first file to be loaded in a module, so you can use it to
execute code that you want to run each time a module is loaded, or specify the
submodules to be exported.

6. What is Library in python?


Ans: A Python library is a collection of related modules. It contains bundles of
code that can be used repeatedly in different programs.

7. Some of the pre-defined modules Are?


Ans:

1) random

2) decimal

3) string

4)math

5)operator

8. What are Python libraries? Name a few of them.


Ans:Python libraries are a collection of Python packages. Some of the majorly
used python libraries are – Numpy, Pandas, Matplotlib, Scikit-learn and many
more.

www.imageconindia.com/academy
9. What is the difference between a module, a package, and a
library?
Ans:

A module is a Python file that’s intended to be imported into scripts or other


modules. It can contains functions, classes, and global variables.

A package is a collection of modules that are grouped together inside a folder to


provide consistent functionality. Packages can be imported just like modules.
They usually have a __init__.py file in them that tells the Python interpreter to
process them as such.

A library is a collection of packages.

File and Exception Handling

1. How can files be deleted in Python?


Ans: To delete a file in Python, you need to import the OS Module. After that,
you need to use the os.remove() function

2. How to open a new file in Python?


Ans:Opening a file creates a file object. In this example, the variable f refers to
the new file object. >>> f = open("test.dat","w") >>> print f The open function
takes two arguments. The first is the name of the file, and the second is the
mode. Mode "w" means that we are opening the file for writing.

www.imageconindia.com/academy
3. Explain how the write method works on a file.
Ans: >>> f.write("Now is the time")

>>> f.write("to close the file") Closing the file tells the system that we are done
writing and makes the file available for reading:

>>> f.close()

4. What is a text file?


Ans:Give an example for a text file. A text file is a file that contains printable
characters and whitespace, organized into lines separated by newline
characters. To demonstrate, we‘ll create a text file with three lines of text
separated by newlines:

>>> f = open("test.dat","w")

>>> f.write("line one\nline two\nline three\n")

>>> f.close()

5. What is meant by directory? How and where is it useful?


Ans: When we want to open a file somewhere else, you have to specify the path
to the file, which is the name of the directory (or folder) where the file is located:
>>> f = open("/usr/share/dict/words","r") >> > printf.readline() Aarhus This
example opens a file named words that resides in a directory named dict, which
resides in share, which resides in usr, which resides in the top-level directory of
the system, called .

6. What are the different operations we can perform on file?


Ans.

There are three basic operations we can perform on file

Read – r mode

Write – w mode

Append – a mode

www.imageconindia.com/academy
7. What are different modes to open a file?
Ans. Mode for a file:

Mode Description

t Open in Text Mode (default option)

b Open in Binary Mode

r Open in read mode (Default Option)


– Gives error if file does not exist

w Open in Write mode


– Overwrite file if it exist
– Create File if it does not exist

a Open in Append mode


– Append at end if exists
– Create new file if it does not exist

r+ Open for reading and writing


– File MUST exist
– Does not truncate the file

w+ Open for writing + reading


-Creates new file if it does not exist
– Truncates the file if it exists

x Open for exclusive creation

8. What is file handle?


Ans.

When we call the open command, it returns to us a file object or reference to the
file, it is called file handle.

This file handle is used to carry out any subsequent operation on the file like
read or write.

www.imageconindia.com/academy
9. What are the differentiate File Attributes in Python?
Ans.

closed: Returns true if file is closed, false otherwise.

mode: Returns access mode with which file was opened.

name: Returns name of the file.

softspace: Returns false if space explicitly required with print, true otherwise.

10. What is file mode? Name the default file mode.


Ans. A file mode governs the type of operations possible in the opened file. The
default mode is read(‘r’)

11. How is r+ file mode different from rb+ mode?

Ans. r+ is used to read or write a normal Ascii or Unicode file whereas rb+ mode
is used to read or write a binary file

12. Differentiate between read() and readlines().


Ans.

read() readlines()

This function is used to read the file This function is used to read all lines
together in one string from the file and return a list with each
line as separate string.

It returns string It returns list of Strings.

e.g. F1.read() e.g. F1.readLines()

www.imageconindia.com/academy
13 .List some few common Exception types and explain when
they occur.
ArithmeticError- Base class for all errors that occur for numeric calculations.

OverflowError- Raised when a calculation exceeds maximum limit for a


numeric type.

ZeroDivisionError- Raised when division or modulo by zero takes o place.

ImportError- Raised when an import statement fails.

IndexError- Raised when an index is not found in a sequence.

RuntimeError- Raised when a generated error does not fall into any category

14. What do you mean by an exception?


Ans:It is an abnormal condition that is sometimes encountered when a program
is executed. It disrupts the normal flow of the program. It is necessary to handle
this exception; otherwise,it can cause the program to be terminated abruptly.

15. Will it be possible to only include a ‘try’ block without the


‘catch’ and ‘finally’ blocks?
Ans:This would give a compilation error. It is necessary for the ‘try’ block to be
followed with either a ‘catch’ block or a ‘finally’ block, if not both. Either one of
‘catch’ or ‘finally’ blocks is needed so that the flow of exception handling is
undisrupted.

16. Explain an unreachable catch block error.


Ans:In the case of multiple catch blocks, the order in which catch blocks are
placed is from the most specific to the most general ones. That is, the sub
classes of an exception should come first, and then the super classes will follow.
In case that the super classes are kept first, followed by the sub classes after it,
the compiler will show an unreachable catch block error.

www.imageconindia.com/academy
17. Differentiate error and exception in Java.
Ans:The key difference between error and exception is that while the error is
caused by the environment in which the JVM(Java Virtual Machine) is running,
exceptions are caused by the program itself. For example, OutOfMemory is an
error that occurs when the JVM exhausts its memory.

But, NullPointerException is an exception that is encountered when the program


tries to access a null object. Recovering from an error is not possible. Hence, the
only solution to an error is to terminate the execution. However, it is possible to
workaround exceptions using try and catch blocks or by throwing exceptions
back to the caller function.

18. What are the types of exceptions? Explain them.


There are two types of exceptions:

Checked Exceptions

The type of exceptions that are known and recognized by the compiler. These
exceptions can be checked in compile time only. Therefore, they are also called
compile time exceptions. These can be handled by either using try and catch

blocks or by using a throw clause. If these exceptions are not handled


appropriately, they will produce compile time errors. Examples include the
subclasses of java.lang.Exception except for the RunTimeException.

Unchecked Exceptions

The type of exceptions that are not recognized by the compiler. They occur at
run time only. Hence, they are also called run time exceptions. They are not
checked at compile time. Hence, even after a successful compilation, they can
cause the program to terminate prematurely if not handled appropriately.
Examples include the subclasses of java.lang.RunTimeException and
java.lang.Error.

www.imageconindia.com/academy
19. What are runtime exceptions in Java? Give a few examples.
Ans:The exceptions that occur at run time are called run time exceptions. The
compiler cannot recognise these exceptions, like unchecked exceptions. It
includes all sub classes of java.lang.RunTimeException and java.lang.Error.
Examples include, NumberFormatException, NullPointerException,
ClassCastException, ArrayIndexOutOfBoundException, StackOverflowError etc.

20. Does the ‘finally’ block get executed if either of ‘try’ or ‘catch’
blocks return the control?
Ans:The ‘finally’ block is always executed irrespective of whether try or catch
blocks are returning the control or not.

OBJECT ORIENTED PROGRAMS

1. What is the difference between OOP and SP?

Object-Oriented Programming Structural Programming


Object-Oriented Programming is a type
of programming which is based on Provides logical structure to a program
objects rather than just functions and where programs are divided functions
procedures
Bottom-up approach Top-down approach
Provides data hiding Does not provide data hiding
Can solve problems of any complexity Can solve moderate problems
Code can be reused thereby reducing
Does not support code reusability
redundancy

www.imageconindia.com/academy
2. What is Object Oriented Programming?

Object-Oriented Programming(OOPs) is a type of programming that is based on


objects rather than just functions and procedures. Individual objects are grouped
into classes. OOPs implements real-world entities like inheritance, polymorphism,
hiding, etc into programming. It also allows binding data and code together

3. Why use OOPs?

• OOPs allows clarity in programming thereby allowing simplicity in solving


complex problems
• Code can be reused through inheritance thereby reducing redundancy
• Data and code are bound together by encapsulation
• OOPs allows data hiding, therefore, private data is kept confidential
• Problems can be divided into different parts making it simple to solve
• The concept of polymorphism gives flexibility to the program by allowing
the entities to have multiple forms

4. What are the main features of OOPs?

• Inheritance
• Encapsulation
• Polymorphism
• Data Abstraction

5. What is a class?

A class is a prototype that consists of objects in different states and with different
behavior. It has a number of methods that are common the objects present within
that class.

6. Can you call the base class method without creating an


instance?

Yes, you can call the base class without instantiating it if:

• It is a static method
• The base class is inherited by some other subclass

www.imageconindia.com/academy
7. What is inheritance?

Inheritance is a feature of OOPs which allows classes inherit common properties


from other classes. For example, if there is a class such as ‘vehicle’, other classes
like ‘car’, ‘bike’, etc can inherit common properties from the vehicle class. This
property helps you get rid of redundant code thereby reducing the overall size of
the code

8. What is hybrid inheritance?


Hybrid inheritance is a combination of multiple and multi-level inheritance

9. What are the limitations of inheritance?

• Increases the time and effort required to execute a program as it requires


jumping back and forth between different classes
• The parent class and the child class get tightly coupled
• Any modifications to the program would require changes both in the parent
as well as the child class
• Needs careful implementation else would lead to incorrect results

10. What is a superclass?


A superclass or base class is a class that acts as a parent to some other class or
classes. For example, the Vehicle class is a superclass of class Car.

11. What is a subclass?


A class that inherits from another class is called the subclass. For example, the
class Car is a subclass or a derived of Vehicle class.

12. What is polymorphism?

Polymorphism refers to the ability to exist in multiple forms. Multiple definitions


can be given to a single interface. For example, if you have a class named Vehicle,

www.imageconindia.com/academy
it can have a method named speed but you cannot define it because different
vehicles have different speed. This method will be defined in the subclasses with
different definitions for different vehicles.

13. What is method overloading?


Method overloading is a feature of OOPs which makes it possible to give the same
name to more than one methods within a class if the arguments passed differ.

14. What is method overriding?


Method overriding is a feature of OOPs by which the child class or the subclass
can redefine methods present in the base class or parent class. Here, the method
that is overridden has the same name as well as the signature meaning the
arguments passed and the return type.

15. What is operator overloading?


Operator overloading refers to implementing operators using user-defined types
based on the arguments passed along with it.

16. What is encapsulation?


Encapsulation refers to binding the data and the code that works on that together
in a single unit. For example, a class. Encapsulation also allows data-hiding as the
data specified in one class is hidden from other classes.

17. What is data abstraction?


Data abstraction is a very important feature of OOPs that allows displaying only
the important information and hiding the implementation details

www.imageconindia.com/academy
18. Can you create an instance of an abstract class?
No. Instances of an abstract class cannot be created because it does not have a
complete implementation. However, instances of subclass inheriting the abstract
class can be created.

19. What is a constructor?


A constructor is a special type of method that has the same name as the class and
is used to initialize objects of that class.

20. What is a destructor?


A destructor is a method that is automatically invoked when an object is
destroyed. The destructor also recovers the heap space that was allocated to the
destroyed object, closes the files and database connections of the object, etc

21. What is an exception?

An exception is a kind of notification that interrupts the normal execution of a


program. Exceptions provide a pattern to the error and transfer the error to the
exception handler to resolve it. The state of the program is saved as soon as an
exception is raised.

22. What is exception handling?

Exception handling in Object-Oriented Programming is a very important concept


that is used to manage errors. An exception handler allows errors to be thrown
and caught and implements a centralized mechanism to resolve them.

23. What is a try/ catch block?

A try/ catch block is used to handle exceptions. The try block defines a set of
statements that may lead to an error. The catch block basically catches the
exception.

www.imageconindia.com/academy
24. What is a finally block?

A finally block consists of code that is used to execute important code such as
closing a connection, etc. This block executes when the try block exits. It also
makes sure that finally block executes even in case some unexpected exception
is encountered.

25. What are the limitations of OOPs?

• Usually not suitable for small problems


• Requires intensive testing
• Takes more time to solve the problem
• Requires proper planning
• The programmer should think of solving a problem in terms of objects

26. Decorators in Python

In programming, decorator is a design pattern that adds additional


responsibilities to an object dynamically. In Python, a function is the first-order
object. So, a decorator in Python adds additional responsibilities/functionalities
to a function dynamically without modifying a function.

DATABASE MANAGEMENT SYSTEM

1. Explain what is MongoDB?

Mongo-DB is a document database which provides high performance, high


availability and easy scalability.

2. What is “Namespace” in MongoDB?

MongoDB stores BSON (Binary Interchange and Structure Object Notation)


objects in the collection. The concatenation of the collection name and database
name is called a namespace.

www.imageconindia.com/academy
3. What is sharding in MongoDB?

The procedure of storing data records across multiple machines is referred as


Sharding. It is a MongoDB approach to meet the demands of data growth. It is the
horizontal partition of data in a database or search engine. Each partition is
referred as shard or database shard.

4. How can you see the connection used by Mongos?


To see the connection used by Mongos use db_adminCommand
(“connPoolStats”);

5. What is the syntax to create a collection and to drop a


collection in MongoDB?

Syntax to create collection in MongoDB is db.createCollection(name,options)

Syntax to drop collection in MongoDB is db.collection.drop()

6. To do safe backups what is the feature in MongoDB that you


can use?
Journaling is the feature in MongoDB that you can use to do safe backups.

7. Mention what is the command syntax for inserting a


document?

For inserting a document command syntax is database.collection.insert


(document).

8. Mention how you can inspect the source code of a function?

To inspect a source code of a function, without any parentheses, the function


must be invoked.

www.imageconindia.com/academy
9. What is the command syntax that tells you whether you are on
the master server or not? And how many master does MongoDB
allow?

Command syntax Db.isMaster() will tell you whether you are on the master server
or not. MongoDB allows only one master server, while couchDB allows multiple
masters.

10. Mention the command syntax that is used to view Mongo is


using the link?
The command syntax that is used to view mongo is using the link is
db._adminCommand(“connPoolStats.”)

11. What are alternatives to MongoDB?

Cassandra, CouchDB, Redis, Riak, Hbase are a few good alternatives.

12. What is MySQL?

MySQL is a database management system for web servers. It can grow with the
website as it is highly scalable. Most of the websites today are powered by MySQL.

13. What are some of the advantages of using MySQL?

• Flexibility: MySQL runs on all operating systems


• Power: MySQL focuses on performance
• Enterprise-Level SQL Features: MySQL had for some time been lacking in
advanced features such as subqueries, views, and stored procedures.
• Full-Text Indexing and Searching
• Query Caching: This helps enhance the speed of MySQL greatly
• Replication: One MySQL server can be duplicated on another, providing
numerous advantages
• Configuration and Security

www.imageconindia.com/academy
14. What do you mean by ‘databases’?

A database is a structured collection of data stored in a computer system and


organized in a way to be quickly searched. With databases, information can be
rapidly retrieved.

15. What does SQL in MySQL stand for?

The SQL in MySQL stands for Structured Query Language. This language is also
used in other databases such as Oracle and Microsoft SQL Server. One can use
commands such as the following to send requests from a database:

SELECT title FROM publications WHERE author = ' J. K. Rowling’;

Note that SQL is not case sensitive. However, it is a good practice to write the SQL
keywords in CAPS and other names and variables in a small case.

16. What does a MySQL database contain?

A MySQL database contains one or more tables, each of which contains records
or rows. Within these rows are various columns or fields that contain the data
itself.

17. How do you create a database in MySQL?

Use the following command to create a new database called ‘books’:

CREATE DATABASE books;

18. How do you create a table using MySQL?

Use the following to create a table using MySQL:

CREATE TABLE history (


author VARCHAR(128),
title VARCHAR(128),
type VARCHAR(16),
year CHAR(4)) ENGINE InnoDB;

www.imageconindia.com/academy
19. How do you Insert Data Into MySQL?

The INSERT INTO statement is used to add new records to a MySQL table:

INSERT INTO table_name (column1, column2, column3,...)


VALUES (value1, value2, value3,...)

If we want to add values for all the columns of the table, we do not need to
specify the column names in the SQL query. However, the order of the values
should be in the same order as the columns in the table. The INSERT INTO syntax
would be as follows:

INSERT INTO table_name


VALUES (value1, value2, value3, ...);

20. How do you remove a column from a database?

You can remove a column by using the DROP keyword:

ALTER TABLE classics DROP pages;

21. How to create an Index in MySQL?

In MySQL, there are different index types, such as a regular INDEX, a PRIMARY
KEY, or a FULLTEXT index. You can achieve fast searches with the help of an
index. Indexes speed up performance by either ordering the data on disk so it's
quicker to find your result or, telling the SQL engine where to go to find your
data.

Example: Adding indexes to the history table:

ALTER TABLE history ADD INDEX(author(10));


ALTER TABLE history ADD INDEX(title(10));
ALTER TABLE history ADD INDEX(category(5));
ALTER TABLE history ADD INDEX(year);
DESCRIBE history;

www.imageconindia.com/academy
22. How to Delete Data From a MySQL Table?

In MySQL, the DELETE statement is used to delete records from a table:

DELETE FROM table_name


WHERE column_name = value_name

23. How do you view a database in MySQL?

One can view all the databases on the MySQL server host using the following
command:

mysql> SHOW DATABASES;

24. What are the Numeric Data Types in MySQL?

MySQL has numeric data types for integer, fixed-point, floating-point, and bit
values, as shown in the table below. Numeric types can be signed or unsigned,
except BIT. A special attribute enables the automatic generation of sequential
integer or floating-point column values, which is useful for applications that
require a series of unique identification numbers.

Type Name Meaning

TINYINT Very Small Integer

SMALLINT Small Integer

MEDIUMINT Medium-sized Integer

INT Standard Integer

BIGINT Large Integer

DECIMAL Fixed-point number

FLOAT Single-precision floating-point number

DOUBLE Double-precision floating-point number

BIT Bit-field

www.imageconindia.com/academy
25. What are the String Data Types in MySQL?

Type Name Meaning

CHAR fixed-length nonbinary(character) string

VARCHAR variable-length nonbinary string

BINARY fixed-length binary string

VARBINARY variable-length binary string

TINYBLOB Very small BLOB(binary large object)

BLOB Small BLOB

MEDIUMBLOB Medium-sized BLOB

LONGBLOB Large BLOB

TINYTEXT A very small nonbinary string

TEXT Small nonbinary string

MEDIUMTEXT Medium-sized nonbinary string

LONGTEXT Large nonbinary string

An enumeration; each column value is assigned, one enumeration


ENUM
member

SET A set; each column value is assigned zero or more set members

NULL in SQL is the term used to represent a missing value. A NULL


NULL value in a table is a value in a field that appears to be blank. This
value is different than a zero value or a field that contains spaces.

www.imageconindia.com/academy
26. How to add users in MySQL?

You can add a User by using the CREATE command and specifying the necessary
credentials. For example:

CREATE USER ‘testuser’ IDENTIFIED BY ‘sample password’;


Intermediate MySQL Interview Questions

27. What are MySQL “Views”?

In MySQL, a view consists of a set of rows that is returned if a particular query is


executed. This is also known as a ‘virtual table’. Views make it easy to retrieve
the way of making the query available via an alias.
The advantages of views are:

• Simplicity
• Security
• Maintainability

28. How do you create and execute views in MySQL?

Creating a view is accomplished with the CREATE VIEW statement. As an


example:

CREATE
[OR REPLACE]
[ALGORITHM = {MERGE | TEMPTABLE | UNDEFINED }]
[DEFINER = { user | CURRENT_USER }]
[SQL SECURITY { DEFINER | INVOKER }]
VIEW view_name [(column_list)]
AS select_statement
[WITH [CASCADED | LOCAL] CHECK OPTION]

29. What is the MySQL server?

The server, mysqld, is the hub of a MySQL installation; it performs all


manipulation of databases and tables.

www.imageconindia.com/academy
30. How can you interact with MySQL?

There are three main ways you can interact with MySQL:

• using a command line


• via a web interface
• through a programming language

31. What are MySQL Database Queries?

A query is a specific request or a question. One can query a database for specific
information and have a record returned.

NETWORKING

1.What is a Network?

Network is defined as a set of devices connected to each other using a physical


transmission medium.
For Example, A computer network is a group of computers connected with each
other to communicate and share information and resources like hardware, data,
and software. In a network, nodes are used to connect two or more networks

2. What is a Node?

Answer: Two or more computers are connected directly by an optical fiber or


any other cable. A node is a point where a connection is established. It is a
network component that is used to send, receive and forward the electronic
information.
A device connected to a network is also termed as Node. Let’s consider that in a
network there are 2 computers, 2 printers, and a server are connected, then we
can say that there are five nodes on the network.

www.imageconindia.com/academy
3. Explain Transmission Control Protocol, TCP.

• TCP is a connection-oriented protocol. It simply means when data is


transferring from source to destination, the protocol takes care of data
integrity by sending the data packet again if it is lost during transmission.
• TCP ensures reliability and an error-free data stream.
• TCP packets contain fields such as Sequence Number, AcK number, Data
offset, Reserved, Control bit, Window, Urgent Pointer, Options, Padding,
checksum, Source Port, and Destination port.

4. Explain User Datagram Protocol, UDP.

• UDP is a connection-less protocol. In simple terms, if one data packet is


lost during transmission, it will not send that packet again.
• This protocol is suitable where minor data loss is not a major issue.

5. How does TCP work?

TCP uses a three-way handshake to establish a connection between client


and server. It uses SYN, ACK and FIN flags (1 bit) for connecting two
endpoints. After the establishment of the connection, data is transferred
sequentially. If there is any loss of packet, it retransmits data.

6. List out common TCP/IP protocols.

• HTTP - Used between a web client and a web server, for non-secure data
transmissions.
• HTTPS - Used between a web client and a web server, for secure data
transmissions.
• FTP - Used between two or more computers to transfer files.

www.imageconindia.com/academy
7. Comparison between TCP/IP & OSI model.

TCP/IP is the alternate model that also explains the information flow in the
network.It is a simpler representation in comparison to the OSI model but
contains fewer details of protocols than the OSI model

8. Is UDP better than TCP?


Both protocols are used for different purposes. If the user wants error-free and
guarantees to deliver data, TCP is the choice. If the user wants fast transmission
of data and little loss of data is not a problem, UDP is the choice.

9. What is the port number of Telnet and DNS?

• Telnet is a protocol used to access remote servers but insecurely. Port no


of Telnet is 23.
• DNS is a protocol used to translate a domain name to IP address. Port no
of DNS is 53.

www.imageconindia.com/academy
10. What is the UDP packet format?

The UDP packet format contains four fields:


• Source Port and Destination Port fields (16 bits each): Endpoints of the
connection.
• Length field (16 bits): Length of the header and data.
• Checksum field (16 bits): It allows packet integrity checking (optional).

11. What is the TCP packet format?

The TCP packet format consists of these fields:


Source Port and Destination Port fields (16 bits each); Sequence Number
field(32 bits); Acknowledgement Number field (32 bits); Data Offset (a.k.a.
Header Length) field (variable length); Reserved field (6 bits); Flags field (6 bits)
contains the various flags: URG, ACK, PSH, RST, SYN, FIN; Window field (16 bits);
Checksum field (16 bits) ; Urgent pointer field (16 bits) ; Options field (variable
length) & Data field (variable length).

www.imageconindia.com/academy
12. List out common TCP/IP ports and protocols.

I am listing out common TCP/IP ports and protocols:


Port
Protocol RFC TCP/UDP
Number
File Transfer Protocol (FTP) 20/21 959 TCP
4250-
Secure Shell (SSH) 22 TCP
4256
Telnet 23 854 TCP
Simple Mail Transfer Protocol
25 5321 TCP
(SMTP)
1034-
Domain Name System (DNS) 53 TCP/UDP
1035
Dynamic Host Configuration
67/68 2131 UDP
Protocol (DHCP)
Trivial File Transfer Protocol
69 1350 UDP
(TFTP)

13. What are the different types of a network? Explain each


briefly.
Answer: There are 4 major types of networks.

• Personal Area Network (PAN): It is the smallest and basic network type
that is often used at home. It is a connection between the computer and
another device such as phone, printer, modem tablets, etc
• Local Area Network (LAN): LAN is used in small offices and Internet
cafes to connect a small group of computers to each other. Usually, they
are used to transfer a file or for playing the game in a network.
• Metropolitan Area Network (MAN): It is a powerful network type than
LAN. The area covered by MAN is a small town, city, etc. A huge server is
used to cover such a large span of area for connection.
• Wide Area Network (WAN): It is more complex than LAN and covers a
large span of the area typically a large physical distance. The Internet is
the largest WAN which is spread across the world. WAN is not owned by
any single organization but it has distributed ownership.

www.imageconindia.com/academy
14. Differentiate Communication and Transmission?

Answer: Through Transmission the data gets transferred from source to


destination (only one way). It is treated as the physical movement of data.
Communication means the process of sending and receiving data between two
media (data is transferred between source and destination in both ways).

15. Explain the characteristics of networking?

Topology: This deals with how the computers or nodes are arranged in the
network. The computers are arranged physically or logically.
Protocols: Deals with the process of how computers communicate with one
another.
Medium: This is nothing but the medium used by computers for communication.

16. What is the full form of ASCII?

ASCII stands for American Standard Code for Information Interchange.

17. How VPN is used in the corporate world?

Answer: VPN stands for Virtual Private Network. With the help of a VPN, remote
users can securely connect to the organization’s network. Corporate companies,
educational institutions, government offices, etc use this VPN.

18. What is the use of encryption and decryption?

Encryption is the process of converting the transmission data into another form
that is not read by any other device other than the intended receiver.

Decryption is the process of converting back the encrypted data to its normal
form. An algorithm called cipher is used in this conversion process.

www.imageconindia.com/academy
19. Brief Ethernet?

Ethernet is a technology that is used to connect computers all over the network
to transmit the data between each other.

For Example, if we connect a computer and laptop to a printer, then we can call
it as an Ethernet network. Ethernet acts as the carrier for the Internet within short
distance networks like a network in a building.
The main difference between the Internet and Ethernet is security. Ethernet is
safer than the Internet as Ethernet is a closed-loop and has only limited access.

20. What is an Encoder?

Answer: Encoder is a circuit that uses an algorithm to convert any data or


compress audio data or video data for transmission purposes. An encoder
converts the analog signal into the digital signal.

21. What is a Decoder?

Answer: Decoder is a circuit that converts the encoded data to its actual format.
It converts the digital signal into an analog signal.

22. Explain the difference between baseband and broadband


transmission?

• Baseband Transmission: A single signal consumes the whole bandwidth


of the cable.
• Broadband Transmission: Multiple signals of multiple frequencies are
sent simultaneously

www.imageconindia.com/academy
GRAPHICAL USER INTERFACE

1. What Is A Graphical User Interface (GUI)?

Graphical User Interface (GUI) is nothing but a desktop application which


helps you to interact with the computers. They perform different tasks in the
desktops, laptops and other electronic devices.

• GUI apps like Text-Editors create, read, update and delete different types
of files.

• Apps like Sudoku, Chess and Solitaire are games which you can play.

• GUI apps like Google Chrome, Firefox and Microsoft Edge browse
through the Internet

2.Python Libraries To Create Graphical User Interfaces

• Kivy
• Python QT
• wxPython
• Tkinter

3. What Is Tkinter?

Tkinter is actually an inbuilt Python module used to create simple GUI apps. It
is the most commonly used module for GUI apps in the Python.

www.imageconindia.com/academy
4. what are widgets?

Widgets are something like elements in the HTML. You will find different types
of widgets to the different types of elements in the Tkinter.

• Canvas – Canvas is used to draw shapes in your GUI.


• Button – Button widget is used to place the buttons in the Tkinter.
• Checkbutton – Checkbutton is used to create the check buttons in
your application. Note that you can select more than one option at a
time.
• Entry – Entry widget is used to create input fields in the GUI.
• Frame – Frame is used as containers in the Tkinter.
• Label – Label is used to create a single line widgets like text, images
etc.
• Menu – Menu is used to create menus in the GUI.

5.Geometry Management
All widgets in the Tkinter will have some geometry measurements. These
measurements give you to organize the widgets and their parent frames,
windows and so on.

Tkinter has the following three Geometry Manager classes.

• pack():- It organizes the widgets in the block, which mean it occupies the
entire available width. It’s a standard method to show the widgets in the
window.
• grid():- It organizes the widgets in table-like structure.
• place():- It places the widgets at a specific position you want.

www.imageconindia.com/academy
www.imageconindia.com/academy
www.imageconindia.com/academy
www.imageconindia.com/academy

You might also like