Python Interview questions
for freshers & Experienced
Python telephonic /theory-oriented interview questions
Python telephonic interview questions
********** @@@ Interview Questions on Python Basics
@@@*************
__author__ = "Narendra
Boyina"
Note: For an interviewer no need
to answer exactly as I have written below.
I have written complete information regarding the
question
Understand the below questions &
answers, then perform on your own in front of the interviewer
@ All the
best for your bright future @
********** Interview Questions on
Python Basics **********
è What is Python?
Ø Python
is a very powerful general-purpose interpreted, interactive, object-oriented, open
source, high-level scripting and programming language.
It was invented by Guido
van Rossum and released in 1991.
è What are the advantages/features
of Python?
Advantages:
Ø Readability & Ease to use: Python's
syntax is designed to be readable, allowing programmers to write expressive
code.
Ø Platform independent: Python runs virtually on every major platform used today (Linux/ Windows/ MAC).
As long as you have a compatible Python interpreter installed,
Ø Free and open-source
Ø Large Standard Library: python comes with a large
standard library that supports many common programming tasks such as connecting
to web servers, searching text, reading, and modifying files.
Ø Large community: Python has a large
community of developers that provide third-party libraries and support
Ø Unit testing framework: Python has its own
unit testing framework.
è What
are the disadvantages/ drawbacks of Python?
Ø Runtime error: Python is a dynamic typing language , the data type of a variable can change at any
time. Runtime errors can result from a variable containing an integer
number holding a string in the future. As a result, applications must be
thoroughly tested by Python programmers
Ø Indentation issues: Moving a Python script
from one environment to another can cause indentation issues due to differences
in how editors interpret spaces and tabs.
Ø Memory Consumption: Python's data
structures demand more memory space.
Ø Slow Execution Speed: Python is an
interpreted language that works with an interpreter, not a compiler (slow as
compared to C, C++).
è What can you do with
Python?
Ø To
create web applications, desktop applications, and hardware applications, also
we can develop & test framework works.
Ø Many
data scientists use Python due to its excellent libraries including Numpy and
Pandas.
è Why Python is an
Interpreted Language?
Ø
Python
is designed as an interpretive language.
Ø
Interpreted
programming languages, that are not machine-level code before execution.
è What is a variable? Explain
with real-time examples.
Ø The variable is a reserved memory
location to store values (Simply variable is a name-value pair)
Ø
Python
is dynamically typed. User no need to declare variables!
Ø
The
declaration happens automatically, when user assign a value to a variable
Ø
Variables
can change data-type, simply by assigning them a new value of different type
Ø
Python
allows users to assign a single value to several variables simultaneously
Ø
User
can also assign multiple objects to multiple variables.
Ex: The variable is a container to store
values.
If we want to store water, we need a glass
so if we want to store the value we need a variable.
è
Mention what are the rules for local
and global variables in Python.
Ø
Local variables: If a variable is assigned a new value anywhere within the
function's body,
Ø Global
variables: Defined outside the functions
but only referenced inside the function
è Can
we declare a variable in Python?
Ø In Python, the Programmer does not
need to declare variables!
Ø Reason: Python is dynamically typed.
Ø The declaration happens automatically
when the user assigns a value to a variable (initialization)
è Is Python
case-sensitive or not?
Python is a case-sensitive programming language.
Ex: Manpower and manpower are two different
identifiers in Python.
è Where do we store the
memory in Python?
Ø In
Python memory is managed by Python's private heap space i.e All python objects and data structures will
be stored in a private heap space.
Ø Python
interpreter takes care of private heap space. If you want to view the memory
address, you can use id() built-in function
Ø
Python
has an inbuilt garbage collector.
Ø
garbage
collector recycles all unused memory (frees the memory, and makes it
available to the heap space)
è
What are the inbuilt
functions of python
Ø Built-in
functions are the pre-defined functions in Python
int(), float(), str(),
list(), tuple(), dict(), set(), char(), ord(), enumerate(), min(), max(),
all(), any(), input(), print(), pow(), len(), range(), map(), filter(), open(),
help(), id(), type(), zip(), dir(), next(), sorted(), sum(), hasattr(), getattr(),
setattr(), delattr(), isinstance(), issubclass(), super()
è Explain how you can make
a Python Script executable on Unix?
Ø To make a Python
Script executable on Unix, you need to do 2 things:
Ø Script file's
mode must be executable and
Ø Inside python
file the first line must begin with # ( #!/usr/local/bin/python)
è How to check data type in
Python?
Ø You can check the data type of any variable by using type() function
è What is range()?
Ø Range
is a type of sequence used to represent arithmetic progression integers.
Ø Range
is a constructor that returns a list.
Syntax:
range (start, end, step)
è What is the escape
sequence character?
Ø Escape
sequences allow you to include special characters in strings.
Ø Whenever
an escape sequence occurs within the double quotes, it will be replaced with
its property (Ex: \n replaced with a new line, \t à
replaced with 4 spaces)
è What is an identifier? Explain
the rules of identifiers.
Ø Identifier
is a name used to identify a variable/ function/ class/ module/ other object.
· Rules for identifiers:
·
For identifier purpose,
we will use a combination of alphabets (A to Z or a to z), digits (0to 9),
an underscore (_)
·
Doesn’t allow punctuation
characters such as @, $, and % - + … within identifiers except
underscore
·
Identifier names should
not start with numbers.
·
Keywords/ reserved words
should not be used as an Identifier.
·
Identifier length can be
any number of characters
è What is a keyword?
Ø Keywords
are the reserved words.
Ø All
the Python keywords contain lowercase letters only except Boolean.
Ø We
can see all the keywords available in the latest Python version by Import
keyword
print(Keyword.kwlist)
********** Interview Questions on
Operators **********
è What is an operator? How
many types of operators are present in Python
Ø operator is a symbol that is used to manipulate data and perform various computations.
Ø Operators
are classified into 3 types
1. Unary operator: Python doesn’t
support unary operators. EX: a++, ++a
2. Binary operator: Which operator is used in two operands is
called a Binary operator.
Types of binary
operators:
·
Arithmetic operators (+ -
* / // % **)
·
Comparison operators (>
, <, ==, !=, >=, <=)
·
Logical operators (and, or,
not)
·
Assignment operators
·
Identity operators
·
Membership operators
· Bitwise operators
3. Ternary operator:
Which operator is used 3 operands is called a Ternary operator.
·
This consists of the true
or false values with a statement that has to be evaluated for it.
Syntax: [on-true] if
[expression] else [on -false]
·
Result = x if x > y
else y # x, y are operands
Ex: The expression gets
evaluated like if x>y else y, in this case if x>y is true
then the value is returned as big=x and if it is incorrect then big=y will be
sent as a result.
"""
x, y = 1135, 150
big = x if x > y else y
print(big)
è Mention the use of the // operator in Python?
It is a Floor Division-operator,
which is used for dividing two operands with the result as a quotient showing only digits before the decimal point.
For instance, 10//5 = 2 and 10.0//5.0 = 2.0
********** Interview Questions on
Data Structures **********
è What are the data structures /data types available in Python?
Ø Numbers can be integers (1 and 2), floats (1.1 and 1.2) or fractions (1/2 and
2/3), even complex numbers(c = 3+i7).
Ø String:
·
A string is a collection of one or more
Unicode characters put in a single quote, or double quote.
·
We can access the substring by using
Index, The Index always starts with 0 and ends with -1
Ø List:
·
Lists are super dynamic, and
heterogeneous mutable sequences of elements delimited by square brackets [ ].
·
We can access list elements by using
Index, Index always starts with 0 and ends with -1
Ø Tuple:
·
Tuple is a heterogeneous immutable
sequence of elements delimited by parenthesis (). In a tuple, we can’t store a
single value.
·
It is used to return multiple values
from a function.
Ø Set:
·
Sets are heterogeneous unordered collection
of unique elements, delimited by curly braces {}
·
Empty set use the set() constructor
Ø Dictionary:
·
Dictionary is an unordered, mapping
from unique immutable key to mutable/Immutable values
·
Dictionary holds a key: value pair.
·
No duplicate key is allowed in
dictionaries
è What are
the built-in Data types available in Python, classify them as either
Homogeneous or Heterogeneous & classify
them as mutable or immutable.
Immutable built-in types
Numbers ------> Ex:
123
------->
Homogeneous
Strings
------> Ex: "Narendra "
------>
Homogeneous
Tuples
------> Ex: (1, "Narendra",
1.5) ------> Heterogeneous
Mutable built-in types
List
------> Ex: [1, "Narendra",
1.5] ------> Heterogeneous
Set
------> Ex: {1, "Narendra", 1.5}
------> Heterogeneous
Dictionary -----> Ex: {'Name':'Narendra', 'Age':26, 'Percentage':76.2, 1990:'birthday'}
where the key is immutable &
unique.
The value may be mutable/
immutable (Heterogeneous)
è
What is the difference between List
and Tuple?
Ø
List and Tuple are both
heterogeneous, allowing us to store more than one value in a single variable.
Ø
List is a mutable
sequence; we can modify list elements.
Ø
Tuple is an
immutable sequence; we can’t perform modifications on
tuple.
è
What modifications can be made to the
list?
Ø The list is a super dynamic and mutable sequence.
Ø We can append(), extend(), insert(), remove(), pop(), clear(), sort(), reverse(), etc.
è
What is the difference between append
and extend?
Ø Append function will add a single element at
the end of the List.
Ø Extend function will add multiple elements
at the end of the List.
è What is the difference between a Dictionary and a Set?
Dictionary is a key value pair
Dictionary is an unordered mapping
from a unique immutable key to mutable/immutable values.
Ø Delimited by {curly braces}
filled with comma-separated items
Ø No duplicate key is allowed
in a dictionary.
Ø When duplicate keys occur
during an assignment the last assignment wins.
Set is an Unordered collection of unique elements.
Ø Delimited by {curly braces} filled with
comma-separated elements.
Ø For an empty set, we use the set() constructor
********* Interview Questions on
Conditional Statements *********
è What are Conditional statements? what are types of conditional
statements?
Ø The statement/s may or may
not be executed depending on the condition of the expression.
Types
of conditional statements:
· Simple if
· Nested if
· if else
· nested if else
· if elif else
if :
if the given condition is true, then a block of statements will be executed.
else:
else block is always followed by an if
block. If the if block statements are not executed due to their false condition,
then the else block statements will execute.
elif: elif is used to check for multiple
conditions.
For
example, if the first condition is false, it moves on to the next “elif”
statement to check if that condition is true
è What is the difference between if-else and if-elif-else?
if-else
:
Used when you only have two outcomes—either the condition is true or
false.
if x > 0:
print("Positive")
else:
print("Non-positive")
if-elif-else
:
Used when you have more than two conditions to check. You can specify
multiple conditions using elif
.
if x > 0:
print("Positive")
elif x == 0:
print("Zero")
else:
print("Negative")
è What are nested if statements?
Ø Nested if statements
are if statements placed inside another if or else block.
Ø nested if statements allow checking
multiple levels of conditions.
x = 10
if x > 5:
if x <
15:
print("x is between 5 and 15")
è What is the ternary operator in Python?
Python supports a ternary conditional operator for quick and
concise decision-making in one line.
Syntax: [on_true] if [condition]
else [on_false]
Example x = 5
result = "Even" if x % 2 == 0 else "Odd"
print(result)
********* Interview Questions on control statements *********
è What is the Purpose of control statements/loops?
A set of statements executed more than once is known as a looping/control flow statements.
Control statements(loops) are used to manage the flow of execution of a program based on certain conditions.
Loops are used to execute a block of code repeatedly.
è Define Control flow statements or iterative statements
control
statements are classified into 3 types (for loop, while
loop, Nested loops)
·
For loop:
- A for loop can be used to execute a
group of statements repeatedly depending upon the number of elements/items in
the iterable (list, tuple, dict, set)
- The loop control variable is typically updated automatically (Ex: via sequences/iterables).
- The loop ends when all items in the sequence are exhausted.
·
While loop:
- A set of statements is repeatedly executed
until the given condition fails.
- The loop control variable
must be manually updated within the loop to ensure progress toward terminating
the loop.
- If not handled properly,
it can lead to infinite loops
·
Nested loops (nested for / nested while): A loop that contains another loop is known
as a nested loop.
èDefine Break and
continue statements?
Ø Break keyword will cause your loop (for or while) to stop executing
and exit without reaching the end of the sequence or end of the function.
Ø Continue: we can use the continue keyword to skip the current iteration and continue
the next iteration
Assert keyword:
Ø The
assert keyword lets you test if a condition in your code returns true, if
not, the program will raise. An
assertion error.
It is used as a debugging code
********** Interview
Questions on Functions **********
è
What is Function?
A function is a
block of organized code, used to perform single or multiple actions.
Note:
The purpose of the function is code re-usability.
Once the basic structure of a function is finalized, you can execute it by calling it from another function.
Ø
Types of Functions
Functions are classified into two types
1. Recursive
function
2. Non-recursive
functions
We have 6 types
of non-recursive functions:
·
function without arguments
·
function with arguments/ positional/
Required arguments
·
function with Default arguments
·
function with Variable-length
arguments (*args)
·
function with Keyword arguments
(**args) / (**kw args)
·
function with command line arguments
è What is a docstring, and why is it used in Python functions?
A
docstring is a string literal used to provide documentation for functions,
classes, or modules.
It
helps users understand the purpose and usage of the function/ class/module
·
Declaring Docstrings: The docstrings are declared using ”’triple single quotes”’ or
“””triple double quotes””” just below the function, class, method declaration.
All functions should have a docstring.
·
Accessing Docstrings: The docstrings can be accessed using the __doc__ method of the
object or using the help function.
è What is the purpose of the None keyword in Python functions?
None is used to represent the absence of a value in functions.
Functions without a return statement implicitly return None.
è
Define variable-length arguments/
*args in Python.
Ø
Variable-length arguments are defined
using *args.
Ø
Variable-length arguments can take
zero or an unspecified amount of input values and store those values in a
tuple
è
Define Keyword arguments/
**args/kw_args in Python.
Ø
Keyword arguments are defined using
**args.
Ø
Keyword arguments can take zero or an
unspecified amount of input items and store those in a dictionary.
è Write a Python function using all types of arguments
""" Let's create a real-world example using a function to manage a restaurant order
This function will include a required argument for the dish name,
default argument, additional positional arguments for the side dishes,
and keyword arguments for optional parameters like special requests or dietary preferences """
def place_order(Main_dish_name, water="general", *side_dishes, **special_requests):
# Print the required dish name
print(f"Main Dish: {Main_dish_name}")
print(water)
# Print any additional side dishes
if side_dishes:
print("Side Dishes:")
for side in side_dishes:
print(f" - {side}")
# Print any special requests
if special_requests:
print("Special Requests:")
for key, value in special_requests.items():
print(f" - {key}: {value}")
else:
print("No special requests.")
# calling function
place_order("Chiken fry piece biryani",
"Mineral water", # default argument
"panner Naan", # Side Dish 1
"panner butter masala", # Side Dish 2
"crispy prawns fry", # Side Dish 3
omlet="half boil", # Special request
extra_lemon="Please add extra lemon slices" # Special request
)
è What is the purpose of the return statement in a function?
Ø The return statement in a function is
used to exit the function and return a value to the caller.
Ø It marks the end of the function's execution, and
the specified value is sent back to the point in the program where the function
was called.
Note: always calling function will be replaced with its
return value/s
è Explain the concept of scope in Python functions.
The concept of scope in Python refers to the region
or context in which a variable is defined and can be accessed. There are two
main types of scope:
1. Local Scope:
Ø Variables defined within a function have a local
scope.
Ø They are only accessible within that specific
function.
Ø Once the function execution completes, the local
variables are destroyed.
Ø Local variables can have the same names as
variables in other functions or in the global scope without causing conflicts.
2. Global Scope:
Ø Variables defined outside of any function or at the
module level have a global scope.
Ø They can be accessed and modified from any part of
the code, including within functions.
Ø Global variables persist throughout the program's
execution.
è
What is the difference between Deep
copy and shallow copy?
Ø
Deep copy creates a separate memory
location.
While copying
a list to another variable, if we use deep copy, it creates a separate memory
location for the 2nd list. so, if you change an element in
the 2nd list, the 1st list will not be changed.
Ø
Shallow copy uses the same memory
location.
While copying a
list to another variable, if we use shallow copy, it uses the same memory
location for the 2nd list. If you change an element in the 2nd list,
then the 1st list values also will change.
è What is a decorator in Python, and how is it used with functions?
A decorator is a higher-order function that can be used to modify (or)
enhance the behavior of another function. It is applied using
the @decorator_name syntax.
è
What is a decorator in Python, and
how do you use it to modify a function’s behavior?
A decorator is a function that takes another function as input and
returns a modified version of that function. It is often used to add
functionality to functions without changing their code.
è
How do you pass a function as an
argument to another function in Python?
Ø You can pass a function as an argument by using the function name
without parentheses, like this: my_function(another_function).
Ø Functions can be passed as parameters to other functions because they
are objects.
Ø Higher-order functions are functions that can take other functions as
arguments.
è How do you debug a Python program?
By using the below command, we can debug a Python program:
python3 -m pdb python-script.py
è What is PIP?
Ø PIP is an acronym for Python Installer Package,
which provides a seamless interface to install various Python modules.
Ø pip is a command-line tool that can search for
packages over the internet and install them without any user interaction.
è What is PEP-8?
Ø PEP-8 (Python Enhancement
Proposals)
Ø PEP8 is a coding convention which specifies a set
of guidelines about how to write consistent python code and more readable code.
Ø always a good idea, and adopting a nice coding
style
è What is Python Switch Statement
Ø From version 3.10 upward, Python has implemented a
switch case feature called “structural pattern matching”.
Ø You can implement this feature with the match and
case keywords.
Ø Note that the underscore symbol is what you use to
define a default case for the switch statement in Python.
Note: Before Python 3.10 Python doesn’t support match
Statements.
match term:
case pattern-1:
action-1
case pattern-2:
action-2
case pattern-3:
action-3
case _:
action-default
********** Interview
Questions on Exceptions **********
è What is an exception?
Ø An
exception is a Python object that represents an error.
Ø An
exception occurs during the execution of a program that disturbs the normal
flow of the program instruction.
Ø When
an exception occurs, the program stops its normal execution and jumps to a
special code block known as an exception handler.
Syntax:
·
try:
It contains suspicious code, if any error
occurs then it will go to except block otherwise it will execute the statements.
·
except:
o It
catches the error from the try block.
o
If
an exception occurs in the try block, the
corresponding except block is executed. It handles and catches the
exception, preventing the program from crashing
·
else: else block is executed if no exceptions occur in the try block.
It contains code that should run only when there are no exceptions.
·
finally
block always
gets executed, whether an exception occurs or not.
It is useful for releasing
resources or cleaning up, ensuring that certain actions are taken regardless of
the outcome.
è Explain the difference
between syntax errors and exception
Syntax
Errors: also
known as parsing errors
·
Syntax errors, occur when there is a mistake in the code structure.
·
Syntax errors indicate that the code violates the language's grammar
rules.
·
These errors are detected by the Python interpreter during the parsing
(compilation) phase before the program is executed.
# Syntax Error
print("Hello,
World!"
Output:
File "", line 2
print("Hello, World!"
^
SyntaxError: unexpected EOF
while parsing
Exceptions:
·
Exceptions occur during the execution of the program.
·
These errors are not detected by the parser but are raised during runtime when a specific condition
is encountered.
·
Exceptions can be handled using try, except, else, and finally
blocks.
è Can you catch multiple
exceptions in a single except block?
Yes, you can catch multiple
exceptions in a single except block by using a tuple.
try:
# Some code that might raise an
exception
x = int("invalid")
except (ValueError, TypeError) as e:
print("Caught an
exception:", e)
********** Interview
Questions on file Handling **********
è What is file handling in Python?
Ø A file
is a collection of information.
Ø File handling is an important part of any
web/mobile/desktop/hardware application
Ø Python has several functions for creating, reading,
updating, and deleting files
Ø The key
function for working with files in python is the open () function. The open
function takes two arguments: filename, and mode.
## Syntax for Open a file
f_object = open(filename_along_with_path, [mode])
è How many modes
are available for files?
There are different modes for opening a file:
o txt
file modes: r r+, w w+,
a a+
o binary
file modes: rb rb+, wb wb+, ab ab+
è What is the difference
b/w open() and with open()?
Ø
open()
function is used to open a file in the required mode
Ø
with
open() closes the file automatically
after the task is completed, ensuring file safety and preventing memory issues.
Ex:
with open("narendra.txt",'w+') as f_obj:
f_obj.write("my first file\n")
f_obj.seek(0,0)
print(f_obj.read())
è What is the difference
between r+, w+, and a+ ?
r+
·
Opens
a file for both reading and writing.
·
If
the file does not exist, it gives a “File not found” error).
w+
·
Opens
a file for both writing and reading.
·
If
the file does not exist, create a new file for reading and writing.
·
If
the file exists with data, Overwrites the existing file (i.e old data will be
erased).
a+
·
Opens
a file for both appending and reading.
·
If
the file does not exist, it creates a new file for reading and writing.
·
If
the file exists with data, it will append new data at the end
è How can you check if a
file exists in Python before opening it?
You
can check if a file exists using the os.path.exists()
function
from the os
module before
attempting to open it.
è What is the difference
between the read(), readline() and readlines() methods when
reading a file?
read() method is used to read the entire content of a file as a
single string
readline() reads one line at a time.
readlines() reads all lines in the file into a list
è How do you handle exceptions when working with files in
Python?
You
can use try
...except
blocks
to handle exceptions, such as FileNotFoundError
or IOError
,
that may occur when working with files.
è What is the purpose of the seek()
&
tell() method in file handling?
The seek()
method
is used to change the current cursor position in the file.
syntax:
seek(offset, [from])
offset --> The offset argument indicates the number of
bytes to be moved.
from --> The
from argument specifies the reference position from where the bytes are to be
moved.
·
If from is set to 0,
the beginning of the file is used as the reference position.
·
If it is set to 1,
the current position is used as the reference position.
· If it is set to 2 then the end of the file would be taken
as the reference position.
The
tell() method tells you the current cursor position within the file
è What is the
purpose of the os.path.join()
function
in file handling?
Ø The os.path.join()
function
is used to create platform-independent file paths by joining directory and file
name components.
è How do you check if a
file is a directory or a regular file in Python?
Ø You can use the os.path.isdir()
and os.path.isfile()
functions
to check if a path corresponds to a directory or a regular file.
è What is the purpose of
the os.path.dirname() & os.path.basename(), os.path.split() functions
in file handling?
Ø os.path.dirname()
extracts
the directory part of a path, excluding the filename.
Ø os.path.basename() extracts
the base name (filename) from a path, ignoring the directory part.
Ø os.path.split() splits a path
into its directory and filename components
è How do you
list files and directories in a directory using Python?
Ø You can use the os.listdir()
function to list files and directories in a
directory.
è What is a generator
function?
Ø A
generator function is a normal function except that it contains yield
expression in the function definition making it a generator function.
è What is an iterator?
Ø An
iterator is an object that allows a programmer to iterate through all the elements
of a collection.
********** Interview
Questions on comprehensions **********
è What is comprehension?
Ø Comprehension
in Python provides us with a short way to construct new sequences (such as
lists, sets, dictionaries, etc.) using sequences that have been already
defined.
Advantages of using comprehensions
·
No need to declare an
empty list/set/dictionary.
·
No need to write an
append method, comprehension will take care of both.
Python has 3 comprehensions
·
List
comprehension
·
Dictionary
comprehension
·
Set
comprehension.
List Comprehensions
List Comprehensions provide an elegant way to create new lists.
Syntax: Variable = [expression(element) for element in iterable]
Ex: list_1 =
["Always", "Trust yourself", "Do",
Hard-work", "You", "can", "reach",
"your", "goals", "easily"]
x = [((len(i)) *3)
for i in list_1]
# It calculates the
length of each word & length multiplied by 3 then the result is stored in
the same list instead of taking a new empty list and appending the result
print(x) # [18, 42,
6, 27, 9, 9, 15, 12, 15, 18]
·
Set Comprehensions
Syntax: Variable = {expression(item) for item in iterable}
set function
eliminates duplicate objects present if any result set will not store in order
because the set is unordered.
from math import factorial
f =
{len(str(factorial(x))) for x in range (20)}
print(f) # length
of factorial of numbers till 19
# Result :
set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 18])
# Note:
duplicate elements were discarded because of set comprehension
·
Dictionary Comprehensions
Syntax: Variable = {key_expr : value_expr for item in iterable}
Ex: Naren =
[1,2,3,4]
x = {i: i**i for i
in Naren} # dictionary comprehension print(x)
# Output {1:
1, 2: 4, 3: 27, 4: 256}
è Why do we not use tuple
comprehension in Python?
Ø Because
a tuple is an immutable object, we cannot change inside a tuple object so in
Python tuple comprehension isn’t supported.
è
What is lambda in Python and what is
the drawback of lambda?
Ø
Lambda function is a single-line anonymous function but not declared in the
standard manner by using the “def” keyword
Ø
Drawback: lambda function
allows multiple arguments in it but can return only one return value in
the form of an expression.
è
Define Map( ) and filter( )
Ø
map() will apply the same function to every element of iterable /sequence and return
a list of the results.
Ø
filter() The filter(function_name,
iterable) function offers a way, to filter out all the elements
of a list, for which the function returns True.
********** Interview
Questions on class **********
è
What is Class?
Ø
Class is nothing but just blue-print
and there is no use of class definition until, unless you have created the
instance for that class.
Ø
Advantages of classes compared with functions
·
We can provide a specific class name
by grouping functions in the form of methods
·
We can inherit the class into another
class.
·
We can perform multiple class-related
properties (single/multiple/hybrid inheritances, Data hiding/abstraction/
method overriding / encapsulation...)
è
Difference between
method and function?
Ø
A function that is defined inside of
the class is a method.
Ø
A function that is defined outside of
the class is a Function.
è
What is the _ _init_ _ () method or
the Constructor method?
Ø
Constructor method (def
__init__(self)) is a special kind of method,
as soon as you have created an object/ instance for the class then
automatically,
_ _init_ _ method will be executed,
without calling it.
è
What is an attribute in Python?
Ø An attribute is nothing but a variable defined inside the class
definition, also known as class variable.
Ø class variables are shared among multiple instances created for a
specific class.
General information
regarding identifiers:
· Class
name starts with an uppercase letter.
· All
other identifiers start with a lowercase letter (Ex: variable, function,
method).
· Starting
an identifier with a single leading underscore indicates that the identifier is
private (private variables/private method).
Explanation:
o Generally, we use
private variables & private methods inside a class for Data hiding purposes.
o Outside the class,
you cannot access the private variables as well as the private methods.
· Starting
an identifier with two leading underscores indicates a
strongly private identifier.
· If
the identifier ends with two trailing underscores, the identifier
is a language-defined special name.
Example: __author__ = "Narendra Boyina"
è
What is the difference between the
class variable and the instance variable?
Ø
Class variables, also known as static
variables, have the same value across all instances of a class.
Ø
Instance variables are specific to
each instance of a class and are owned by those instances.
Ø
Class variables are defined within
the class but outside of class methods, and they are not used as frequently as
instance variables.
Ø
Class variables are shared among
multiple instances of the class, while instance variables are independent and
unique to each instance.
è
What are the oops features in Python?
Ø
The mechanism of deriving a new class
from an existing class is known as inheritance.
Ø
Here, the base class is known as a
parent class and the derived class is a child class.
Ø
Types of inheritance:
· Single inheritance: A derived class inherits from
only one base class.
· Multiple inheritance: A derived class inherits from multiple base
classes.
· Multilevel inheritance: The mechanism of deriving a class from another derived class. In this
type of inheritance one derived class acts as a base class for another derived
class. (There is no permanent base class & permanent derived class)
· Hierarchical inheritance: Multiple derived classes have only one base class.
This type of inheritance is used to maintain a tree-structured relation.
· Hybrid inheritance:
The combination of more
than one form of inheritance.
Ø
Method overriding:
The same method names for different classes are called method overriding.
Ø
Data hiding & Abstraction:
·
We can hide
attributes and methods based on requirements.
·
To hide attributes
and methods, we need to use a double underscore prefix for the attributes and methods.
Syntax: __Class
attribute/method name
·
Directly we can’t
access hidden attributes or hidden methods outside the class definition.
Ø
Abstraction:
If you want to view hidden attributes and methods, you can use data
abstraction.
·
Syntax: instance.single
underscore class namedouble_underscore attribute/method name
Ø
Polymorphism: It means different
types of responses to the same function.
Ex: num = 1
num.__add__(2) o/p : 3
Ø
Encapsulation: Encapsulation
means binding the code and the data together.
Ex:
A Python class is an example of encapsulation.
è What is Python superfunction?
Ø Python Super() Function allows us to call the same method that is available in the parent class.
è What are the compound statements?
Ø if, else, elif, for, while, def, and class are compound statements, and these should be terminated with a colon (:)
è Define the Pass keyword
Ø pass means, a no-operation Python statement,
Ø pass is a placeholder in a compound statement when syntactically some code is required but no
action is desired
è What is assert keyword in Python?
Ø Python's assert statement is a
debugging aid that tests a condition.
Ø If the condition is true, it does nothing and
your program just continues to execute.
Ø But if the assert condition evaluates to false,
it raises an AssertionError exception with an optional error message.
x = "narendra"
#if the condition returns False,
AssertionError is raised:
assert x == "Narendra", "x
should be 'narendra'"
è What are Python namespaces? Why are they used? Scope in Python
Ø A namespace in Python
ensures that object names in a program are unique and can be used without any
conflict.
Ø Python implements
these namespaces as dictionaries with 'name as key' mapped to a corresponding
'object as value'.
Ø This allows for
multiple namespaces to use the same name and map it to a separate object.
A few examples of
namespaces are as follows:
· Local Namespace includes local
names inside a function. the namespace is temporarily created for a function
call and gets cleared when the function returns. Examples :
narendra =30, x = 40, y =50 defined inside functions
· Global Namespace includes names
from various imported packages/ modules that are being used in the current
project. This namespace is created when the package is imported in the script
and lasts until the execution of the script.
· Built-in Namespace includes
built-in functions of core Python and built-in names for various types of
exceptions. Examples: print(), id(), type(), len(), input()
********** Interview
Questions on Modules **********
è
What is a module and the purpose of a module?
Ø
Python module is nothing but a Python
file. That filename is referred to as the module name while importing to
another
Ø
Purpose of a module:
For using the functions, class
methods are defined in another file in the current Python file.
è
How many types of modules Python have?
Python has 3 types of modules
· User-defined modules: We need to create these modules
· Internal modules: During the installation of the Python, these modules will be installed Ex: string, time, calendar,
random, os, sys, re, json, math, …etc
· External modules: We need to install these modules, openpyxl, paramiko, serial, and subprocess,
pandas, numpy
è What internal & external modules do you know?
Internal Modules: datetime, time, calendar, random, os, sys, re, json,
string
External Modules: openpyxl, paramiko,
serial, and subprocess, pandas, numpy
è Tell the different ways of utilizing modules in your code?
We can use modules in 17
ways.
Different ways to utilize
modules
1. import module_name
2. from module_name import function
3. from module_name import function_1, function_2, ..., funcetion_n
4. from module_name as alias_name (or) short_name
5. from module_name import function as alias_name (or) short_function_name
6. from module_name import *
7. from directory_name import module_name
8. from directory_name.module_name import function
9. from directory_name.module_name import function1, function2,... function_n
10. from directory_name.module_name import function_name as alias_name (or)
short_name
11. from directory_name.module_name import function_names as alias_names (or)
short_names
12. from directory_name.module_name import *
(all functions)
13. from directory_name.module_name import class_name
14. from directory_name.module_name import class_name1, class_name2,
...class_name_n
15. from directory_name.module_name import * (importing all class, functions
and all )
16. from directory_name.module_name import class_name as alias_name (or) short_name
17. from directory_name.module_name import class_names as alias_names (or)
short_names
è What is the module and package in Python?
Ø Module is a way to structure a program. Each Python program file is a
module, which imports other modules like objects and attributes.
Ø The folder of the Python program is a package of modules. A package can
have modules or subfolders.
Ø If a folder contains __init__ (constructer) then it is a package (it may
be an empty constructer) otherwise, it is just a folder.
è How can you share global variables across modules?
Ø To share global
variables across modules within a single program, create a special
module.
Ø Import the config
module in all modules of your application.
Ø The module will be
available as a global variable across modules.
è Define JSON Module
Ø
JSON stands for javascript object
notation. Inspired by Java script but now independent of any programming
language.
In
json module, the most frequent functions are 4:
Ø load: It is used to read the dictionary data, from JSON
files.
Ø loads: It is used to convert the JSON string into the
Python dictionary.
Ø dump: It is used for writing the Python object i.e.,
dictionary to JSON file.
Ø dumps: It
converts a Python object into a JSON string.
è What is the purpose of os module?
Ø
The os module in Python
provides a way to interact with the operating system.
Ø
os module is
essential for performing a wide range of operating system-related tasks.
Key Purposes of the os Module
Ø File and Directory Management:
o Creating and Removing Directories: Functions like os.mkdir() to create directories
and os.rmdir() to remove them.
o Listing Files and Directories: os.listdir() to list files in a directory.
o Renaming and Removing Files: os.rename() for renaming and os.remove()for
deleting files.
Ø Path Manipulation:
o Path Operations: Functions like os.path.join(), os.path.exists(), and os.path.abspath()
help in manipulating file paths in a platform-independent way.
o Checking File Types: os.path.isfile() and os.path.isdir() to check if
a path is a file or directory.
Ø Environment Variables:
o Accessing Environment Variables: os.getenv() to get environment variable values
and os.environ to access all environment variables.
o Setting Environment Variables: You can use os.environ to set environment
variables.
Ø Executing Shell Commands:
o Running Commands: Functions like os.system() and os.exec*() allow you to execute shell
commands from within your Python script.
Ø Working with Current Working Directory:
o Getting and Changing the Current Directory: os.getcwd() to get the current working directory
and os.chdir() to change it.
Ø Process Management:
o Managing Processes: Functions like os.getpid() to get the current
process ID, and os.kill() to terminate a process.
è What is the purpose of paramiko module?
Ø The paramiko module in Python is primarily used for handling SSH (Secure
Shell) connections, allowing you to perform operations on remote servers
securely.
Ø It provides an interface to work with SSH2, enabling you to connect to
remote machines, execute commands, transfer files, and manage SSH keys.
Ø Install Paramiko in PyCharm.
go to File-->Settings--Project-->Project Interpreter . Then hit the plus sign, and type paramiko
Ø How to use paramiko to connect to a remote server,
execute a command, and retrieve the output:
import paramiko
ssh =
paramiko.SSHClient() # Create an SSH client
ssh.load_system_host_keys() # Load system host keys
# Automatically add
the server's host key (not recommended for production)
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# Connect to the
remote server
hostname =
'your.remote.server'
username =
'your_username'
password = 'your_password' # Use key-based authentication for better
security
try:
ssh.connect(hostname, username=username,
password=password)
# Execute a command
stdin, stdout, stderr =
ssh.exec_command('ls -l')
# Print the command output
print("Command Output:")
for line in stdout:
print(line.strip())
# Print any errors
print("Errors:")
for line in stderr:
print(line.strip())
finally:
# Close the connection
ssh.close()
è How you can use paramiko for SFTP file
transfers
import paramiko
# Create an SFTP session
ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
hostname = 'your.remote.server'
username = 'your_username'
password = 'your_password'
try:
ssh.connect(hostname,
username=username, password=password)
# Start an SFTP session
sftp = ssh.open_sftp()
# Upload a file
sftp.put('local_file.txt',
'remote_file.txt')
print("File uploaded
successfully.")
# Download a file
sftp.get('remote_file.txt',
'downloaded_file.txt')
print("File downloaded
successfully.")
# List files in the remote
directory
print("Files in remote directory:")
print(sftp.listdir('.'))
finally:
sftp.close() # Close SFTP session
ssh.close() # Close SSH connection
è
What are the advantages of NumPy over regular Python lists?
Ø Memory
Numpy arrays consume less
memory.
For example, if you create
a list and a Numpy array of a thousand elements. The list will consume 48K
bytes, and the Numpy array will consume 8k bytes of memory.
Ø Speed
Numpy arrays take less time
to perform the operations on arrays than lists.
For example, if we are
multiplying two lists and two Numpy arrays of 1 million elements together. It
took 0.15 seconds for the list and 0.0059 seconds for the array to
operate.
Ø Vesititly
Numpy arrays are convenient
to use as they offer simple array multiple, addition, and a lot more built-in
functionality. Whereas Python lists are incapable of running basic
operations.
è What is the purpose of the pandas module?
Ø The pandas module in Python is a powerful and
widely-used library for data manipulation and analysis.
Ø pandas provides data structures and functions
needed to work with structured data effectively, making it an essential tool
for data scientists, analysts, and anyone working with data in Python.
Key Features of the Pandas Module
1.
Data
Structures:
o
Series: A one-dimensional labeled array that can hold any
data type. It’s similar to a list or a dictionary.
o
DataFrame: A two-dimensional labeled data structure, similar
to a spreadsheet or SQL table, where data is organized in rows and columns.
2.
Data
Manipulation:
o
Data Cleaning: Functions for handling missing data, removing
duplicates, and transforming data types.
o
Filtering and
Selection: Easily filter and select
data based on conditions.
o
Aggregation: Grouping data and applying aggregation functions
like sum, mean, etc.
3.
Data Input
and Output:
o
Support for
reading data from various file formats, including CSV, Excel, SQL databases,
JSON, and more.
o
Ability to
write data frames to different file formats.
4.
Time Series
Analysis:
o
Built-in
functions to work with time series data, including resampling, frequency
conversion, and moving window statistics.
5.
Merging and
Joining:
o
Functions to
merge and join different DataFrames based on common keys or indices.
6.
Data
Visualization:
o
Integration
with visualization libraries like Matplotlib and Seaborn to create plots
directly from DataFrames.
simple
example to demonstrate some common functionalities of the pandas module
import pandas as pd
# Creating a
DataFrame
data = {
'Name': ['Alice', 'Bob', 'Charlie',
'David'],
'Age': [24, 30, 22, 35],
'City': ['New York', 'Los Angeles',
'Chicago', 'Houston']
}
df =
pd.DataFrame(data)
# Display the
DataFrame
print("Original
DataFrame:")
print(df)
# Filtering rows
where Age > 25
filtered_df =
df[df['Age'] > 25]
print("\nFiltered
DataFrame (Age > 25):")
print(filtered_df)
# Adding a new
column
df['Salary'] =
[70000, 80000, 65000, 90000]
print("\nDataFrame
with Salary column added:")
print(df)
# Grouping by City
and calculating the average age
average_age =
df.groupby('City')['Age'].mean()
print("\nAverage
Age by City:")
print(average_age)
# Saving the
DataFrame to a CSV file
df.to_csv('people.csv', index=False)
print("\nDataFrame saved to 'people.csv'")
è What is the purpose of the sys module in Python?
Ø
The sys module in Python provides
access to system-specific parameters and functions that interact closely with
the Python interpreter.
Ø The sys module is beneficial when writing scripts that need to
interact with the interpreter or access command-line arguments, system
paths, and other environment-related variables.
Ø
It allows you to manipulate the
Python runtime environment and interact with the operating system in several
useful ways.
Key Purposes of the sys
Module:
Command-line
Arguments:
Ø
The sys.argv list holds command-line arguments passed to the Python script.
Ø
The first item in the list is the script
name, and the subsequent items are the arguments passed to the script.
import sys
print(sys.argv)
run the python script on the cmd prompt or bash using the below
command
python3 script.py Narendra
Surendra 472 732
output ['script.py', “Narendra”, “Surendra”, 472, 732]
Exiting a Program:
The sys.exit()
function allows
you to terminate the Python interpreter.
You can optionally pass an exit status code, where 0
indicates success, and any non-zero value indicates an error.
import sys
if some_condition:
sys.exit("Exiting the
program due to an error")
System Path:
Ø
sys.path is a list of directories
where Python looks for modules.
Ø
You can modify this list to add or
remove directories, allowing you to dynamically change where Python searches
for modules.
import sys
print(sys.path) # List of paths
where Python searches for modules
sys.path.append('/path/to/my/module')
# Add a custom path
Interpreter-Related
Information:
Ø sys.platform: Returns
a string that identifies the platform (e.g., 'linux', 'win32', 'darwin' for
macOS).
Ø
sys.executable: Provides the path of
the Python interpreter executable.
Ø sys.maxsize: Represents the maximum
size of a Python object (e.g., the largest integer)
import sys
print(f"Platform: {sys.platform}")
print(f"Interpreter path: {sys.executable}")
print(f"Max integer size: {sys.maxsize}")
Python
Version:
Ø sys.version provides information about the Python version
that is currently being used.
import sys
print(sys.version)
output:
3.12.6 (tags/v3.12.6:a4a2d2b, Sep 6 2024, 20:11:23) [MSC v.1940 64 bit (AMD64)]
Request: Please
provide your valuable comments