[go: up one dir, main page]

0% found this document useful (0 votes)
24 views14 pages

Top 50+ Python Interview Questions and Answers (Latest 2024)

Uploaded by

Shibil Haq
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)
24 views14 pages

Top 50+ Python Interview Questions and Answers (Latest 2024)

Uploaded by

Shibil Haq
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/ 14

GEEKSFORGEEKS

Top 50+ Python Interview Questions and Answers (Latest


2024)
Pyt hon is t he most used language in t op companies such as Int el, IBM, NASA, Pixar, Net flix,
Facebook, JP Morgan Chase, Spot ify, and many more because of it s performance and it s
powerful libraries. To get int o t hese companies and organizat ions as a Pyt hon developer, you
need t o mast er some import ant Python Interview Questions t o crack t heir Pyt hon Online
Assessment Round and Pyt hon Int erview Round. We have prepared a list of t he Top 50 Python
Interview Questions along wit h t heir answers t o ace in int erviews.

Pyt hon Int erview Quest ions

Table of Content
Basic Pyt hon Int erview Quest ions for Freshers
Int ermediat e Pyt hon Int erview Quest ions
Advanced Pyt hon Int erview Quest ions & Answers

What is Python?

Pyt hon is one of t he most widely-used and popular programming languages, was developed by
Guido van Rossum and released first on February 20, 1991. Pyt hon is a free and open-source
language wit h a very simple and clean synt ax which makes it easy for developers t o learn Pyt hon.
It support s object -orient ed programming and is most commonly used t o perform general-
purpose programming. Pyt hon is used in several domains like Dat a Science, Machine Learning,
Deep Learning, Art ificial Int elligence, Scient ific Comput ing Script ing, Net working, Game
Open In
Development Web Development , Web Scraping, andApp
various ot her domains.
Pyt hon grows exponent ially due t o it s simplist ic nat ure and t he abilit y t o perform several
funct ions in just a few lines of code. Due t o it s abilit y t o support powerful comput at ions using
powerful libraries, it is used in various domains and it become t he reason for t he huge demand for
Pyt hon developers across t he world. Companies are willing t o offer amazing Packages and
benefit s t o t hese developers.

Basic Python Interview Questions for Freshers

1. What is Python? List some popular applications of Python in the world of


technology.

Pyt hon is a widely-used general-purpose, high-level programming language. It was creat ed by


Guido van Rossum in 1991 and furt her developed by t he Pyt hon Soft ware Foundat ion. It was
designed wit h an emphasis on code readabilit y, and it s synt ax allows programmers t o express
t heir concept s in fewer lines of code.
It is used for:

Syst em Script ing


Web Development
Game Development
Soft ware Development
Complex Mat hemat ics

2. What are the benefits of using Python language as a tool in the present
scenario?

The following are t he benefit s of using Pyt hon language:

Object -Orient ed Language


High-Level Language
Dynamically Typed language
Ext ensive support Libraries
Presence of t hird-part y modules
Open source and communit y development
Port able and Int eract ive
Port able across Operat ing syst ems

3. Is Python a compiled language or an interpreted language?

Open In App
Act ually, Pyt hon is a part ially compiled language and part ially int erpret ed language. The
compilat ion part is done first when we execut e our code and t his will generat e byt e code
int ernally t his byt e code get s convert ed by t he Pyt hon virt ual machine(p.v.m) according t o t he
underlying plat form(machine+operat ing syst em).

4. What does the ‘#’ symbol do in Python?

‘#’ is used t o comment on everyt hing t hat comes aft er on t he line.

5. What is the difference between a Mutable datatype and an Immutable data


type?

Mut able dat a t ypes can be edit ed i.e., t hey can change at runt ime. Eg – List , Dict ionary, et c.
Immut able dat a t ypes can not be edit ed i.e., t hey can not change at runt ime. Eg – St ring, Tuple,
et c.

6. How are arguments passed by value or by reference in Python?

Everyt hing in Pyt hon is an object and all variables hold references t o t he object s. The reference
values are according t o t he funct ions; as a result , you cannot change t he value of t he references.
However, you can change t he object s if it is mut able.

7. What is the difference between a Set and Dictionary?

The set is an unordered collect ion of dat a t ypes t hat is it erable, mut able and has no duplicat e
element s.
A dict ionary in Pyt hon is an ordered collect ion of dat a values, used t o st ore dat a values like a
map.

8. What is List Comprehension? Give an Example.

List comprehension is a synt ax const ruct ion t o ease t he creat ion of a list based on exist ing
it erable.

For Example:

my_list = [i for i in range(1, 10)]

9. What is a lambda function?

Open In App
A lambda funct ion is an anonymous funct ion. This funct ion can have any number of paramet ers
but , can have just one st at ement . For Example:

a = lambda x, y : x*y

print(a(7, 19))

10. What is a pass in Python?

Pass means performing no operat ion or in ot her words, it is a placeholder in t he compound


st at ement , where t here should be a blank left and not hing has t o be writ t en t here.

11. What is the difference between / and // in Python?

/ represent s precise division (result is a float ing point number) whereas // represent s floor division
(result is an int eger). For Example:

5//2 = 2

5/2 = 2.5

12. How is Exceptional handling done in Python?

There are 3 main keywords i.e. t ry, except , and finally which are used t o cat ch except ions and
handle t he recovering mechanism accordingly. Try is t he block of a code t hat is monit ored for
errors. Except block get s execut ed when an error occurs.

The beaut y of t he final block is t o execut e t he code aft er t rying for an error. This block get s
execut ed irrespect ive of whet her an error occurred or not . Finally, block is used t o do t he required
cleanup act ivit ies of object s/variables.

13. What is swapcase function in Python?

It is a st ring’s funct ion t hat convert s all uppercase charact ers int o lowercase and vice versa. It is
used t o alt er t he exist ing case of t he st ring. This met hod creat es a copy of t he st ring which
cont ains all t he charact ers in t he swap case. For Example:

string = "GeeksforGeeks"

string.swapcase() ---> "gEEKSFORgEEKS"

Open In App
14. Difference between for loop and while loop in Python

The “for” Loop is generally used t o it erat e t hrough t he element s of various collect ion t ypes such
as List , Tuple, Set , and Dict ionary. Developers use a “for” loop where t hey have bot h t he
condit ions st art and t he end. Whereas, t he “while” loop is t he act ual looping feat ure t hat is used
in any ot her programming language. Programmers use a Pyt hon while loop where t hey just have
t he end condit ions.

15. Can we Pass a function as an argument in Python?

Yes, Several argument s can be passed t o a funct ion, including object s, variables (of t he same or
dist inct dat a t ypes), and funct ions. Funct ions can be passed as paramet ers t o ot her funct ions
because t hey are object s. Higher-order funct ions are funct ions t hat can t ake ot her funct ions as
argument s.

To read more, refer t o t he art icle: Passing funct ion as an argument in Pyt hon

16. What are *args and *kwargs?

To pass a variable number of argument s t o a funct ion in Pyt hon, use t he special synt ax *args and
**kwargs in t he funct ion specificat ion. It is used t o pass a variable-lengt h, keyword-free
argument list . By using t he *, t he variable we associat e wit h t he * becomes it erable, allowing you
t o do operat ions on it such as it erat ing over it and using higher-order operat ions like map and
filt er.

17. Is Indentation Required in Python?

Yes, indent at ion is required in Pyt hon. A Pyt hon int erpret er can be informed t hat a group of
st at ement s belongs t o a specific block of code by using Pyt hon indent at ion. Indent at ions make
t he code easy t o read for developers in all programming languages but in Pyt hon, it is very
import ant t o indent t he code in a specific order.

18. What is Scope in Python?

The locat ion where we can find a variable and also access it if required is called t he scope of a
variable.

Python Local variable: Local variables are t hose t hat are init ialized wit hin a funct ion and are
unique t o t hat funct ion. It cannot be accessed out side of t he funct ion.
Python Global variables: Global variables are t he ones t hat are defined and declared out side
any funct ion and are not specified t o anyOpen
functIn App
ion.
Module-level scope: It refers t o t he global object s of t he current module accessible in t he
program.
Outermost scope: It refers t o any built -in names t hat t he program can call. The name
referenced is locat ed last among t he object s in t his scope.

19. What is docstring in Python?

Pyt hon document at ion st rings (or docst rings) provide a convenient way of associat ing
document at ion wit h Pyt hon modules, funct ions, classes, and met hods.

Declaring Docstrings: The docst rings are declared using ”’t riple single quot es”’ or “””t riple
double quot es””” just below t he class, met hod, or funct ion declarat ion. All funct ions should
have a docst ring.
Accessing Docstrings: The docst rings can be accessed using t he _ _ doc_ _ met hod of t he
object or using t he help funct ion.

20. What is a dynamically typed language?

Typed languages are t he languages in which we define t he t ype of dat a t ype and it will be known
by t he machine at t he compile-t ime or at runt ime. Typed languages can be classified int o t wo
cat egories:

Statically typed languages: In t his t ype of language, t he dat a t ype of a variable is known at
t he compile t ime which means t he programmer has t o specify t he dat a t ype of a variable at
t he t ime of it s declarat ion.
Dynamically typed languages: These are t he languages t hat do not require any pre-defined
dat a t ype for any variable as it is int erpret ed at runt ime by t he machine it self. In t hese
languages, int erpret ers assign t he dat a t ype t o a variable at runt ime depending on it s value.

21. What is a break, continue, and pass in Python?

The break st at ement is used t o t erminat e t he loop or st at ement in which it is present . Aft er t hat ,
t he cont rol will pass t o t he st at ement s t hat are present aft er t he break st at ement , if available.

Cont inue is also a loop cont rol st at ement just like t he break st at ement . cont inue st at ement is
opposit e t o t hat of t he break st at ement , inst ead of t erminat ing t he loop, it forces t o execut e
t he next it erat ion of t he loop.

Pass means performing no operat ion or in ot her words, it is a placeholder in t he compound


st at ement , where t here should be a blank left and not hing has t o be writ t en t here.
Open In App
22. What are Built-in data types in Python?

The following are t he st andard or built -in dat a t ypes in Pyt hon:

Numeric: The numeric dat a t ype in Pyt hon represent s t he dat a t hat has a numeric value. A
numeric value can be an int eger, a float ing number, a Boolean, or even a complex number.
Sequence Type: T he sequence Dat a Type in Pyt hon is t he ordered collect ion of similar or
different dat a t ypes. There are several sequence t ypes in Pyt hon:
Pyt hon St ring
Pyt hon List
Pyt hon Tuple
Pyt hon range

Mapping Types: In Pyt hon, hashable dat a can be mapped t o random object s using a mapping
object . There is current ly only one common mapping t ype, t he dict ionary, and mapping object s
are mut able.
Pyt hon Dict ionary

Set Types: In Pyt hon, a Set is an unordered collect ion of dat a t ypes t hat is it erable, mut able,
and has no duplicat e element s. The order of element s in a set is undefined t hough it may
consist of various element s.

23. How do you floor a number in Python?

The Pyt hon mat h module includes a met hod t hat can be used t o calculat e t he floor of a number.

floor() met hod in Pyt hon ret urns t he floor of x i.e., t he largest int eger not great er t han x.
Also, The met hod ceil(x) in Pyt hon ret urns a ceiling value of x i.e., t he smallest int eger great er
t han or equal t o x.

Intermediate Python Interview Questions

24. What is the difference between xrange and range functions?

range() and xrange() are t wo funct ions t hat could be used t o it erat e a cert ain number of t imes in
for loops in Pyt hon. In Pyt hon 3, t here is no xrange, but t he range funct ion behaves like xrange in
Pyt hon 2.

range() – This ret urns a list of numbers creat ed using t he range() funct ion.
xrange() – This funct ion ret urns t he generat or object t hat can be used t o display numbers only
by looping. The only part icular range is displayed
Open In on demand and hence called lazy evaluation.
App
25. What is Dictionary Comprehension? Give an Example

Dict ionary Comprehension is a synt ax const ruct ion t o ease t he creat ion of a dict ionary based on
t he exist ing it erable.

For Example: my_dict = {i:1+7 for i in range(1, 10)}

26. Is Tuple Comprehension? If yes, how, and if not why?

(i for i in (1, 2, 3))

Tuple comprehension is not possible in Pyt hon because it will end up in a generat or, not a t uple
comprehension.

27. Differentiate between List and Tuple?

Let ’s analyze t he differences bet ween List and Tuple:

List

List s are Mut able dat at ype.


List s consume more memory
The list is bet t er for performing operat ions, such as insert ion and delet ion.
The implicat ion of it erat ions is Time-consuming

Tuple

Tuples are Immut able dat at ype.


Tuple consumes less memory as compared t o t he list
A Tuple dat a t ype is appropriat e for accessing t he element s
The implicat ion of it erat ions is comparat ively Fast er

28. What is the difference between a shallow copy and a deep copy?

Shallow copy is used when a new inst ance t ype get s creat ed and it keeps values t hat are copied
whereas deep copy st ores values t hat are already copied.

A shallow copy has fast er program execut ion whereas a deep coy makes it slow.
Open In App
29. Which sorting technique is used by sort() and sorted() functions of
python?

Pyt hon uses t he Tim Sor t algorit hm for sort ing. It ’s a st able sort ing whose worst case is O(N log
N). It ’s a hybrid sort ing algorit hm, derived from merge sort and insert ion sort , designed t o perform
well on many kinds of real-world dat a.

30. What are Decorators?

Decorat ors are a very powerful and useful t ool in Pyt hon as t hey are t he specific change t hat we
make in Pyt hon synt ax t o alt er funct ions easily.

31. How do you debug a Python program?

By using t his command we can debug a Pyt hon program:

$ python -m pdb python-script.py

32. What are Iterators in Python?

In Pyt hon, it erat ors are used t o it erat e a group of element s, cont ainers like a list . It erat ors are
collect ions of it ems, and t hey can be a list , t uples, or a dict ionary. Pyt hon it erat or implement s
_ _ it r_ _ and t he next () met hod t o it erat e t he st ored element s. We generally use loops t o it erat e
over t he collect ions (list , t uple) in Pyt hon.

33. What are Generators in Python?

In Pyt hon, t he generat or is a way t hat specifies how t o implement it erat ors. It is a normal
funct ion except t hat it yields expression in t he funct ion. It does not implement _ _ it r_ _ and
next () met hod and reduces ot her overheads as well.

If a funct ion cont ains at least a yield st at ement , it becomes a generat or. The yield keyword
pauses t he current execut ion by saving it s st at es and t hen resumes from t he same when
required.

34. Does Python supports multiple Inheritance?

Pyt hon does support mult iple inherit ances, unlike Java. Mult iple inherit ances mean t hat a class
can be derived from more t han one parent class.

35. What is Polymorphism in Python?


Open In App
Polymorphism means t he abilit y t o t ake mult iple forms. So, for inst ance, if t he parent class has a
met hod named ABC t hen t he child class also can have a met hod wit h t he same name ABC having
it s own paramet ers and variables. Pyt hon allows polymorphism.

36. Define encapsulation in Python?

Encapsulat ion means binding t he code and t he dat a t oget her. A Pyt hon class is an example of
encapsulat ion.

37. How do you do data abstraction in Python?

Dat a Abst ract ion is providing only t he required det ails and hides t he implement at ion from t he
world. It can be achieved in Pyt hon by using int erfaces and abst ract classes.

38. How is memory management done in Python?

Pyt hon uses it s privat e heap space t o manage t he memory. Basically, all t he object s and dat a
st ruct ures are st ored in t he privat e heap space. Even t he programmer can not access t his privat e
space as t he int erpret er t akes care of t his space. Pyt hon also has an inbuilt garbage collect or,
which recycles all t he unused memory and frees t he memory and makes it available t o t he heap
space.

39. How to delete a file using Python?

We can delet e a file using Pyt hon by following approaches:

os.remove()
os.unlink()

40. What is slicing in Python?

Pyt hon Slicing is a st ring operat ion for ext ract ing a part of t he st ring, or some part of a list . Wit h
t his operat or, one can specify where t o st art t he slicing, where t o end, and specify t he st ep. List
slicing ret urns a new list from t he exist ing list .

Syntax: Lst[ Initial : End : IndexJump ]

41. What is a namespace in Python?

A namespace is a naming syst em used t o make sure t hat names are unique t o avoid naming
conflict s.
Open In App
Advanced Python Interview Questions & Answers

42. What is PIP?

PIP is an acronym for Pyt hon Inst aller Package which provides a seamless int erface t o inst all
various Pyt hon modules. It is a command-line t ool t hat can search for packages over t he int ernet
and inst all t hem wit hout any user int eract ion.

43. What is a zip function?

Pyt hon zip() funct ion ret urns a zip object , which maps a similar index of mult iple cont ainers. It
t akes an it erable, convert s it int o an it erat or and aggregat es t he element s based on it erables
passed. It ret urns an it erat or of t uples.

44. What are Pickling and Unpickling?

The Pickle module accept s any Pyt hon object and convert s it int o a st ring represent at ion and
dumps it int o a file by using t he dump funct ion, t his process is called pickling. While t he process
of ret rieving original Pyt hon object s from t he st ored st ring represent at ion is called unpickling.

45. What is monkey patching in Python?

In Pyt hon, t he t erm monkey pat ch only refers t o dynamic modificat ions of a class or module at
run-t ime.

# g.py

class GeeksClass:

def function(self):

print "function()"

import m

def monkey_function(self):

print "monkey_function()"

m.GeeksClass.function = monkey_function

obj = m.GeeksClass()

obj.function()

46. What is _ _ init_ _ () in Python?


Open In App
Equivalent t o const ruct ors in OOP t erminology, _ _ init _ _ is a reserved met hod in Pyt hon classes.
The _ _ init _ _ met hod is called aut omat ically whenever a new object is init iat ed. This met hod
allocat es memory t o t he new object as soon as it is creat ed. This met hod can also be used t o
init ialize variables.

47. Write a code to display the current time?

currenttime= time.localtime(time.time())

print (“Current time is”, currenttime)

48. What are Access Specifiers in Python?

Pyt hon uses t he ‘_ ’ symbol t o det ermine t he access cont rol for a specific dat a member or a
member funct ion of a class. A Class in Pyt hon has t hree t ypes of Pyt hon access modifiers:

Public Access Modifier: The members of a class t hat are declared public are easily
accessible from any part of t he program. All dat a members and member funct ions of a class
are public by default .
Protected Access Modifier: The members of a class t hat are declared prot ect ed are only
accessible t o a class derived from it . All dat a members of a class are declared prot ect ed by
adding a single underscore ‘_ ’ symbol before t he dat a members of t hat class.
Private Access Modifier: The members of a class t hat are declared privat e are accessible
wit hin t he class only, t he privat e access modifier is t he most secure access modifier. Dat a
members of a class are declared privat e by adding a double underscore ‘_ _ ’ symbol before t he
dat a member of t hat class.

49. What are unit tests in Python?

Unit Test ing is t he first level of soft ware t est ing where t he smallest t est able part s of t he
soft ware are t est ed. This is used t o validat e t hat each unit of t he soft ware performs as
designed. The unit t est framework is Pyt hon’s xUnit st yle framework. The Whit e Box Test ing
met hod is used for Unit t est ing.

50. Python Global Interpreter Lock (GIL)?

Pyt hon Global Int erpret er Lock (GIL) is a t ype of process lock t hat is used by Pyt hon whenever it
deals wit h processes. Generally, Pyt hon only uses only one t hread t o execut e t he set of writ t en
st at ement s. The performance of t he single-t hreaded process and t he mult i-t hreaded process
will be t he same in Pyt hon and t his is because of GIL in Pyt hon. We can not achieve
Open In App
mult it hreading in Pyt hon because we have a global int erpret er lock t hat rest rict s t he t hreads and
works as a single t hread.

51. What are Function Annotations in Python?

Funct ion Annot at ion is a feat ure t hat allows you t o add met adat a t o funct ion paramet ers and
ret urn values. This way you can specify t he input t ype of t he funct ion paramet ers and t he ret urn
t ype of t he value t he funct ion ret urns.

Funct ion annot at ions are arbit rary Pyt hon expressions t hat are associat ed wit h various part s of
funct ions. These expressions are evaluat ed at compile t ime and have no life in Pyt hon’s runt ime
environment . Pyt hon does not at t ach any meaning t o t hese annot at ions. They t ake life when
int erpret ed by t hird-part y libraries, for example, mypy.

52. What are Exception Groups in Python?

The lat est feat ure of Pyt hon 3.11, Except ion Groups. The Except ionGroup can be handled using a
new except * synt ax. The * symbol indicat es t hat mult iple except ions can be handled by each
except * clause.

Except ionGroup is a collect ion/group of different kinds of Except ion. Wit hout creat ing Mult iple
Except ions we can group t oget her different Except ions which we can lat er fet ch one by one
whenever necessary, t he order in which t he Except ions are st ored in t he Except ion Group doesn’t
mat t er while calling t hem.

Pyt hon3

try:
raise ExceptionGroup('Example ExceptionGroup', (
TypeError('Example TypeError'),
ValueError('Example ValueError'),
KeyError('Example KeyError'),
AttributeError('Example AttributeError')
))
except* TypeError:
...
except* ValueError as e:
...
except* (KeyError, AttributeError) as e:
...
Open In App
53. What is Python Switch Statement

From version 3.10 upward, Pyt hon has implement ed a swit ch case feat ure called “st ruct ural
pat t ern mat ching”. You can implement t his feat ure wit h t he mat ch and case keywords. Not e t hat
t he underscore symbol is what you use t o define a default case for t he swit ch st at ement in
Pyt hon.

Note : Before Pyt hon 3.10 Pyt hon doesn’t support mat ch St at ement s.

Pyt hon3

match term:
case pattern-1:
action-1
case pattern-2:
action-2
case pattern-3:
action-3
case _:
action-default

54. What is Walrus Operator?

The Walrus Operat or allows you t o assign a value t o a variable wit hin an expression. This can be
useful when you need t o use a value mult iple t imes in a loop, but don’t want t o repeat t he
calculat ion.

The Walrus Operat or is represent ed by t he `:=` synt ax and can be used in a variet y of cont ext s
including while loops and if st at ement s.

Note: Pyt hon versions before 3.8 doesn’t support Walrus Operat or.

Pyt hon3

names = ["Jacob", "Joe", "Jim"]

if (name := input("Enter a name: ")) in names:


print(f"Hello, {name}!")
else:
print("Name not found.")Open In App

You might also like