Interview Python
Interview Python
Home
Interview Questions
Java
SQL
Python
JavaScript
Angular
Selenium
Spring Boot
HR
C
Data Structure
DBMS
HTML
C#
C++
All Interview
Interview TipsJOB/HR InterviewCompetency InterviewBusiness AnalystBehavioral
Interview
Company Interview
Company InterviewIBM InterviewInfosys InterviewCapgemini InterviewCognizant
InterviewWipro InterviewAccenture InterviewiGate InterviewTCS InterviewHCL
InterviewAdobe InterviewMicrosoft InterviewDXC Technology InterviewEricsson
InterviewEXL Service InterviewIndiaMART InterviewIntuit InterviewSpaceX
InterviewSapient InterviewAmazon Interview
Technical Interview
C InterviewC++ InterviewData Structure InterviewLinux InterviewUnix InterviewShell
ScriptingNetworking InterviewCCNA InterviewAndroid InterviewCloud ComputingHadoop
InterviewTesting/QTP InterviewSelenium InterviewWeb Services InterviewOS
InterviewExcel InterviewSEO InterviewDigital MarketingPython Interview Django
InterviewPascal InterviewRuby InterviewRuby on Rails InterviewMemcached InterviewGo
InterviewOpenStack InterviewScala InterviewControl SystemsElectrical MachinesPower
SystemDigital ElectronicsRobotics InterviewTypeScript InterviewSwift
InterviewBlockchain InterviewBitcoin InterviewAWS InterviewInformatica InterviewQA
InterviewReact InterviewGIT InterviewJ2EE InterviewDeep LearningSalesforce
InterviewTestNG InterviewAgile InterviewMachine LearningAPI TestingAlgorithmJava
Design PatternTeradataTensorFlowLINQMainframeLaravelJIRAJCLPytorchETL
TestingLinked ListDataStageTableauSAP ABAPDAAComputer GraphicsData
ScienceSoftware EngineeringPower BIXamarinAnsibleData WarehouseIonicDevopsReact
NativePython PandasHTTP InterviewKali Linux InterviewPowerShell InterviewSharePoint
InterviewTalend InterviewMicrosoft Azure InterviewR InterviewFlutter InterviewMATLAB
InterviewES6 InterviewRPA InterviewDesktop Support InterviewAngular 8
InterviewGraphQL InterviewVue.js InterviewAutomation Anywhere InterviewAI
InterviewUiPath InterviewBlue Prism InterviewSSIS InterviewMobile Computing
InterviewITIL InterviewSAS InterviewElasticsearch InterviewEntity Framework
InterviewRxJS InterviewAccounting InterviewElectron.js InterviewKnockout JS
InterviewTop Angular InterviewIAS Interview QuestionBanking InterviewInterview
Questions for FreshersPowerPoint InterviewBPO InterviewCivil Engineering
InterviewApache Spark InterviewData Mining InterviewJava Support
InterviewKubernetes InterviewWeb API InterviewScrum Master InterviewSystem Design
InterviewSSB Interview QuestionsTeachers Interview QuestionsFinance Interview
QuestionsTechnical Support InterviewActive Directory InterviewAppium
InterviewCucumber InterviewFull-Stack DeveloperServiceNow InterviewNursing
InterviewSales InterviewMicroservices InterviewElectrical Engineering InterviewAccounts
Payable InterviewVISA InterviewVLSI InterviewAutoCAD InterviewVerilog InterviewOOPs
InterviewWeb Developer InterviewExpress.js InterviewCakePHP InterviewYii
InterviewZend Framework InterviewJava Concurrency InterviewSymfony InterviewBasic
InterviewDynamic Programming InterviewProgramming InterviewNext.js
InterviewMicrosoft Java InterviewAEM InterviewSvelte.js InterviewCOBOL
InterviewCyber Security InterviewSQL Query InterviewBGP InterviewApache Hive
InterviewKafka InterviewEmbedded C InterviewPega InterviewKotlin InterviewSAP MM
InterviewOSPF InterviewMobile Testing InterviewMulesoft InterviewTerraform
InterviewSalesforce Lightning InterviewSCCM InterviewPostman InterviewContent Writer
InterviewIoT InterviewNLP InterviewSplunk InterviewPostgreSQL InterviewTricky Java
InterviewPySpark InterviewVBA InterviewFront End Developer InterviewComputer
Science InterviewData Modeling InterviewGoogle Analytics InterviewSqoop
InterviewStatistics InterviewTally InterviewCICS InterviewChemistry InterviewData
Engineer InterviewAzure Data Factory InterviewInsurance InterviewIIS InterviewMS
Word InterviewSDET InterviewWeblogic InterviewPHP OOPs InterviewCheckpoint
InterviewPython Coding InterviewGarbage Collection InterviewPython Interview
Questions for Five Years ExperiencedLinkedIn Python 2022 Qualifying Assessment
AnswersTop Coding Interview Questions on Arrays-C
Web Interview
HTML InterviewCSS InterviewJavaScript InterviewjQuery InterviewAngularJS
InterviewAngular InterviewAngular 7 InterviewNode.js InterviewAJAX InterviewXML
InterviewDojo InterviewBackbone.js InterviewEmber.js InterviewXHTML InterviewXSLT
InterviewXPath InterviewXQuery InterviewXForms InterviewSASS InterviewCoffeeScript
InterviewLESS InterviewPerl InterviewPure.CSS InterviewMaterialize
InterviewFramework7 InterviewSVG InterviewSAP FICO InterviewAb Initio Interview
PHP Interview
PHP InterviewWordpress InterviewJoomla InterviewDrupal InterviewMagento
InterviewCodeIgniter InterviewPhalcon Interview
.Net Interview
.Net InterviewC# InterviewASP.NET InterviewADO.NET InterviewWCF InterviewWPF
InterviewSilverlight InterviewF# Interview
Java Interview
Java 1 InterviewJava 2 InterviewException & StringMultithreadingCollections
InterviewJDBC InterviewServlet InterviewJSP InterviewEJB InterviewStruts
InterviewHibernate InterviewSpring InterviewSpring Boot InterviewSpring MVC
InterviewJPA InterviewMaven InterviewJUnit InterviewJSF InterviewPrimeFaces
InterviewRichFaces InterviewGWT InterviewJDB InterviewJOGL InterviewjBPM
InterviewJenkins InterviewJava Constructor InterviewTechnical Architect InterviewArray
Interview Questions
Database Interview
DBMS InterviewSQL InterviewPL/SQL InterviewOracle InterviewMySql InterviewSQL
Server InterviewMongoDB InterviewCassandra InterviewDB2 InterviewAccess
InterviewSQLite InterviewCouchDB InterviewNeo4j InterviewMariaDB InterviewPouchDB
InterviewRedis Interview
Python Interview Questions
A list of frequently asked Python interview questions with answers for freshers and
experienced are given below.
1) What is Python?
2) Why Python?
Python provides various web frameworks to develop web applications. The popular
python web frameworks are Django, Pyramid, Flask.
Python's standard library supports for E-mail processing, FTP, IMAP, and other
Internet protocols.
Free and open source: It is an open-source project which is publicly available to reuse.
It can be downloaded free of cost.
o It is Extensible
o Object-oriented
Built-in data structure: Tuple, List, and Dictionary are useful integrated data structures
provided by the language.
o Readability
o High-Level Language
o Cross-platform
Portable: Python programs can run on cross platforms without affecting its
performance.
5) What is PEP 8?
PEP 8 stands for Python Enhancement Proposal, it can be defined as a document
that helps us to provide the guidelines on how to write the Python code. It is basically
a set of rules that specify how to format Python code for maximum readability. It was
written by Guido van Rossum, Barry Warsaw and Nick Coghlan in 2001.
String Literals
String literals are formed by enclosing text in the single or double quotes. For
example, string literals are string values.
Example:
1. # in single quotes
2. single = 'JavaTpoint'
3. # in double quotes
4. double = "JavaTpoint"
5. # multi-line String
6. multi = '''''Java
7. T
8. point'''
9.
10. print(single)
11. print(double)
12. print(multi)
Output:
JavaTpoint
JavaTpoint
Java
T
point
Numeric Literals
Python supports three types of numeric literals integer, float and complex.
Example:
1. # Integer literal
2. a = 10
3. #Float Literal
4. b = 12.3
5. #Complex Literal
6. x = 3.14j
7. print(a)
8. print(b)
9. print(x)
Output:
10
12.3
3.14j
Boolean Literals
Boolean literals are used to denote Boolean values. It contains either True or False.
Example:
1. p = (1 == True)
2. q = (1 == False)
3. r = True + 3
4. s = False + 7
5.
6. print("p is", p)
7. print("q is", q)
8. print("r:", r)
9. print("s:", s)
Output:
p is True
q is False
r: 4
s: 7
Special literals
Python contains one special literal, that is, 'None'. This special literal is used for
defining a null variable. If 'None' is compared with anything else other than a 'None',
it will return false.
Example:
1. word = None
2. print(word)
Output:
None
o Built-In Functions: copy(), len(), count() are the some built-in functions.
o User-defined Functions: Functions which are defined by a user known as
user-defined functions.
o Anonymous functions: These functions are also known as lambda functions
because they are not declared with the standard def keyword.
Signature
Parameters
iterator1, iterator2, iterator3: These are iterator objects that are joined together.
Return
Note: If the given lists are of different lengths, zip stops generating tuples when the first
list ends. It means two lists are having 3, and 5 lengths will create a 3-tuple.
9) What is Python's parameter passing mechanism?
There are two parameters passing mechanism in Python:
o Pass by references
o Pass by value
By default, all the parameters (arguments) are passed "by reference" to the functions.
Thus, if you change the value of the parameter within a function, the change is
reflected in the calling function as well. It indicates the original variable. For example,
if a variable is declared as a = 10, and passed to a function where it's value is modified
to a = 20. Both the variables denote to the same value.
The pass by value is that whenever we pass the arguments to the function only values
pass to the function, no reference passes to the function. It makes it immutable that
means not changeable. Both variables hold the different values, and original value
persists even after modifying in the function.
Python has a default argument concept which helps to call a method using an
arbitrary number of arguments.
Example:
1. class student:
2. def __init__(self, name):
3. self.name = name
4. def __init__(self, name, email):
5. self.name = name
6. self.email = email
7.
8. # This line will generate an error
9. #st = student("rahul")
10.
11. # This line will call the second constructor
12. st = student("rahul", "rahul@gmail.com")
13. print("Name: ", st.name)
14. print("Email id: ", st.email)
Output:
Name: rahul
Email id: rahul@gmail.com
Example:
1. list_1 = [ 3, 5, 7, 3, 9, 3 ]
2. print(list_1)
3. list_1.remove(3)
4. print("After removal: ", list_1)
Output:
[3, 5, 7, 3, 9, 3]
After removal: [5, 7, 3, 9, 3]
If you want to delete an object at a specific location (index) in the list, you can either
use del or pop.
Example:
1. list_1 = [ 3, 5, 7, 3, 9, 3 ]
2. print(list_1)
3. del list_1[2]
4. print("After deleting: ", list_1)
Output:
[3, 5, 7, 3, 9, 3]
After deleting: [3, 5, 3, 9, 3]
Note: You don't need to import any extra module to use these functions for removing an
element from the list.
We cannot use these methods with a tuple because the tuple is different from the list.
Example:
Output:
it is in lowercase.
IT IS IN UPPERCASE.
13) How to remove whitespaces from a string in Python?
To remove the whitespaces and trailing spaces from the string, Python providies
strip([str]) built-in function. This function returns a copy of the string after removing
whitespaces if present. Otherwise returns original string.
Example:
Output:
javatpoint
javatpoint
javatpoint
After stripping all have placed in a sequence:
Javatpoint
javatpoint
javatpoint
Example:
Output:
javatpoint
javatpoint
After stripping all leading whitespaces:
javatpoint
javatpoint
After stripping, all the whitespaces are removed, and now the string looks like the
below:
Example:
1. str = "Rohan"
2. str2 = "ab"
3. # Calling function
4. str2 = str.join(str2)
5. # Displaying result
6. print(str2)
Output:
aRohanb
16) Give an example of shuffle() method?
This method shuffles the given string or an array. It randomizes the items in the array.
This method is present in the random module. So, we need to import it and then we
can call the function. It shuffles elements each time when the function calls and
produces different output.
Example:
Output:
Original LIST1:
['Z', 'Y', 'X', 'W', 'V', 'U']
Output:
2
X 11
X 22
X 33
Y 11
Y 22
Y 33
BREAK
Python Break statement flowchart.
Example:
1. # Declaring tuple
2. tup = (2,4,6,8)
3. # Displaying value
4. print(tup)
5.
6. # Displaying Single value
7. print(tup[2])
Output:
(2, 4, 6, 8)
6
Example:
1. # Declaring tuple
2. tup = (2,4,6,8)
3. # Displaying value
4. print(tup)
5.
6. # Displaying Single value
7. print(tup[2])
8.
9. # Updating by assigning new value
10. tup[2]=22
11. # Displaying Single value
12. print(tup[2])
Output:
tup[2]=22
TypeError: 'tuple' object does not support item assignment
(2, 4, 6, 8)
Here, os and os.path - modules include a function for accessing the filesystem
while shutil - module enables you to copy and delete the files.
o Read-only mode (r): Open a file for reading. It is the default mode.
o Write-only mode (w): Open a file for writing. If the file contains data, data
would be lost. Other a new file is created.
o Read-Write mode (rw): Open a file for reading, write mode. It means updating
mode.
o Append mode (a): Open for writing, append to the end of the file, if the file
exists.
Example:
1. # Unary Operator
2. A = 12
3. B = -(A)
4. print (B)
5. # Binary Operator
6. A = 12
7. B = 13
8. print (A + B)
9. print (B * A)
10. #Ternary Operator
11. A = 12
12. B = 13
13. min = A if A < B else B
14.
15. print(min)
Output:
# Unary Operator
-12
# Binary Operator
25
156
# Ternary Operator
12
Example:
Output:
35
-11
276
0.5217391304347826
Relational Operators are used to comparing the values. These operators test the
conditions and then returns a boolean value either True or False.
Example:
1. a, b = 10, 12
2. print(a==b) # False
3. print(a<b) # True
4. print(a<=b) # True
5. print(a!=b) # True
Output:
False
True
True
True
Assignment operators are used to assigning values to the variables. See the
examples below.
Example:
Output:
12
14
12
24
576
Logical operators are used to performing logical operations like And, Or, and Not.
See the example below.
Example:
Output:
False
True
True
Example:
Output:
False
True
Identity Operators (is and is not) both are used to check two values or variable which
are located on the same part of the memory. Two variables that are equal does not
imply that they are identical. See the following examples.
Example:
Output:
False
True
Bitwise Operators are used to performing operations over the bits. The binary
operators (&, |, OR) work on bits. See the example below.
Example:
Output:
8
14
6
-11
Example:
2. print (unicode_1)
Output:
Example:
1. def function_is_called():
2. def function_is_returned():
3. print("JavaTpoint")
4. return function_is_returned
5. new_1 = function_is_called()
6. # Outputs "JavaTpoint"
7. new_1()
Output:
JavaTpoint
27) What are the rules for a local and global variable in Python?
Global Variables:
o Variables declared outside a function or in global space are called global
variables.
o If a variable is ever assigned a new value inside the function, the variable is
implicitly local, and we need to declare it as 'global' explicitly. To make a
variable globally, we need to declare it by using global keyword.
o Global variables are accessible anywhere in the program, and any function can
access and modify its value.
Example:
1. A = "JavaTpoint"
2. def my_function():
3. print(A)
4. my_function()
Output:
JavaTpoint
Local Variables:
Example:
1. def my_function2():
2. K = "JavaTpoint Local"
3. print(K)
4. my_function2()
Output:
JavaTpoint Local
Also, Python implements namespaces in the form of dictionaries and maintains name-
to-object mapping where names act as keys and the objects as values.
In simple words: Iterators are objects which can be traversed though or iterated
upon.
Example:
Output:
Example:
The following example contains some keys Country Hero & Cartoon. Their
corresponding values are India, Modi, and Rahul respectively.
Country: India
Hero: Modi
Cartoon: Rahul
Example:
1. class Student:
2. pass # Passing class
3. class Student:
4. def info():
5. pass # Passing function
String literals occurring immediately after a simple assignment at the top are called
"attribute docstrings".
String literals occurring immediately after another docstring are called "additional
docstrings".
Python uses triple quotes to create docstrings even though the string fits on one line.
Docstring phrase ends with a period (.) and can be multiple lines. It may consist of
spaces and other special chars.
Example:
1. # One-line docstrings
2. def hello():
3. """A function to greet."""
4. return "hello"
35) What is a negative index in Python and why are they used?
The sequences in Python are indexed and it consists of the positive as well as negative
numbers. The numbers that are positive uses '0' that is uses as first index and '1' as
the second index and the process go on like that.
The index for the negative number starts from '-1' that represents the last index in the
sequence and '-2' as the penultimate index and the sequence carries forward like the
positive number.
The negative index is used to remove any new-line spaces from the string and allow
the string to except the last character that is given as S[:-1]. The negative index is also
used to show the index to represent the string in correct order.
The process of retrieving the original Python objects from the stored string
representation is called as Unpickling.
Criteria Java
Help() function: The help() function is used to display the documentation string and
also facilitates us to see the help related to modules, keywords, and attributes.
Dir() function: The dir() function is used to display the defined symbols.
39) What are the differences between Python 2.x and Python
3.x?
Python 2.x is an older version of Python. Python 3.x is newer and latest version. Python
2.x is legacy now. Python 3.x is the present and future of this language.
The most visible difference between Python2 and Python3 is in print statement
(function). In Python 2, it looks like print "Hello", and in Python 3, it is print ("Hello").
The xrange() method has removed from Python 3 version. A new keyword as is
introduced in Error handling.
Example:
Output:
Example:
1. list_1 = ["A","B","C"]
2. s_1 = "Javatpoint"
3. # creating enumerate objects
4. object_1 = enumerate(list_1)
5. object_2 = enumerate(s_1)
6.
7. print ("Return type:",type(object_1))
8. print (list(enumerate(list_1)))
9. print (list(enumerate(s_1)))
Output:
Return type:
[(0, 'A'), (1, 'B'), (2, 'C')]
[(0, 'J'), (1, 'a'), (2, 'v'), (3, 'a'), (4, 't'), (5, 'p'), (6, 'o'), (7,
'i'), (8, 'n'), (9, 't')]
43) Give the output of this example: A[3] if A=[1,4,6,7,9,66,4,94].
Since indexing starts from zero, an element present at 3rd index is 7. So, the output
is 7.
list() - This function is used to convert any data type to a list type.
dict() - This function is used to convert a tuple of order (key,value) into a dictionary.
Example:
1. import smtplib
2. # Calling SMTP
3. s = smtplib.SMTP('smtp.gmail.com', 587)
4. # TLS for network security
5. s.starttls()
6. # User email Authentication
7. s.login("sender@email_id", "sender_email_id_password")
8. # Message to be sent
9. message = "Message_sender_need_to_send"
10. # Sending the mail
11. s.sendmail("sender@email_id ", "receiver@email_id", message)
Example:
Output:
Example:
1. def New_func():
2. print ("Hi, Welcome to JavaTpoint")
3. New_func() #calling the function
Output:
Example:
1. class Employee_1:
2. def __init__(self, name, age,salary):
3. self.name = name
4. self.age = age
5. self.salary = 20000
6. E_1 = Employee_1("pqr", 20, 25000)
7. # E1 is the instance of class Employee.