PYTHON QUESTION BANK (1)
PYTHON QUESTION BANK (1)
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
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
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.
1. You can start an interactive interpreter from the command line and
start writing the instructions after the »> prompt.
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.
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.
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.
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']
>>>
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. 2
Ans. a. Selection
b. Iteration
Ans. if else
Ans. Selection
www.imageconindia.com/academy
8. ______ statements can be written in if block.
Ans. Nested if
if True:
print("Hello")
else:
print("Bye")
Ans. Hello
y=2
if 2!=y:
print("H")
else :
print("K")
Ans. K
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
Ans. false
www.imageconindia.com/academy
19. Write the output of the following :
x = 10
if x > 7 and x <= 10:
print("Pass", end="")
print("Fail")
if 'i' == "i" :
print(True)
else:
print("False")
Ans. True
www.imageconindia.com/academy
DATA STRUCTURES
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
• 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:
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.
• Multiple inheritances are when a child class is inherited from more than
one superclass.
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.
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.
• Built-in
• User-defined
▪ 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
▪ In a stack, the item that is most recently added is removed first whereas in
queue, the item least recently added is removed first.
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]))
min = list[ 0 ]
for a in list:
if a < min:
min = a
return min
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
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
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.
1. default arguments
2. keyword arguments
3. positional arguments
values if no explicit values are passed to these arguments from the function call.
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.
execution of the program as it gets executed only when the program is run
directly
function if imported as a module, but the Main Function gets executed only
when it is run as a Python program.
you can use the keyword arguments in your function call. You use these to
identify the arguments by their parameter name.
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
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:
An argument is the value that are sent to the function when it is called.
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.
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
www.imageconindia.com/academy
Modules and Packages
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.
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.
1) random
2) decimal
3) string
4)math
5)operator
www.imageconindia.com/academy
9. What is the difference between a module, a package, and a
library?
Ans:
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()
>>> f = open("test.dat","w")
>>> f.close()
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
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.
softspace: Returns false if space explicitly required with print, true otherwise.
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
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.
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.
RuntimeError- Raised when a generated error does not fall into any category
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.
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
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.
www.imageconindia.com/academy
2. What is Object Oriented Programming?
• 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.
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?
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.
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.
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.
www.imageconindia.com/academy
3. What is sharding in MongoDB?
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.
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.
www.imageconindia.com/academy
14. What do you mean by ‘databases’?
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:
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.
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.
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:
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:
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.
www.imageconindia.com/academy
22. How to Delete Data From a MySQL Table?
One can view all the databases on the MySQL server host using the following
command:
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.
BIT Bit-field
www.imageconindia.com/academy
25. What are the String Data Types in MySQL?
SET A set; each column value is assigned zero or more set members
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:
• Simplicity
• Security
• Maintainability
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]
www.imageconindia.com/academy
30. How can you interact with MySQL?
There are three main ways you can interact with MySQL:
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?
2. What is a Node?
www.imageconindia.com/academy
3. Explain Transmission Control Protocol, TCP.
• 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
www.imageconindia.com/academy
10. What is the UDP packet format?
www.imageconindia.com/academy
12. List out common TCP/IP ports and protocols.
• 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?
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.
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.
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.
Answer: Decoder is a circuit that converts the encoded data to its actual format.
It converts the digital signal into an analog signal.
www.imageconindia.com/academy
GRAPHICAL USER INTERFACE
• 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
• 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.
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.
• 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