Python-Interview-Questions-and-Answers

Python Interview Questions and Answers

Last updated on 25th Sep 2020, Blog, Interview Question

About author

Shalini (Sr Technical Project Manager )

Delegates in Corresponding Technical Domain with 6+ Years of Experience. Also, She is a Technology Writer for Past 3 Years & Share's this Informative Blogs for us.

(5.0) | 11457 Ratings 598

In this Informative Python Series of Tutorials, Python’s main function was explained in detail in our last tutorial.

This Blog provides details on most frequently asked interview questions and answers on Python.

It covers most of the concepts, features and also has some questions directed towards the application of concepts and features. With this Q&A list, you would be able to prepare for any Python theoretical interview. 

Enlisted below are the most commonly asked interview questions and answers on Python programming language.

1. What is Python?

Ans:

Python is a high-level, interpreted, general-purpose programming language. Being a general-purpose language, it can be used to build almost any type of application with the right tools/libraries. Additionally, python supports objects, modules, threads, exception-handling and automatic memory management which help in modelling real-world problems and building applications to solve these problems.

2. What are the benefits of using Python?

Ans:

Python is a general-purpose programming language that has simple, easy-to-learn syntax which emphasizes readability and therefore reduces the cost of program maintenance. Moreover, the language is capable of scripting, completely open-source and supports third-party packages encouraging modularity and code-reuse.

Its high-level data structures, combined with dynamic typing and dynamic binding, attract a huge community of developers for Rapid Application Development and deployment.

3. What is a dynamically typed language?

Ans:

Before we understand what a dynamically typed language, we should learn about what typing is. Typing refers to type-checking in programming languages. In a strongly-typed  language, such as Python, “1” + 2 will result in a type error, since these languages don’t allow for “type-coercion” (implicit conversion of data types). On the other hand, a weakly-typed  language, such as Javascript, will simply output “12” as a result.

Type-checking can be done at two stages –

  • Static – Data Types are checked before execution.
  • Dynamic – Data Types are checked during execution.

Python being an interpreted language, executes each statement line by line and thus type-checking is done on the fly, during execution. Hence, Python is a Dynamically Typed language.

4. What is an Interpreted language?

Ans:

An Interpreted language executes its statements line by line. Languages such as Python, Javascript, R, PHP and Ruby are prime examples of Interpreted languages. Programs written in an interpreted language runs directly from the source code, with no intermediary compilation step.

5. What is PEP 8 and why is it important?

Ans:

PEP stands for Python Enhancement Proposal. A PEP is an official design document providing information to the Python Community, or describing a new feature for Python or its processes. PEP 8 is especially important since it documents the style guidelines for Python Code. Apparently contributing in the Python open-source community requires you to follow these style guidelines sincerely and strictly.

6. How is memory managed in Python?

Ans:

Memory management in Python is handled by the Python Memory Manager. The memory allocated by the manager is in the form of a private heap space dedicated for Python. All Python objects are stored in this heap and being private, it is inaccessible to the programmer. Though, python does provide some core API functions to work upon the private heap space.

Additionally, Python has an in-built garbage collection to recycle the unused memory for the private heap space.

7. What are Python namespaces? Why are they used?

Ans:

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.
  • 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.

Lifecycle of a namespace depends upon the scope of objects they are mapped to. If the scope of an object ends, the lifecycle of that namespace comes to an end. Hence, it isn’t possible to access inner namespace objects from an outer namespace.

python_namespaces

8. What is Scope in Python?

Ans:

Every object in Python functions within a scope. A scope is a block of code where an object in Python remains relevant. Namespaces uniquely identify all the objects inside a program. However, these namespaces also have a scope defined for them where you could use their objects without any prefix. A few examples of scope created during code execution in Python are as follows:

  • A local scope refers to the local objects available in the current function.
  • A global scope refers to the objects available throughout the code execution since their inception.
  • A module-level scope refers to the global objects of the current module accessible in the program.
  • An outermost scope refers to all the built-in names callable in the program. The objects in this scope are searched last to find the name referenced.

Note: Local scope objects can be synced with global scope objects using keywords such as global.

9. What is Scope Resolution in Python?

Ans:

Sometimes objects within the same scope have the same name but function differently. In such cases, scope resolution comes into play in Python automatically. A few examples of such behaviour are:

  • Python modules namely ‘math’ and ‘cmath’ have a lot of functions that are common to both of them – log10(), acos(), exp() etc. To resolve this amiguity, it is necessary to prefix them with their respective module, like math.exp() and cmath.exp().
  • Consider the code below, an object temp has been initialized to 10 globally and then to 20 on function call. However, the function call didn’t change the value of the temp globally. Here, we can observe that Python draws a clear line between global and local variables treating both their namespaces as separate identities.
  • temp = 10 # global-scope variable
  • def func():
  •       temp = 20   # local-scope variable
  •       print(temp)
  • print(temp) # output => 10
  • func() # output => 20
  • print(temp) # output => 10

This behaviour can be overridden using the global keyword inside the function, as shown in the following example:

  • temp = 10 # global-scope variable
  • def func():
  • global temp
  • temp = 20   # local-scope variable
  • print(temp)
  • print(temp)
  • # output => 10func()
  • # output => 20print(temp)
  • # output => 20

10. What are decorators in Python?

Ans:

Decorators in Python are essentially functions that add functionality to an existing function in Python without changing the structure of the function itself. They are represented by the @decorator_name in Python and are called in bottom-up fashion. For example:

# decorator function to convert to lowercase

  • def lowercase_decorator(function):
  • def wrapper():
  • func = function()
  • string_lowercase = func.lower()
  • return string_lowercase
  • return wrapper

# decorator function to split words

  • def splitter_decorator(function):
  • def wrapper():
  • func = function()
  • string_split = func.split()
  • return string_split
  • return wrapper

@splitter_decorator # this is executed next

@lowercase_decorator # this is executed first

  • def hello():
  • return ‘Hello World’
  • hello() # output => [ ‘hello’ , ‘world’ ]

The beauty of the decorators lies in the fact that besides adding functionality to the output of the method, they can even accept arguments for functions and can further modify those arguments before passing it to the function itself. The inner nested function, i.e. ‘wrapper’ function, plays a significant role here. It is implemented to enforce encapsulation and thus, keep itself hidden from the global scope.

# decorator function to capitalize names

  • def names_decorator(function):
  • def wrapper(arg1, arg2):
  • arg1 = arg1.capitalize()
  • arg2 = arg2.capitalize()
  • string_hello = function(arg1, arg2)
  • return string_hello
  • return wrapper
  • @names_decorator
  • def say_hello(name1, name2):
  • return ‘Hello ‘ + name1 + ‘ ! Hello ‘+ name2 + ‘! ‘
  • say_hello( ‘sara ‘, ‘ansh ‘) # output = ‘Hello Sara!Hello Ansh ‘ !
Subscribe For Free Demo
[contact-form-7 404 "Not Found"]

11. What are lists and tuples? What is the key difference between the two?

Ans:

Lists and Tuples are both sequence data types that can store a collection of objects in Python. The objects stored in both sequences can have different data types. Lists are represented with square brackets [‘sara’, 6, 0.19], while tuples are represented with parentheses (‘ansh’, 5, 0.97).

But what is the real difference between the two? The key difference between the two is that while lists are mutable, tuples on the other hand are immutable objects. This means that lists can be modified, appended or sliced on-the-go but tuples remain constant and cannot be modified in any manner. You can run the following example on Python IDLE to confirm the difference:

  • my_tuple = (‘sara’, 6, 5, 0.97)
  • my_list = [‘sara’, 6, 5, 0.97]
  • print(my_tuple[0])     # output => ‘sara’
  • print(my_list[0])     # output => ‘sara’
  • my_tuple[0] = ‘ansh’    # modifying tuple => throws an error
  • my_list[0] = ‘ansh’    # modifying list => list modified
  • print(my_tuple[0])     # output => ‘sara’
  • print(my_list[0])     # output => ‘ansh’

12. What are Dict and List comprehensions?

Ans:

Python comprehensions, like decorators, are syntactic sugar constructs that help build altered and filtered lists, dictionaries or sets from a given list, dictionary or set. Using comprehensions, saves a lot of time and code that might be considerably more verbose (containing more lines of code). Let’s check out some examples, where comprehensions can be truly beneficial:

  • Performing mathematical operations on the entire listmy_list = [2, 3, 5, 7, 11]
  • squared_list = [x**2 for x in my_list]    # list comprehension
  • # output => [4 , 9 , 25 , 49 , 121]
  • squared_dict = {x:x**2 for x in my_list}    # dict comprehension
  • # output => {11: 121, 2: 4 , 3: 9 , 5: 25 , 7: 49}
  • Performing conditional filtering operations on the entire listmy_list = [2, 3, 5, 7, 11]
  • squared_list = [x2 for x in my_list if x%2 != 0]    # list comprehension
  • # output => [9 , 25 , 49 , 121]
  • squared_dict = {x:x2 for x in my_list if x%2 != 0}    # dict comprehension
  • # output => {11: 121, 3: 9 , 5: 25 , 7: 49}

Combining multiple lists into one
Comprehensions allow for multiple iterators and hence, can be used to combine multiple lists into one

Flattening a multi-dimensional list
A similar approach of nested iterators (as above) can be applied to flatten a multi-dimensional list or work upon its inner elements.

  • my_list = [[10,20,30],[40,50,60],[70,80,90]]
  • flattened = [x for temp in my_list for x in temp]
  • # output => [10, 20, 30, 40, 50, 60, 70, 80, 90]

Note: List comprehensions have the same effect as the map method in other languages. They follow the mathematical set builder notation rather than map and filter functions in Python.

13. What are the common built-in data types in Python?

Ans:

There are several built-in data types in Python. Although, Python doesn’t require data types to be defined explicitly during variable declarations but type errors are likely to occur if the knowledge of data types and their compatibility with each other are neglected. Python provides type() and isinstance() functions to check the type of these variables. These data types can be grouped into the following categories-

  • None Type
    None keyword represents the null values in Python. Boolean equality operations can be performed using these NoneType objects.
  • Numeric Types
    There are three distinct numeric types – integers, floating-point numbers, and complex numbers. Additionally, booleans are a subtype of integers.

Note: The standard library also includes fractions to store rational numbers and decimal to store floating-point numbers with user-defined precision.

  • Sequence Types
    According to Python Docs, there are three basic Sequence Types – lists, tuples, and range objects. Sequence types have the in and not in operators defined for their traversing their elements. These operators share the same priority as the comparison operations.

Note: The standard library also includes additional types for processing:


1. Binary data such as bytearray bytes memoryview , and


2. Text strings such as str .


  • Mapping Types
    A mapping object can map hashtable values to random objects in Python. Mappings objects are mutable and there is currently only one standard mapping type, the dictionary.
  • Set Types
    Currently, Python has two built-in set types – set and frozenset. set type is mutable and supports methods like add() and remove(). frozenset type is immutable and can’t be modified after creation.

Note: set is mutable and thus cannot be used as a key for a dictionary. On the other hand, frozenset is immutable and thus, hashable, and can be used as a dictionary key or as an element of another set.

  • Modules
    Module is an additional built-in type supported by the Python Interpreter. It supports one special operation, i.e., attribute access: mymod.myobj, where mymod is a module and myobj references a name defined in m’s symbol table. The module’s symbol table resides in a very special attribute of the module __dict__, but direct assignment to this module is neither possible nor recommended.
  • Callable Types
    Callable types are the types to which function call can be applied. They can be user-defined functions, instance methods, generator functions, and some other built-in functions, methods and classes.
    Refer the documentation at docs.python.org for a detailed view into the callable types.

14. What is lambda in Python? Why is it used?

Ans:

Lambda is an anonymous function in Python, that can accept any number of arguments, but can only have a single expression. It is generally used in situations requiring an anonymous function for a short time period. Lambda functions can be used in either of the two ways:

  • Assigning lambda functions to a variablemul = lambda a, b : a * b
  • print(mul(2, 5))    # output => 10
  • Wrapping lambda functions inside another functiondef myWrapper(n):
  •   return lambda a : a * n
  • mulFive = myWrapper(5)
  • print(mulFive(2))    # output => 10

15. What is passed in Python?

Ans:

The pass keyword represents a null operation in Python. It is generally used for the purpose of filling up empty blocks of code which may execute during runtime but has yet to be written. Without the pass statement in the following code, we may run into some errors during code execution.

  • def myEmptyFunc():
  •     # do nothing
  •     pass
  • myEmptyFunc()    # nothing happens
  • ## Without the pass keyword
  • # File “<stdin>”, line 3
  • # IndentationError: expected an indented block

16. How do you copy an object in Python?

Ans:

In Python, the assignment statement (= operator) does not copy objects. Instead, it creates a binding between the existing object and the target variable name. To create copies of an object in Python, we need to use the copy module. Moreover, there are two ways of creating copies for the given object using the copy module –

  • Shallow Copy is a bitwise copy of an object. The copied object created has an exact copy of the values in the original object. If either of the values are references to other objects, just the reference addresses for the same are copied.
  • Deep Copy copies all values recursively from source to target object, i.e. it even duplicates the objects referenced by the source object.

from copy import copy, deepcopy

  • list_1 = [1, 2, [3, 5], 4]
  • ## shallow copy
  • list_2 = copy(list_1) 
  • list_2[3] = 7
  • list_2[2].append(6)
  • list_2    # output => [1, 2, [3, 5, 6], 7]
  • list_1    # output => [1, 2, [3, 5, 6], 4]
  • ## deep copy
  • list_3 = deepcopy(list_1)
  • list_3[3] = 8
  • list_3[2].append(7)
  • list_3    # output => [1, 2, [3, 5, 6, 7], 8]
  • list_1    # output => [1, 2, [3, 5, 6], 4]

17. What is the difference between xrange and range in Python?

Ans:

xrange() and range() are quite similar in terms of functionality. They both generate a sequence of integers, with the only difference that range() returns a Python list, whereas, xrange() returns an xrange object.

So how does that make a difference? It sure does, because unlike range(), xrange() doesn’t generate a static list, it creates the value on the go. This technique is commonly used with object type generators and has been termed as “yielding”.

Yielding is crucial in applications where memory is a constraint. Creating a static list as in range() can lead to a Memory Error in such conditions, while xrange() can handle it optimally by using just enough memory for the generator (significantly less in comparison).

  • for i in xrange(10):    # numbers from o to 9
  •     print i      
  • # output => 0 1 2 3 4 5 6 7 8 9
  • for i in xrange(1,10):    # numbers from 1 to 9
  •     print i    
  •   # output => 1 2 3 4 5 6 7 8 9
  • for i in xrange(1, 10, 2):    # skip by two for next
  •     print i    
  •   # output => 1 3 5 7 9

Note: xrange has been deprecated as of Python 3.x. Now range does exactly the same what xrange used to do in Python 2.x, since it was way better to use xrange() than the original range() function in Python 2.x.

18. What are modules and packages in Python?

Ans:

Python packages and Python modules are two mechanisms that allow for modular programming in Python. Modularizing has several advantages –

  • Simplicity: Working on a single module helps you focus on a relatively small portion of the problem at hand. This makes development easier and less error-prone.
  • Maintainability: Modules are designed to enforce logical boundaries between different problem domains. If they are written in a manner that reduces interdependency, it is less likely that modifications in a module might impact other parts of the program.
  • Reusability: Functions defined in a module can be easily reused by other parts of the application.
  • Scoping: Modules typically define a separate namespace, which helps avoid confusion between identifiers from other parts of the program.

Modules, in general, are simply Python files with a .py extension and can have a set of functions, classes or variables defined and implemented. They can be imported and initialized once using the import statement. If partial functionality is needed, import the requisite classes or functions using from foo import bar.

Packages allow for hierarchical structuring of the module namespace using dot notation. As modules help avoid clashes between global variable names, in a similar manner, packages help avoid clashes between module names.

Creating a package is easy since it makes use of the system’s inherent file structure. So just stuff the modules into a folder and there you have it, the folder name as the package name. Importing a module or its contents from this package requires the package name as prefix to the module name joined by a dot.

Note: You can technically import the package as well, but alas, it doesn’t import the modules within the package to the local namespace, thus, it is practically useless.

19. What are global, protected and private attributes in Python?

Ans:

  • Global variables are public variables that are defined in the global scope. To use the variable in the global scope inside a function, we use the global keyword.
  • Protected attributes are attributes defined with a underscore prefixed to their identifier eg. _sara. They can still be accessed and modified from outside the class they are defined in but a responsible developer should refrain from doing so.
  • Private attributes are attributes with double underscore prefixed to their identifier eg. __ansh. They cannot be accessed or modified from the outside directly and will result in an AttributeError if such an attempt is made.

20. What is self in Python?

Ans:

Self is a keyword in Python used to define an instance or an object of a class. In Python, it is explicitly used as the first parameter, unlike in Java where it is optional. It helps in distinguishing between the methods and attributes of a class from its local variables.

21. What is __init__?

Ans:

__init__ is a constructor method in Python and is automatically called to allocate memory when a new object/instance is created. All classes have a __init__ method associated with them. It helps in distinguishing methods and attributes of a class from local variables.

  • # class definition
  • class Student:
  •     def __init__(self, fname, lname, age, section):
  •         self.firstname = fname
  •         self.lastname = lname
  •         self.age = age
  •         self.section = section
  • # creating a new object
  • stu1 = Student(“Sara”, “Ansh”, 22, “A2”)

22. What is break, continue and pass in Python?

Ans:

BreakThe break statement terminates the loop immediatelyand the control flows to the statement after the body of the loop.
ContinueThe continue statement terminates the current iteration of the statement,skips the rest of the code in the current iteration and the control flows to the next iteration of the loop.
PassAs explained above, pass keyword in Python is generally used to fill-up empty blocksand is similar to an empty statement represented by a semi-colon in languages such as Java, C++, Javascript etc.
  • pat = [1, 3, 2, 1, 2, 3, 1, 0, 1, 3]
  • for p in pat:
  •     pass
  •     if (p == 0):
  •         current = p
  •         break
  •     elif (p % 2 == 0):
  •         continue
  •     print(p)    # output => 1 3 1 3 1
  • print(current)    # output => 0

23. What is pickling and unpickling?

Ans:

Python library offers a feature – serialization out of the box. Serializing an object refers to transforming it into a format that can be stored, so as to be able to deserialize it later on, to obtain the original object. Here, the pickle module comes into play.

Pickling

Pickling is the name of the serialization process in Python. Any object in Python can be serialized into a byte stream and dumped as a file in the memory. The process of pickling is compact but pickle objects can be compressed further. Moreover, pickle keeps track of the objects it has serialized and the serialization is portable across versions.

The function used for the above process is

  • pickle.dump().

Unpickling

Unpickling is the complete inverse of pickling. It deserializes the byte stream to recreate the objects stored in the file, and loads the object to memory.

The function used for the above process is

  • pickle.load().

Note: Python has another, more primitive, serialization module called marshall, which exists primarily to support .pyc files in Python and differs significantly from pickle.

24. What are generators in Python?

Ans:

Generators are functions that return an iterable collection of items, one at a time, in a set manner. Generators, in general, are used to create iterators with a different approach. They employ the use of yield keyword rather than return to return a generator object.

Let’s try and build a generator for fibonacci numbers –

  • ## generate fibonacci numbers upto n
  • def fib(n):
  •     p, q = 0, 1
  •     while(p < n):
  •         yield p
  •         p, q = q, p + q
  • x = fib(10)    # create generator object 
  • ## iterating using __next__(), for Python2, use next()
  • x.__next__()    # output => 0
  • x.__next__()    # output => 1
  • x.__next__()    # output => 1
  • x.__next__()    # output => 2
  • x.__next__()    # output => 3
  • x.__next__()    # output => 5
  • x.__next__()    # output => 8
  • x.__next__()    # error
  • ## iterating using loop
  • for i in fib(10):
  •     print(i)    # output => 0 1 1 2 3 5 8

25. What is PYTHONPATH in Python?

Ans:

PYTHONPATH is an environment variable which you can set to add additional directories where Python will look for modules and packages. This is especially useful in maintaining Python libraries that you do not wish to install in the global default location.

26. What is the use of help() and dir() functions?

Ans:

help() function in Python is used to display the documentation of modules, classes, functions, keywords, etc. If no parameter is passed to the help() function, then an interactive help utility is launched on the console.

dir() function tries to return a valid list of attributes and methods of the object it is called upon. It behaves differently with different objects, as it aims to produce the most relevant data, rather than the complete information.

  • For Modules/Library objects, it returns a list of all attributes, contained in that module.
  • For Class Objects, it returns a list of all valid attributes and base attributes.
  • With no arguments passed, it returns a list of attributes in the current scope.

27. What is the difference between .py and .pyc files?

Ans:

  • .py files contain the source code of a program. Whereas, .pyc file contains the bytecode of your program. We get bytecode after compilation of .py file (source code). .pyc files are not created for all the files that you run. It is only created for the files that you import.
  • Before executing a python program python interpreter checks for the compiled files. If the file is present, the virtual machine executes it. If not found, it checks for .py file. If found, compiles it to .pyc file and then python virtual machine executes it.
  • Having a .pyc file saves you the compilation time.

28. How is Python interpreted?

Ans:

  • Python as a language is not interpreted or compiled. Interpreted or compiled is the property of the implementation. Python is a bytecode(set of interpreter readable instructions) interpreted generally.
  • Source code is a file with .py extension.
  • Python compiles the source code to a set of instructions for a virtual machine. The Python interpreter is an implementation of that virtual machine. This intermediate format is called “bytecode”.
  • .py source code is first compiled to give .pyc which is bytecode. This bytecode can be then interpreted by official CPython, or JIT(Just in Time compiler) compiled by PyPy.

29. What are unit tests in Python?

Ans:

  • unittest is a unit testing framework of Python.
  • Unit testing means testing different components of software separately. Can you think why unit testing is important? Imagine a scenario, you are building software which uses three components namely A, B, and C. Now, suppose your software breaks at a point time. How will you find which component was responsible for breaking the software? Maybe it was component A that failed, which in turn failed component B, and this actually failed the software. There can be many such combinations.
  • This is why it is necessary to test each and every component properly so that we know which component might be highly responsible for the failure of the software.

30. What is docstring in Python?

Ans:

  • Documentation string or docstring is a multiline string used to document a specific code segment.
  • The docstring should describe what the function or method does.
Course Curriculum

Get On-Demand Python Training with Advanced Concepts By IT Experts

  • Instructor-led Sessions
  • Real-life Case Studies
  • Assignments
Explore Curriculum

31. What will the following code output?

Ans:

  • >>> word=’abcdefghij’
  • >>> word[:3]+word[3:]

The output is ‘abcdefghij’. The first slice gives us ‘abc’, the next gives us ‘defghij’.

32. How will you convert a list into a string?

Ans:

We will use the join() method for this.

  • >>> nums=[‘one’,’two’,’three’,’four’,’five’,’six’,’seven’]
  • >>> s=’ ‘.join(nums)
  • >>> s

‘one two three four five six seven’

33. How will you remove a duplicate element from a list?

Ans:

We can turn it into a set to do that.

  • >>> list=[1,2,1,3,4,2]
  • >>> set(list)
  • {1, 2, 3, 4}

34. Can you explain the life cycle of a thread?

Ans:

  • To create a thread, we create a class that we override the run method of the thread class. Then, we instantiate it.
  • A thread that we just created is in the new state. When we make a call to start() on it, it forwards the threads for scheduling. These are in the ready state.
  • When execution begins, the thread is in the running state.
  • Calls to methods like sleep() and join() make a thread wait. Such a thread is in the waiting/blocked state.
  • When a thread is done waiting or executing, other waiting threads are sent for scheduling.
  • A running thread that is done executing terminates and is in the dead state.

35. What is a dictionary in Python?

Ans:

A python dictionary is something I have never seen in other languages like C++ or Java programming. It holds key-value pairs.

  • >>> roots={25:5,16:4,9:3,4:2,1:1}
  • >>> type(roots)
  • <class ‘dict
  • >>> roots[9]
  • 3

A dictionary is mutable, and we can also use a comprehension to create it.

  • >>> roots={x**2? for x in range(5,0,-1)}
  • >>> roots
  • {25: 5, 16: 4, 9: 3, 4: 2, 1: 1}

36. Explain the //, %, and ** operators in Python.

Ans:

The // operator performs floor division. It will return the integer part of the result on division.

  • >>> 7//2
  • 3

Normal division would return 3.5 here.

Similarly, ** performs exponentiation. a**b returns the value of a raised to the power b.

  • >>> 2**10
  • 1024

Finally, % is for modulus. This gives us the value left after the highest achievable division.

  • >>> 13%7
  • 6
  • >>> 3.5%1.5
  • 0.5

37.What do you know about relational operators in Python?

Ans:

Relational operators compare values.

  • Less than (<) If the value on the left is lesser, it returns True.
  • >>> ‘hi'<‘Hi’
  • False
  • Greater than (>) If the value on the left is greater, it returns True.
  • >>> 1.1+2.2>3.3
  • True
  • This is because of the flawed floating-point arithmetic in Python, due to hardware dependencies.
  • Less than or equal to (<=) If the value on the left is lesser than or equal to, it returns True.
  • >>> 3.0<=3
  • True
  • Greater than or equal to (>=) If the value on the left is greater than or equal to, it returns True.
  • >>> True>=False
  • True
  • Equal to (==) If the two values are equal, it returns True.
  • >>> {1,3,2,2}=={1,2,3}
  • True
  • Not equal to (!=) If the two values are unequal, it returns True.
  • >>> True!=0.1
  • True
  • >>> False!=0.1
  • True

You will surely face a question from Python Operators. There are chances that question may be in an indirect way. Prepare yourself for it with the best guide – Python Operators

38. What are assignment operators in Python?

Ans:

We can combine all arithmetic operators with the assignment symbol.

  • >>> a=7
  • >>> a+=1
  • >>> a
  • 8
  • >>> a-=1
  • >>> a
  • 7
  • >>> a*=2
  • >>> a
  • 14
  • >>> a/=2
  • >>> a
  • 7.0
  • >>> a**=2
  • >>> a
  • 49.0
  • >>> a//=3
  • >>> a
  • 16.0
  • >>> a%=4
  • >>> a
  • 0.0

39. Explain logical operators in Python.

Ans:

We have three logical operators- and, or, not.

  • >>> False and True
  • False
  • >>> 7<7 or True
  • True
  • >>> not 2==2
  • False

40. What are membership operators?

Ans:

With the operators ‘in’ and ‘not in’, we can confirm if a value is a member in another.

  • >>> ‘me’ in ‘disappointment’
  • True
  • >>> ‘us’ not in ‘disappointment’
  • True

41. Explain identity operators in Python.

Ans:

The operators ‘is’ and ‘is not’ tell us if two values have the same identity.

  • >>> 10 is ’10’
  • False
  • >>> True is not False
  • True

42. Tell us about bitwise operators in Python.

Ans:

These operate on values bit by bit.

AND (&) This performs & on each bit pair.

  • >>> 0b110 & 0b010
  • 2

OR (|) This performs | on each bit pair.

  • >>> 3|2
  • 3

XOR (^) This performs an exclusive-OR operation on each bit pair.

  • >>> 3^2
  • 1

Binary One’s Complement (~) This returns the one’s complement of a value.

  • >>> ~2
  • -3

Binary Left-Shift (<<) This shifts the bits to the left by the specified amount.

  • >>> 1<<2
  • 4

Here, 001 was shifted to the left by two places to get 100, which is binary for 4.

Binary Right-Shift (>>)

  • >>> 4>>2
  • 1

43. What data types do Python support?

Ans:

Python provides us with five kinds of data types:

Numbers – Numbers used to hold numerical values.

  • >>> a=7.0
  • >>>

Strings – A string is a sequence of characters. We declare it using single or double quotes.

  • >>> title=”Ayushi’s Book”

Lists – A list is an ordered collection of values, and we declare it using square brackets.

  • >>> colors=[‘red’,’green’,’blue’]
  • >>> type(colors)
  • <class ‘list’>

Tuples – A tuple, like a list, is an ordered collection of values. The difference. However, is that a tuple is immutable. This means that we cannot change a value in it.

  • >>> name=(‘Ayushi’,’Sharma’)
  • >>> name[0]=’Avery’
  • Traceback (most recent call last):
  • File “<pyshell#129>”, line 1, in <module>
  • name[0]=’Avery’

TypeError: ‘tuple’ object does not support item assignment

Dictionary – A dictionary is a data structure that holds key-value pairs. We declare it using curly braces.

  • >>> squares={1:1,2:4,3:9,4:16,5:25}
  • >>> type(squares)
  • <class ‘dict’>
  • >>> type({})
  • <class ‘dict’>

We can also use a dictionary comprehension:

  • >>> squares={x:x**2 for x in range(1,6)}
  • >>> squares
  • {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

44. What is a docstring?

Ans:

A docstring is a documentation string that we use to explain what a construct does. We place it as the first thing under a function, class, or a method, to describe what it does. We declare a docstring using three sets of single or double-quotes.

  • >>> def sayhi():
  • “””
  • The function prints Hi
  • “””
  • print(“Hi”)
  • >>> sayhi()
  • Hi

To get a function’s docstring, we use its __doc__ attribute.

  • >>> sayhi.__doc__

‘\n\tThis function prints Hi\n\t’

A docstring, unlike a comment, is retained at runtime.

45. How would you convert a string into an int in Python?

Ans:

If a string contains only numeric characters, you can convert it into an integer using the int() function.

  • >>> int(‘227’)
  • 227
  • Let’s check the types:
  • >>> type(‘227’)
  • <class ‘str’>
  • >>> type(int(‘227’))
  • <class ‘int’>

46. How do you take input in Python?

Ans:

For taking input from the user, we have the function input(). In Python 2, we had another function raw_input().

The input() function takes, as an argument, the text to be displayed for the task:

  • >>> a=input(‘Enter a number’)

Enter a number7

But if you have paid attention, you know that it takes input in the form of a string.

  • >>> type(a)
  • <class ‘str’>
  • Multiplying this by 2 gives us this:
  • >>> a*=2
  • >>> a
  • ’77’

So, what if we need to work on an integer instead?

We use the int() function for this.

  • >>> a=int(input(‘Enter a number’))

Enter a number7

Now when we multiply it by 2, we get this:

  • >>> a*=2
  • >>> a
  • 14

47. What is a function?

Ans:

When we want to execute a sequence of statements, we can give it a name. Let’s define a function to take two numbers and return the greater number.

  • >>> def greater(a,b):
  • return a is a>b else b
  • >>> greater(3,3.5)
  • 3.5

48. What is recursion?

Ans:

When a function makes a call to itself, it is termed recursion. But then, in order for it to avoid forming an infinite loop, we must have a base condition.

Let’s take an example.

  • >>> def facto(n):
  • if n==1: return 1
  • return n*facto(n-1)
  • >>> facto(4)
  • 24

49. What does the function zip() do?

Ans:

One of the less common functions with beginners, zip() returns an iterator of tuples.

  • >>> list(zip([‘a’,’b’,’c’],[1,2,3]))
  • [(‘a’, 1), (‘b’, 2), (‘c’, 3)]

Here, it pairs items from the two lists and creates tuples with those. But it doesn’t have to be listed.

  • >>> list(zip((‘a’,’b’,’c’),(1,2,3)))
  • [(‘a’, 1), (‘b’, 2), (‘c’, 3)]

50. How do you calculate the length of a string?

Ans:

This is simple. We call the function len() on the string we want to calculate the length of.

  • >>> len(‘Ayushi Sharma’)
  • 13
Course Curriculum

Learn Python Certification Course & Become a Certified Python Expert

Weekday / Weekend BatchesSee Batch Details

51. Explain Python List Comprehension.

Ans:

The list comprehension in python is a way to declare a list in one line of code. Let’s take a look at one such example.

  • >>> [i for i in range(1,11,2)]
  • [1, 3, 5, 7, 9]
  • >>> [i*2 for i in range(1,11,2)]
  • [2, 6, 10, 14, 18]

52. How do you get all values from a Python dictionary?

Ans:

We saw previously, to get all keys from a dictionary, we make a call to the keys() method. Similarly, for values, we use the method values().

  • >>> ‘d’ in {‘a’:1,’b’:2,’c’:3,’d’:4}.values()
  • False
  • >>> 4 in {‘a’:1,’b’:2,’c’:3,’d’:4}.values()
  • True

53. What if you want to toggle the case for a Python string?

Ans:

We have the swapcase() method from the str class to do just that.

  • >>> ‘AyuShi’.swapcase()
  • ‘aYUsHI’

Let’s apply some concepts now, shall we? Questions 50 through 52 assume the string ‘I love Python’. You need to do the needful.

54. Write code to print only upto the letter t.

Ans:

  • >>> i=0
  • >>> while s[i]!=’t’:
  • print(s[i],end=’’)
  • i+=1
  • I love Py

55. Write code to print everything in the string except the spaces.

Ans:

  • >>> for i in s:
  • if i==’ ‘: continue
  • print(i,end=”)
  • IlovePython

56. Now, print this string five times in a row.

Ans:

  • >>> for i in range(6):
  • print(s)
  • I love Python
  • I love Python
  • I love Python
  • I love Python
  • I love Python
  • I love Python

57. What is the purpose of bytes() in Python?

Ans:

bytes() is a built-in function in Python that returns an immutable bytes object. Let’s take an example.

  • >>> bytes([2,4,8])
  • b’\x02\x04\x08′
  • >>> bytes(5)
  • b’\x00\x00\x00\x00\x00′
  • >>> bytes(‘world’,’utf-8′)
  • b’world’

58. What is a control flow statement?

Ans:

A Python program usually starts to execute from the first line. From there, it moves through each statement just once and as soon as it’s done with the last statement, it transactions the program. However, sometimes, we may want to take a more twisted path through the code. Control flow statements let us disturb the normal execution flow of a program and bend it to our will.

59. Create a new list to convert the following list of number strings to a list of numbers.

Ans:

nums=[‘22’,’68’,’110’,’89’,’31’,’12’]

We will use the int() function with a list comprehension to convert these strings into integers and put them in a list.

  • >>> [int(i) for i in nums]
  • [22, 68, 110, 89, 31, 12]

60. Given the first and last names of all employees in your firm, what data type will you use to store it?

Ans:

I can use a dictionary to store that. It would be something like this-

  • {‘first_name’:’Ayushi’,’second_name’:’Sharma’

61.  How would you work with numbers other than those in the decimal number system?

Ans:

With Python, it is possible to type numbers in binary, octal, and hexadecimal.

Binary numbers are made of 0 and 1. To type in binary, we use the prefix 0b or 0B.

  • >>> int(0b1010)
  • 10

To convert a number into its binary form, we use bin().

  • >>> bin(0xf)
  • ‘0b1111’

Octal numbers may have digits from 0 to 7. We use the prefix 0o or 0O.

  • >>> oct(8)
  • ‘0o10’

Hexadecimal numbers may have digits from 0 to 15. We use the prefix 0x or 0X.

  • >>> hex(16)
  • ‘0x10’
  • >>> hex(15)
  • ‘0xf’

DataFlair’s latest article on Python Numbers with Examples

62. How many arguments can the range() function take?

Ans:

The range() function in Python can take up to 3 arguments. Let’s see this one by one.

a. One argument

When we pass only one argument, it takes it as the stop value. Here, the start value is 0, and the step value is +1.

  • >>> list(range(5))
  • [0, 1, 2, 3, 4]
  • >>> list(range(-5))
  • []
  • >>> list(range(0))
  • []

b. Two arguments

When we pass two arguments, the first one is the start value, and the second is the stop value.

  • >>> list(range(2,7))
  • [2, 3, 4, 5, 6]
  • >>> list(range(7,2))
  • []
  • >>> list(range(-3,4))
  • [-3, -2, -1, 0, 1, 2, 3]

c. Three arguments

Here, the first argument is the start value, the second is the stop value, and the third is the step value.

  • >>> list(range(2,9,2))
  • [2, 4, 6, 8]
  • >>> list(range(9,2,-1))
  • [9, 8, 7, 6, 5, 4, 3]

63. How is Python different from Java?

Ans:

Following is the comparison of Python vs Java –

  • Java is faster than Python
  • Python mandates indentation. Java needs braces.
  • Python is dynamically-typed; Java is statically typed.
  • Python is simple and concise; Java is verbose
  • Python is interpreted
  • Java is platform-independent
  • Java has stronger database-access with JDBC

64.What is Inheritance in Python programming?

Ans:

The composition is also a type of inheritance in Python. It intends to inherit from the base class but a little differently, i.e., by using an instance variable of the base class acting as a member of the derived class.

See the below diagram.

To demonstrate composition, we need to instantiate other objects in the class and then make use of those instances.

  • class PC: # Base class
  •     processor = “Xeon” # Common attribute
  •     def __init__(self, processor, ram):
  •         self.processor = processor
  •         self.ram = ram
  •     def set_processor(self, new_processor):
  •         processor = new_processor
  •     def get_PC(self):
  •         return “%s cpu & %s ram” % (self.processor, self.ram)
  • class Tablet():
  •     make = “Intel”
  •     def __init__(self, processor, ram, make):
  •         self.PC = PC(processor, ram) # Composition
  •         self.make = make
  •     def get_Tablet(self):
  •         return “Tablet with %s CPU & %s ram by %s” % (self.PC.processor, self.PC.ram, self.make)
  • if __name__ == “__main__”:
  •     tab = Tablet(“i7”, “16 GB”, “Intel”)
  •     print(tab.get_Tablet())

The output is:

Tablet with i7 CPU & 16 GB ram by Intel

65. What are Errors and Exceptions in Python programs?

Ans:

Errors are coding issues in a program which may cause it to exit abnormally.

On the contrary, exceptions happen due to the occurrence of an external event which interrupts the normal flow of the program.

66.How do you handle exceptions with Try/Except/Finally in Python?

Ans:

Python lay down Try, Except, Finally constructs to handle errors as well as Exceptions. We enclose the unsafe code indented under the try block. And we can keep our fall-back code inside the except block. Any instructions intended for execution last should come under the finally block.

try:

  •     print(“Executing code in the try block”)
  •     print(exception)

except:

  •     print(“Entering in the except block”)

finally:

  •     print(“Reached to the final block”)

The output is:

Executing code in the try block

Entering in the except block

Reached to the final block

67. How do you raise exceptions for a predefined condition in Python?

Ans:

We can raise an exception based on some condition.

For example, if we want the user to enter only odd numbers, else will raise an exception.

  • # Example – Raise an exception
  • while True:
  •     try:
  •         value = int(input(“Enter an odd number- “))
  •         if value%2 == 0:
  •             raise ValueError(“Exited due to invalid input!!!”)
  •         else:
  •             print(“Value entered is : %s” % value)
  •     except ValueError as ex:
  •         print(ex)
  •         break

The output is:

Enter an odd number- 2

Exited due to invalid input!!!

Enter an odd number- 1

Value entered is : 1

Enter an odd number-

68. What are Python Iterators?

Ans:

Iterators in Python are array-like objects which allow moving on the next element. We use them in traversing a loop, for example, in a “for” loop.

Python library has a no. of iterators. For example, a list is also an iterator and we can start a for loop over it.

69. What is the difference between an Iterator and Iterable?

Ans:

The collection type like a list, tuple, dictionary, and set are all iterable objects whereas they are also iterable containers which return an iterator while traversing.

70.What are Python Generators?

Ans:

A Generator is a kind of function which lets us specify a function that acts like an iterator and hence can get used in a “for” loop.

In a generator function, the yield keyword substitutes the return statement.

# Simple Python function

  • def fn():
  •     return “Simple Python function.”
  • # Python Generator function
  • def generate():
  •     yield “Python Generator function.”
  • print(next(generate()))

The output is:

Python Generator function.

Python Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

71. What are Closures in Python?

Ans:

Python closures are function objects returned by another function. We use them to eliminate code redundancy.

In the example below, we’ve written a simple closure for multiplying numbers.

  • def multiply_number(num):
  •     def product(number):
  •         ‘product() here is a closure’
  •         return num * number
  •     return product
  • num_2 = multiply_number(2)
  • print(num_2(11))
  • print(num_2(24))
  • num_6 = multiply_number(6)
  • print(num_6(1))

The output is:

22

48

6

72. How do you create a dictionary in Python?

Ans:

Let’s take the example of building site statistics. For this, we first need to break up the key-value pairs using a colon(“:”). The keys should be of an immutable type, i.e., so we’ll use the data-types which don’t allow changes at runtime. We’ll choose from an int, string, or tuple.

However, we can take values of any kind. For distinguishing the data pairs, we can use a comma(“,”) and keep the whole stuff inside curly braces({…}).

  • >>> site_stats = {‘site’: ‘tecbeamers.com’, ‘traffic’: 10000, “type”: “organic”}
  • >>> type(site_stats)
  • <class ‘dict’>
  • >>> print(site_stats)
  • {‘type’: ‘organic’, ‘site’: ‘tecbeamers.com’, ‘traffic’: 10000}

73. How do you read from a dictionary in Python?

Ans:

To fetch data from a dictionary, we can directly access it using the keys. We can enclose a “key” using brackets […] after mentioning the variable name corresponding to the dictionary.

  • >>> site_stats = {‘site’: ‘tecbeamers.com’, ‘traffic’: 10000, “type”: “organic”}
  • >>> print(site_stats[“traffic”])

We can even call the get method to fetch the values from a dict. It also let us set a default value. If the key is missing, then the KeyError would occur.

  • >>> site_stats = {‘site’: ‘tecbeamers.com’, ‘traffic’: 10000, “type”: “organic”}
  • >>> print(site_stats.get(‘site’))
  • tecbeamers.com

74.How do you traverse through a dictionary object in Python?

Ans:

We can use the “for” and “in” loop for traversing the dictionary object.

  • >>> site_stats = {‘site’: ‘tecbeamers.com’, ‘traffic’: 10000, “type”: “organic”}
  • >>> for k, v in site_stats.items():
  •     print(“The key is: %s” % k)
  •     print(“The value is: %s” % v)
  •     print(“++++++++++++++++++++++++”)

The output is:

The key is: type

The value is: organic

++++++++++++++++++++++++

The key is: site

The value is: tecbeamers.com

++++++++++++++++++++++++

The key is: traffic

The value is: 10000

++++++++++++++++++++++++

75. How do you add elements to a dictionary in Python?

Ans:

We can add elements by modifying the dictionary with a fresh key and then set the value to it.

  • >>> # Setup a blank dictionary
  • >>> site_stats = {}
  • >>> site_stats[‘site’] = ‘google.com’
  • >>> site_stats[‘traffic’] = 10000000000
  • >>> site_stats[‘type’] = ‘Referral’
  • >>> print(site_stats)
  • {‘type’: ‘Referral’, ‘site’: ‘google.com’, ‘traffic’: 10000000000}

We can even join two dictionaries to get a bigger dictionary with the help of the update() method.

  • >>> site_stats[‘site’] = ‘google.co.in’
  • >>> print(site_stats)
  • {‘site’: ‘google.co.in’}
  • >>> site_stats_new = {‘traffic’: 1000000, “type”: “social media”}
  • >>> site_stats.update(site_stats_new)
  • >>> print(site_stats)
  • {‘type’: ‘social media’, ‘site’: ‘google.co.in’, ‘traffic’: 1000000}

76.How do you delete elements of a dictionary in Python?

Ans:

We can delete a key in a dictionary by using the del() method.

  • >>> site_stats = {‘site’: ‘tecbeamers.com’, ‘traffic’: 10000, “type”: “organic”}
  • >>> del site_stats[“type”]
  • >>> print(site_stats)
  • {‘site’: ‘google.co.in’, ‘traffic’: 1000000}

Another method, we can use is the pop() function. It accepts the key as the parameter. Also, a second parameter, we can pass a default value if the key doesn’t exist.

  • >>> site_stats = {‘site’: ‘tecbeamers.com’, ‘traffic’: 10000, “type”: “organic”}
  • >>> print(site_stats.pop(“type”, None))
  • organic
  • >>> print(site_stats)
  • {‘site’: ‘tecbeamers.com’, ‘traffic’: 10000}

77.How do you check the presence of a key in a dictionary?

Ans:

We can use the Python “in” operator to test the presence of a key inside a dict object.

  • >>> site_stats = {‘site’: ‘tecbeamers.com’, ‘traffic’: 10000, “type”: “organic”}
  • >>> ‘site’ in site_stats
  • True
  • >>> ‘traffic’ in site_stats
  • True
  • >>> “type” in site_stats
  • True

Earlier, Python also provided the has_key() method which got deprecated.

78.What is the syntax for List comprehension in Python?

Ans:

The signature for the list comprehension is as follows:

[ expression(var) for var in iterable ]

For example, the below code will return all the numbers from 10 to 20 and store them in a list.

  • >>> alist = [var for var in range(10, 20)]
  • >>> print(alist)

79.What is the syntax for Dictionary comprehension in Python?

Ans:

A dictionary has the same syntax as was for the list comprehension but the difference is that it uses curly braces:

{ aKey, itsValue for aKey in iterable }

For example, the below code will return all the numbers 10 to 20 as the keys and will store the respective squares of those numbers as the values.

  • >>> adict = {var:var**2 for var in range(10, 20)}
  • >>> print(adict)

80.What is the syntax for Generator expression in Python?

Ans:

The syntax for generator expression matches with the list comprehension, but the difference is that it uses parenthesis:

( expression(var) for var in iterable )

For example, the below code will create a generator object that generates the values from 10 to 20 upon using it.

  • >>> (var for var in range(10, 20))
  •  at 0x0000000003668728>
  • >>> list((var for var in range(10, 20)))

81. How do you write a conditional expression in Python?

Ans:

We can utilize the following single statement as a conditional expression. default_statment if Condition else another_statement

  • >>> no_of_days = 366
  • >>> is_leap_year = “Yes” if no_of_days == 366 else “No”
  • >>> print(is_leap_year)
  • Yes

82. What do you know about the Python enumerate?

Ans:

While using the iterators, sometimes we might have a use case to store the count of iterations. Python gets this task quite easy for us by giving a built-in method known as the enumerate().

The enumerate() function attaches a counter variable to an iterable and returns it as the “enumerated” object.

We can use this object directly in the “for” loops or transform it into a list of tuples by calling the list() method. It has the following signature:

enumerate(iterable, to_begin=0)

Arguments:

iterable: array type object which enables iteration

to_begin: the base index for the counter is to get started, its default value is 0

  • # Example – enumerate function 
  • alist = [“apple”,”mango”, “orange”] 
  • astr = “banana”
  • # Let’s set the enumerate objects 
  • list_obj = enumerate(alist) 
  • str_obj = enumerate(astr) 
  • print(“list_obj type:”, type(list_obj))
  • print(“str_obj type:”, type(str_obj))
  • print(list(enumerate(alist)) )  
  • # Move the starting index to two from zero
  • print(list(enumerate(astr, 2)))

The output is:

list_obj type: <class ‘enumerate’>

str_obj type: <class ‘enumerate’>

[(0, ‘apple’), (1, ‘mango’), (2, ‘orange’)]

[(2, ‘b’), (3, ‘a’), (4, ‘n’), (5, ‘a’), (6, ‘n’), (7, ‘a’)]

83. What is the use of globals() function in Python?

Ans:

The globals() function in Python returns the current global symbol table as a dictionary object.

Python maintains a symbol table to keep all necessary information about a program. This info includes the names of variables, methods, and classes used by the program.

All the information in this table remains in the global scope of the program and Python allows us to retrieve it using the globals() method.

Signature: globals()

Arguments: None

  • # Example: globals() function 
  • x = 9
  • def fn(): 
  •     y = 3
  •     z = y + x
  •     # Calling the globals() method
  •     z = globals()[‘x’] = z
  •     return z
  • # Test Code     
  • ret = fn() 
  • print(ret)

The output is:

12

84. Why do you use the zip() method in Python?

Ans:

The zip method lets us map the corresponding index of multiple containers so that we can use them as a single unit.

Signature: 

 zip(*iterators)

Arguments: 

 Python iterables or collections (e.g., list, string, etc.)

Returns: 

 A single iterator object with combined mapped values

  • # Example: zip() function
  • emp = [ “tom”, “john”, “jerry”, “jake” ] 
  • age = [ 32, 28, 33, 44 ] 
  • dept = [ ‘HR’, ‘Accounts’, ‘R&D’, ‘IT’ ] 
  • # call zip() to map values 
  • out = zip(emp, age, dept)
  • # convert all values for printing them as set 
  • out = set(out) 
  • # Displaying the final values  
  • print (“The output of zip() is : “,end=””) 
  • print (out)

The output is:

The output of zip() is : {(‘jerry’, 33, ‘R&D’), (‘jake’, 44, ‘IT’), (‘john’, 28, ‘Accounts’), (‘tom’, 32, ‘HR’)}

85. What are Class or Static Variables in Python programming?

Ans:

In Python, all the objects share common class or static variables.

But the instance or non-static variables are altogether different for different objects.

The programming languages like C++ and Java need to use the static keyword to make a variable as the class variable. However, Python has a unique way to declare a static variable.

All names initialized with a value in the class declaration becomes the class variables. And those which get assigned values in the class methods become the instance variables.

# Example 

  • class Test: 
  •     aclass = ‘programming’ # A class variable 
  •     def __init__(self, ainst): 
  •         self.ainst = ainst # An instance variable 
  • # Objects of CSStudent class 
  • test1 = Test(1) 
  • test2 = Test(2) 
  • print(test1.aclass)
  • print(test2.aclass)
  • print(test1.ainst)
  • print(test2.ainst)
  • # A class variable is also accessible using the class name
  • print(Test.aclass)

The output is:

programming

programming

1

2

programming

Let’s now answer some advanced-level Python interview questions.

86. How does the ternary operator work in Python?

Ans:

The ternary operator is an alternative for the conditional statements. It combines true or false values with a statement that you need to test.

The syntax would look like the one given below.

  • [onTrue] if [Condition] else [onFalse]
  • x, y = 35, 75
  • smaller = x if x < y else y
  • print(smaller)

87. What does the “self” keyword do?

Ans:

The self is a Python keyword which represents a variable that holds the instance of an object.

In almost, all the object-oriented languages, it is passed to the methods as a hidden parameter.

88.What are the different methods to copy an object in Python?

Ans:

There are two ways to copy objects in Python.

  • copy.copy() function
    • It makes a copy of the file from source to destination.
    • It’ll return a shallow copy of the parameter.
  • copy.deepcopy() function
    • It also produces the copy of an object from the source to destination.
    • It’ll return a deep copy of the parameter that you can pass to the function.

89.What is the purpose of docstrings in Python?

Ans:

In Python, the docstring is what we call as the docstrings. It sets a process of recording Python functions, modules, and classes.

90.Which Python function will you use to convert a number to a string?

Ans:

For converting a number into a string, you can use the built-in function str().  If you want an octal or hexadecimal representation, use the inbuilt function oct() or hex().

91. How do you debug a program in Python? Is it possible to step through the Python code?

Ans:

Yes, we can use the Python debugger (pdb) to debug any Python program. And if we start a program using pdb, then it lets us even step through the code.

92.List down some of the PDB commands for debugging Python programs?

Ans:

Here are a few PDB commands to start debugging Python code.

  • Add breakpoint (b)
  • Resume execution (c)
  • Step by step debugging (s)
  • Move to the next line (n)
  • List source code (l)
  • Print an expression (p)

93.What is the command to debug a Python program?

Ans:

The following command helps run a Python program in debug mode.

  • $ python -m pdb python-script.py

94.How do you monitor the code flow of a program in Python?

Ans:

In Python, we can use the sys module’s settrace() method to setup trace hooks and monitor the functions inside a program.

You need to define a trace callback method and pass it to the settrace() function. The callback should specify three arguments as shown below.

  • import sys
  • def trace_calls(frame, event, arg):
  •     # The ‘call’ event occurs before a function gets executed.
  •     if event != ‘call’:
  •         return
  •     # Next, inspect the frame data and print information.
  •     print ‘Function name=%s, line num=%s’ % (frame.f_code.co_name, frame.f_lineno)
  •     return
  • def demo2():
  •     print ‘in demo2()’
  • def demo1():
  •     print ‘in demo1()’
  •     demo2()
  • sys.settrace(trace_calls)
  • demo1()

95.Why and when do you use generators in Python?

Ans:

A generator in Python is a function which returns an iterable object. We can iterate on the generator object using the yield keyword. But we can only do that once because their values don’t persist in memory, they get the values on the fly.

Generators give us the ability to hold the execution of a function or a step as long as we want to keep it. However, here are a few examples where it is beneficial to use generators.

  • We can replace loops with generators for efficiently calculating results involving large data sets.
  • Generators are useful when we don’t want all the results and wish to hold back for some time.
  • Instead of using a callback function, we can replace it with a generator. We can write a loop inside the function doing the same thing as the callback and turn it into a generator.

96.What does the yield keyword do in Python?

Ans:

The yield keyword can turn any function into a generator. It works like a standard return keyword. But it’ll always return a generator object. Also, a method can have multiple calls to the yield keyword.

See the example below.

  • def testgen(index):
  •   weekdays = [‘sun’,’mon’,’tue’,’wed’,’thu’,’fri’,’sat’]
  •   yield weekdays[index]
  •   yield weekdays[index+1]
  • day = testgen(0)
  • print next(day), next(day)

#output: sun mon

97. How to convert a list into other data types?

Ans:

Sometimes, we don’t use lists as is. Instead, we have to convert them to other types.

Turn a list into a string.

We can use the ”.join() method which combines all elements into one and returns as a string.

  • weekdays = [‘sun’,’mon’,’tue’,’wed’,’thu’,’fri’,’sat’]
  • listAsString = ‘ ‘.join(weekdays)
  • print(listAsString)
  • #output: sun mon tue wed thu fri sat

Turn a list into a tuple.

Call Python’s tuple() function for converting a list into a tuple.

This function takes the list as its argument.

But remember, we can’t change the list after turning it into a tuple because it becomes immutable.

  • weekdays = [‘sun’,’mon’,’tue’,’wed’,’thu’,’fri’,’sat’]
  • listAsTuple = tuple(weekdays)
  • print(listAsTuple)
  • #output: (‘sun’, ‘mon’, ‘tue’, ‘wed’, ‘thu’, ‘fri’, ‘sat’)

Turn a list into a set.

Converting a list to a set poses two side-effects.

  • Set doesn’t allow duplicate entries so that the conversion will remove any such item.
  • A set is an ordered collection, so the order of list items would also change.

However, we can use the set() function to convert a list into a Set.

  • weekdays = [‘sun’,’mon’,’tue’,’wed’,’thu’,’fri’,’sat’,’sun’,’tue’]
  • listAsSet = set(weekdays)
  • print(listAsSet)
  • #output: set([‘wed’, ‘sun’, ‘thu’, ‘tue’, ‘mon’, ‘fri’, ‘sat’])

Turn a list into a dictionary.

In a dictionary, each item represents a key-value pair. So converting a list isn’t as straightforward as it were for other data types.

However, we can achieve the conversion by breaking the list into a set of pairs and then call the zip() function to return them as tuples.

Passing the tuples into the dict() function would finally turn them into a dictionary.

  • weekdays = [‘sun’,’mon’,’tue’,’wed’,’thu’,’fri’]
  • listAsDict = dict(zip(weekdays[0::2], weekdays[1::2]))
  • print(listAsDict)
  • #output: {‘sun’: ‘mon’, ‘thu’: ‘fri’, ‘tue’: ‘wed’}

98. How do you count the occurrences of each item present in the list without explicitly mentioning them?

Ans:

Unlike sets, lists can have items with the same values.

In Python, the list has a count() function which returns the occurrences of a particular item.

Count the occurrences of an individual item.

  • weekdays = [‘sun’,’mon’,’tue’,’wed’,’thu’,’fri’,’sun’,’mon’,’mon’]
  • print(weekdays.count(‘mon’))
  • #output: 3

Count the occurrences of each item in the list.

We’ll use the list comprehension along with the count() method. It’ll print the frequency of each of the items.

  • weekdays = [‘sun’,’mon’,’tue’,’wed’,’thu’,’fri’,’sun’,’mon’,’mon’]
  • print([[x,weekdays.count(x)] for x in set(weekdays)])
  • #output: [[‘wed’, 1], [‘sun’, 2], [‘thu’, 1], [‘tue’, 1], [‘mon’, 3], [‘fri’, 1]]

99.What is NumPy and how is it better than a list in Python?

Ans:

NumPy is a Python package for scientific computing which can deal with large data sizes. It includes a powerful N-dimensional array object and a set of advanced functions.

Also, the NumPy arrays are superior to the built-in lists. There are a no. of reasons for this.

  • NumPy arrays are more compact than lists.
  • Reading and writing items is faster with NumPy.
  • Using NumPy is more convenient than to the standard list.
  • NumPy arrays are more efficient as they augment the functionality of lists in Python.

100.What are different ways to create an empty NumPy array in Python?

Ans:

There are two methods which we can apply to create empty NumPy arrays.

The first method to create an empty array.

  • import numpy
  • numpy.array([])

The second method to create an empty array.

  • # Make an empty NumPy array
  • numpy.empty(shape=(0,0))

Inheritance is an OOP mechanism which allows an object to access its parent class features. It carries forward the base class functionality to the child.

We do it intentionally to abstract away the similar code in different classes.

The common code rests with the base class, and the child class objects can access it via inheritance. Check out the below example.

  • class PC: # Base class
  •     processor = “Xeon” # Common attribute
  •     def set_processor(self, new_processor):
  •         processor = new_processor
  • class Desktop(PC): # Derived class
  •     os = “Mac OS High Sierra” # Personalized attribute
  •     ram = “32 GB”
  • class Laptop(PC): # Derived class
  •     os = “Windows 10 Pro 64” # Personalized attribute
  •     ram = “16 GB”
  • desk = Desktop()
  • print(desk.processor, desk.os, desk.ram)
  • lap = Laptop()
  • print(lap.processor, lap.os, lap.ram)
  • The output:
  • Xeon Mac OS High Sierra 32 GB
  • Xeon Windows 10 Pro 64 16 GB

Are you looking training with Right Jobs?

Contact Us

Popular Courses