Python Interview Questions and Answers

This Article has been Published first on:

Python developer interview questions and answers

Python Interview Questions and Answers for Beginners

1) How do I run a Python script?

A) Run a Python script under Windows with the Command Prompt. Note that you must use the full path of the Python interpreter. If you want to simply type python.exe C:\Users\Username\Desktop\ you must add python.exe to your PATH environmental variable.

2) What is the directory in Python?

A) A directory or folder is a collection of files and sub directories. Python has the os module, which provides us with many useful methods to work with directories (and files as well).

Python Interview Questions and Answers for Intermediates

3) What is the use of dir() function?

A) After assigning values to a few variables, we could use the dir() function to show their existence. In the following example, variables p, av, and d are shown among other names.

[‘p’, ‘av’, ‘d’]

4) How can you unsign or delete variable in Python?

A) Whenever we write code for any application, it might be a good practice to delete those variables that we no longer need. In this case, we could use the del() function to remove or unsign a variable.

click here to know more: How to become a python developer

Python Interview Questions and Answers for Experienced

5) What are the types of inheritance in Python?

A) Python supports different types of inheritance, they are:

  • Single Inheritance
  • Multi-level Inheritance
  • Hierarchical Inheritance
  • Multiple Inheritance

6) What is MRO in Python?

(A) In multiple inheritance, the order in which base classes are searched when looking for a method is often called the Method Resolution Order (MRO).

7) What is super () in Python?

A) Super() is used to return a proxy object that delegates method calls to a parent or sibling class of type.

8) What is overriding in Python?

A) In Python, Overriding is the ability of a class to change the implementation of a method provided by one of its ancestors. Overriding is a very important part of OOP since it is the feature that makes inheritance exploit its full power.

9) What is an abstract class in Python?

A) An abstract method is a method that is declared, but contains no implementation. Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods. Subclasses of an abstract class in Python are not required to implement abstract methods of the parent class.

10) Is multiple inheritances possible in python?

A) Multiple inheritance on the other hand is a feature in which a class can inherit attributes and methods from more than one parent class. Python has a sophisticated and well-designed approach to multiple inheritance.

11) What is a decorator in Python?

A) Decorators provide a simple syntax for calling higher-order functions. By definition, a decorator is a function that takes another function and extends the behavior of the latter function without explicitly modifying it.

Top Python interview questions and answers for experienced

1. Explain the output of the following piece of code-

  1. x=[‘ab’,’cd’]
  2. print(len(map(list,x)))

This actually gives us an error- a TypeError. This is because map() has no len() attribute in their dir().

2. So what is the output of the following piece of code?

  1. x=[‘ab’,’cd’]
  2. print(len(list(map(list,x))))

This outputs 2 because the length of this list is 2. list(map(list,x)) is [[‘a’, ‘b’], [‘c’, ‘d’]], and the length of this is 2.

3.Explain the output of the following piece of code-

  1. >>> tuple=(123,’John’)
  2. >>> tuple*=2
  3. >>> tuple

(123, ‘John’, 123, ‘John’)

In this code, we multiply the tuple by 2. This duplicates its contents, hence, giving us (123, ‘John’, 123, ‘John’). We can also do this to strings:

  1. >>> ‘ba’+’na’*2


4. What does the map() function do?

map() executes the function we pass to it as the first argument; it does so on all elements of the iterable in the second argument. Let’s take an example, shall we?

  1. >>> for i in map(lambda i:i**3, (2,3,7)):
  2. print(i)


This gives us the cubes of the values 2, 3, and 7.

5. What does the following code give us?

  1. >>> b=(1)

Not a tuple. This gives us a plain integer.

  1. >>> type(b)

<class ‘int’>

To let it be a tuple, we can declare so explicitly with a comma after 1:

  1. >>> b=(1,)
  2. >>> type(b)

<class ‘tuple’>

Register here: Python course

Python interview questions and answers for 2 years experience

1) What is self in Python?

A) The first argument of every class method, including init, is always a reference to the current instance of the class. By convention, this argument is always named self. In the init method, self-refers to the newly created object; in other class methods, it refers to the instance whose method was called.

2) How many coding styles are there in Python?

A) There are four main Python coding styles: imperative, functional, object-oriented, and procedural.

interview questions and answers for 5 years experience

3. What is the result of the following Python program?

Ans. The example code is as follows.

def multiplexers ():

return [lambda n: index * n for index in range (4)]

print [m (2) for m in multiplexers ()]

Python 2.7.10 (default, Jul 14 2015, 19:46:27)

[GCC 4.8.2] on linux

[6, 6, 6, 6]

The output of the above code is <[6, 6, 6, 6]>. It’s because of the late binding as the value of the variable <index> gets looked up after a call to any of multiplexers functions.

4. What is the result of the below Python code?

keyword = ‘aeioubcdfg’

print keyword [:3] + keyword [3:]

Ans. The above code will produce the following result.


In Python, while performing string slicing, whenever the indices of both the slices collide, a <+> operator get applied to concatenates them.

Python interview questions and answers for testers

1) What is pickling and unpickling?

Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using dump function, this process is called pickling. While the process of retrieving original Python objects from the stored string representation is called unpickling.

2) How Python is interpreted?

Python language is an interpreted language. Python program runs directly from the source code. It converts the source code that is written by the programmer into an intermediate language, which is again translated into machine language that has to be executed.

3) How memory is managed in Python?

  • Python memory is managed by Python private heap space. All Python objects and data structures are located in a private heap. The programmer does not have an access to this private heap and interpreter takes care of this Python private heap.
  • The allocation of Python heap space for Python objects is done by Python memory manager. The core API gives access to some tools for the programmer to code.
  • Python also have an inbuilt garbage collector, which recycle all the unused memory and frees the memory and makes it available to the heap space.

4) What are the tools that help to find bugs or perform static analysis?

PyChecker is a static analysis tool that detects the bugs in Python source code and warns about the style and complexity of the bug. Pylint is another tool that verifies whether the module meets the coding standard.

5) What are Python decorators?

A Python decorator is a specific change that we make in Python syntax to alter functions easily.

6) What is the difference between list and tuple?

The difference between list and tuple is that list is mutable while tuple is not. Tuple can be hashed for e.g as a key for dictionaries.

Python coding interview questions and answers

1) What is NumPy array?

A) NumPy arrays are more flexible then lists in Python. By using NumPy arrays reading and writing items is faster and more efficient.

2) How can you create Empty NumPy Array In Python?

A) We can create Empty NumPy Array in two ways in Python,

1) import numpy

2) numpy.empty(shape=(0,0))

3) What is a negative index in Python?

A) Python has a special feature like a negative index in Arrays and Lists. Positive index reads the elements from the starting of an array or list but in the negative index, Python reads elements from the end of an array or list.

4) What is the output of the below code?

>> import array
>>> a = [1, 2, 3]
>>> print a[-3]
>>> print a[-2]
>>> print a[-1]

A) The output is: 3, 2, 1

5. How would you define a block in Python?

For any kind of statements, we possibly need to define a block of code under them. However, Python does not support curly braces. This means we must end such statements with colons and then indent the blocks under those with the same amount.

  1. >>> if 3>1:
  2. print(“Hello”)
  3. print(“Goodbye”)



Python coding questions

1) How to print sum of the numbers starting from 1 to 100?

A) We can print sum of the numbers starting from 1 to 100 using this code:

print sum(range(1,101))

# In Python the range function does not include the end given. Here it will exclude 101.

# Sum function print sum of the elements of range function, i.e 1 to 100.

2) How do you set a global variable inside a function?

A) Yes, we can use a global variable in other functions by declaring it as global in each function that assigns to it:

globvar = 0
def set_globvar_to_one():
global globvar # Needed to modify global copy of globvar
globvar = 1
def print_globvar():
print globvar # No need for global declaration to read value of globvar
print_globvar() # Prints 1

3) What is the output of the program?

names1 = [‘Amir’, ‘Bear’, ‘Charlton’, ‘Daman’]
names2 = names1
names3 = names1[:]

names2[0] = ‘Alice’
names3[1] = ‘Bob’

sum = 0
for ls in (names1, names2, names3):
if ls[0] == ‘Alice’:
sum += 1
if ls[1] == ‘Bob’:
sum += 10

print sum

A) 12

4) What is the output, Suppose list1 is [1, 3, 2], What is list1 * 2?

A) [1, 3, 2, 1, 3, 2]

10) What is the output when we execute list(“hello”)?

A) [‘h’, ‘e’, ‘l’, ‘l’, ‘o’]

Cracking python interview questions on programming

cracking python interview questions on programming

1) What should be the typical build environment for Python-based application development?

Answer: You just need to install Python software and using PIP, you can install various Python modules from the open-source community.

For IDE, Pycharm is highly recommended for any kind of application development with vast support for plugins. Another basic IDE is called a RIDE and is a part of the Python open-source community.

2) What tools can be used to unit test your Python code?

Answer: The best and easiest way is to use ‘unittest’ python standard library is to test units/classes. The features supported are very similar to the other unit testing tools such as JUnit, TestNG.

3) How does For Loop and While Loop differ in Python and when do you choose to use them?

Answer: For Loop is generally used to iterate through the elements of various collection types such as List, Tuple, Set, and Dictionary.

While loop is the actual looping feature that is used in any other programming language. This is how Python differs in handling loops from the other programming languages.

4) How are data types defined in Python and how much bytes do integer and decimal data types hold?

Answer: In Python, there is no need to define a variable’s data type explicitly.

Based on the value assigned to a variable, Python stores the appropriate data type. In the case of numbers such as Integer, Float, etc, the length of data is unlimited.

5) How do you make use of Arrays in Python?

Answer: Python does not support Arrays. However, you can use List collection type which can store an unlimited number of elements.

6) How do you implement JSON given that Python is best suited for the server-side application?

Answer: Python has built-in support to handle JSON objects.

You just have to import the JSON module and use the functions such as loads and dumps to convert from JSON string to JSON object and vice versa. It is a straightforward way to handle and exchange JSON based data from the server-side.

python interview questions for data science

1. Name some well-known Python data analysis libraries.

If you’re doing data analysis with Python, you’re likely going to use:

  • NumPy
  • Pandas
  • Matplotlib
  • Seaborn
  • SciKit

These libraries will help you work with arrays and DataFrames, build professional-looking plots, and run machine learning models.

2. What is pandas?

Pandas is a Python open-source library that provides high-performance and flexible data structures and data analysis tools that make working with relational or labeled data both easy and intuitive.

3. Write Python code to create an employees DataFrame from the “HR.csv” file.

We can create a DataFrame from a CSV file by using the read_csv() function from the pandas library. By convention, pandas is imported as pd. So the code is simply the following:

import pandas as pd

emloyees = pd.read_csv(‘HR.csv’)

4. What libraries do data scientists use to plot data in Python?

Matplotlib is the main library used for plotting data in Python. However, the plots created with this library need lots of fine-tuning to look shiny and professional. For that reason, many data scientists prefer Seaborn, which allows you to create appealing and meaningful plots with only one line of code.

4. What Python IDEs are the most popular in data science?

Granted, you won’t be asked this exact question, but it’s likely that your prospective employer will still want to get a better sense of how you work with Python and what exposure you have to the language.

In that case, it’s good to know that Jupyter Notebook, PyCharm, and Spyder are all good Python IDEs, but Jupyter Notebook is arguably the best for data science.

Python interview questions and answers for mcq

  1. Which of the following lines of code will result in an error?

A. s={abs}

B. s={4, ‘abc’, (1,2)}

C. s={2, 2.2, 3, ‘xyz’}

D. s={san}

Answer: Option D


The line: s={san} will result in an error because ‘san’ is not defined. The line s={abs} does not result in an error because abs is a built-in function. The other sets shown do not result in an error because all the items are hashable.

  1. Suppose t=(1,2,4,3), which of the following is incorrect?

A. print(t[3])

B. t[3] = 45

C. print(max(t))

D. print(len(t))

Answer: Option B


Values cannot be modified in the case of tuple, that is, tuple is immutable.

2. What is the output of the following?


A. True

B. False

C. None

D. Error

Answer: Option A


The string has only letters.

3. What is the output of the following?

print(‘abcd’.translate({‘a’: ‘1’, ‘b’: ‘2’, ‘c’: ‘3’, ‘d’: ‘4’}))

A. abcd

B. 1234

C. error

D. none of the mentioned

Answer: Option A


The function translate expects a dictionary of integers. Use maketrans() instead of doing the above.

3. What is the output of the following?

print(‘xyyxyyxyxyxxy’.replace(‘xy’, ‘12’, 100))

A. xyyxyyxyxyxxy

B. 12y12y1212x12

C. none of the mentioned

D. error

Answer: Option B


The first 100 occurences of the given substring are replaced.

Technical Python Interview Questions and Answers

1.What is the with statement in Python?

The with statement in Python ensures that cleanup code is executed when working with unmanaged resources by encapsulating common preparation and cleanup tasks. It may be used to open a file, do something, and then automatically close the file at the end. It may be used to open a database connection, do some processing, then automatically close the connection to ensure resources are closed and available for others. with will cleanup the resources even if an exception is thrown. This statement is like the using statement in C#.
Consider you put some code in a try block, then in the finally block, you close any resources used. The with statement is like syntactic sugar for that.

The syntax of this control-flow structure is:

with expression [as variable]:

  1. >>> with open(‘data.txt’) as data:
  2. #processing statements
  3. How is a .pyc file different from a .py file?

While both files hold bytecode, .pyc is the compiled version of a Python file. It has platform-independent bytecode. Hence, we can execute it on any platform that supports the .pyc format. Python automatically generates it to improve performance(in terms of load time, not speed).

Python OOPS Interview Questions and Answers

You might be strong with object oriented programming language. Here are set of python object oriented programming language questions to hone your skills

1) What makes Python object-oriented?

Again the frequently asked Python Interview Question

Python is object-oriented because it follows the Object-Oriented programming paradigm. This is a paradigm that revolves around classes and their instances (objects). With this kind of programming, we have the following features:

  • Encapsulation
  • Abstraction
  • Inheritance
  • Polymorphism
  • Data hiding

2) How many types of objects does Python support?

Objects in Python are mutable and immutable. Let’s talk about these.

Immutable objects- Those which do not let us modify their contents. Examples of these will be tuples, booleans, strings, integers, floats, and complexes. Iterations on such objects are faster.

  1. >>> tuple=(1,2,4)
  2. >>> tuple

(1, 2, 4)

  1. >>> 2+4j


Mutable objects — Those that let you modify their contents. Examples of these are lists, sets, and dicts. Iterations on such objects are slower.

  1. >>> [2,4,9]

[2, 4, 9]

  1. >>> dict1={1:1,2:2}

2.>>> dict1

{1: 1, 2: 2}

While two equal immutable objects’ reference variables share the same address, it is possible to create two mutable objects with the same content.

Top Python Interview Questions and Answers

1. Whenever Python exits, all the memory isn’t deallocated. Why is it so?

Answer: Upon exiting, Python’s built-in effective cleanup mechanism comes into play and try to deallocate or destroy every other object.

However, Python modules that are having circular references to other objects or the objects that are referenced from the global namespaces aren’t always deallocated or destroyed.

This is because it is not possible to deallocate those portions of the memory that are reserved by the C library.

2. Explain memory managed in Python?

Answer: Python private heap space takes place of memory management in Python. It contains all Python objects and data structures. The interpreter is responsible to take care of this private heap and the programmer does not have access to it. The Python memory manager is responsible for the allocation of Python heap space for Python objects. The programmer may access some tools for the code with the help of the core API. Python also provides an inbuilt garbage collector, which recycles all the unused memory and frees the memory and makes it available to heap space.

3. What are Python decorators?

Answer: A specific change made in Python syntax to alter the functions easily are termed as Python decorators.

4. Differentiate between list and tuple.

Answer: Tuple is not mutable it can be hashed eg. key for dictionaries. On the other hand, lists are mutable.

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

Answer: All of the Python is an object and all variables hold references to the object. The reference values are according to the functions; as a result, the value of the reference cannot be changed.

6. What are Python modules?

Answer: A file containing Python code like functions and variables is a Python module. A Python module is an executable file with a .py extension.

Python has built-in modules some of which are:

  • os
  • sys
  • math
  • random
  • data time
  • JSON

7. What is the // operator? What is its use?

Answer: The // is a Floor Divisionoperator used for dividing two operands with the result as quotient displaying digits before the decimal point. For instance, 10//5 = 2 and 10.0//5.0 = 2.0.

8. What is the split function used for?

Answer: The split function breaks the string into shorter strings using the defined separator. It returns the list of all the words present in the string.

9. Explain the Dogpile effect.

Answer: The event when the cache expires and websites are hit by multiple requests made by the client at the same time. Using a semaphore lock prevents the Dogpile effect. In this system when value expires, the first process acquires the lock and starts generating new value.

10. What is a pass in Python?

Answer: No-operation Python statement refers to pass. It is a place holder in the compound statement, where there should have a blank left or nothing written there.

11. Is Python a case sensitive language?

Answer: Yes Python is a case sensitive language.

12. Define slicing in Python.

Answer: Slicing refers to the mechanism to select the range of items from sequence types like lists, tuples, strings.

13. What are docstring?

Answer: Docstring is a Python documentation string, it is a way of documenting Python functions, classes and modules.

14. What is, not and in operators?

Answer: Operators are functions that take two or more values and returns the corresponding result.

  • is: returns true when two operands are true
  • not: returns inverse of a boolean value
  • in: checks if some element is present in some sequence.

15. How are files deleted in Python?

Answer: To delete a file in Python:

  1. Import OS module
  2. Use os.remove() function

Python interview question pdf

1. When is not a good time to use python generators?

Ans: Use list instead of generator when:
1 You need to access the data multiple times (i.e. cache the results instead of
recomputing them)
2 You need random access (or any access other than forward sequential order):
3 You need to join strings (which requires two passes over the data)
4 You are using PyPy which sometimes can’t optimise generator code as much
as it can with normal function calls and list manipulations.

2. When should you use generator expressions vs. list comprehensions in Python and vice-versa?

Ans: Iterating over the generator expression or the list comprehension will do the same
thing. However, the list comp will create the entire list in memory first while the
generator expression will create the items on the fly, so you are able to use it for very
large (and also infinite!) sequences.

3. How can I find methods or attributes of an object in Python?

Ans: Builtin dir() function of Python ,on an instance shows the instance variables as
well as the methods and class attributes defined by the instance’s class and all its base
classes alphabetically. So by any object as argument to dir() we can find all the
methods & attributes of the object’s class..

4. How do I get a list of all files (and directories) in a given directory in Python?

Ans: Following is one possible solution there can be other similar ones:
import os
for dirname,dirnames,filenames in os.walk(‘.’):

5. How to convert a string to lowercase in Python?

Ans: use lower() function.

6. What is GIL? What does it do?Talk to me about the GIL. How does it impact concurrency in Python? What kinds of applications does it impact more than others?

Ans: Python’s GIL is intended to serialize access to interpreter internals from different
threads. On multicore systems, it means that multiple threads can’t effectively make
use of multiple cores. (If the GIL didn’t lead to this problem, most people wouldn’t care
about the GIL it’s only being raised as an issue because of the increasing prevalence
of multicore systems.)
Note that Python’s GIL is only really an issue for CPython, the reference
implementation. Jython and IronPython don’t have a GIL. As a Python developer, you
don’t generally come across the GIL unless you’re writing a C extension. C extension
writers need to release the GIL when their extensions do blocking I/O, so that other
threads in the Python process get a chance to run.

7 .How do you iterate over a list and pull element indices at the same time?

Ans: You are looking for the enumerate function. It takes each element in a sequence
(like a list) and sticks it’s location right before it. For example:

Note that enumerate() returns an object to be iterated over, so wrapping it in list() just
helps us see what enumerate() produces.
An example that directly answers the question is given below

The output is:

8. How does Python’s list.sort work at a high level? Is it stable? What’s the runtime?

Ans: In early python versions, the sort function implemented a modified version of
quick sort. However, it was deemed unstable and as of 2.3 they switched to using an
adaptive merge sort algorithm.

9. How can we pass optional or keyword parameters from one function to another in Python?

Gather the arguments using the * and ** specifiers in the function’s parameter list. This
gives us positional arguments as a tuple and the keyword arguments as a dictionary.
Then we can pass these arguments while calling another function by using * and **:



10. How do you make a higher order function in Python?

A higher order function accepts one or more functions as input and returns a new
function. Sometimes it is required to use function as data To make high order function ,
we need to import functools module The functools.partial() function is used often for
high order function.

11. Why is not all memory freed when python exits?

Ans: Objects referenced from the global namespaces of Python modules are not
always deallocated when Python exits. This may happen if there are circular
references. There are also certain bits of memory that are allocated by the C library that
are impossible to free (e.g. a tool like the one Purify will complain about these). Python
is, however, aggressive about cleaning up memory on exit and does try to destroy every
single object. If you want to force Python to delete certain things on deallocation, you
can use the at exit module to register one or more exit functions to handle those

12. Given the list below remove the repetition of an element.

A bad solution would be to iterate over the list and checking for copies somehow and
then remove them!

A very good solution would be to use the set type. In a Python set, duplicates are not
So, list(set(words)) would remove the duplicates.

13 .Explain the role of repr function.

Python can convert any value to a string by making use of two functions repr() or
str(). The str() function returns representations of values which are human readable,
while repr() generates representations which can be read by the interpreter. repr()
returns a machine readable representation of values, suitable for an exec command.
Following code snippets shows working of repr() & str() :
— — — — -

44.Describe how to send mail from a Python script?

The smtplib module defines an SMTP client session object that can be used to
send mail to any Internet machine.
A sample email is demonstrated below.
import smtplib
SERVER = smtplib.SMTP(‘smtp.server.domain’)
TO = [“”] # must be a list
SUBJECT = “Hello!”
TEXT = “This message was sent with Python’s smtplib.”
# Main message
message = “””
From: Lincoln < >
To: CarreerRide
Subject: SMTP email msg
This is a test email. Acknowledge the email by responding.
“”” % (FROM, “, “.join(TO), SUBJECT, TEXT)
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)

45.Explain the disadvantages of python

Ans: Disadvantages of Python are: Python isn’t the best for memory intensive tasks.
Python is interpreted language & is slow compared to C/C++ or Java.

46.What is type conversion in Python?

Ans:Type conversion refers to the conversion of one data type into another.

int() — converts any data type into integer type

float() — converts any data type into float type

ord() — converts characters into integer

hex() — converts integers to hexadecimal

oct() — converts integer to octal

tuple() — This function is used to convert to a tuple.

set() — This function returns the type after converting to set.

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.

str() — Used to convert integer into a string.

complex(real,image) — This function converts real numbers to complex(real,image) number.

47.Is indentation required in python?

Ans:Indentation is necessary for Python. It specifies a block of code. All code within loops, classes, functions, etc is specified within an indented block. It is usually done using four space characters. If your code is not indented necessarily, it will not execute accurately and will throw errors as well.

48.How do you write comments in python?

Ans:Comments in Python start with a # character. However, alternatively at times, commenting is done using docstrings(strings enclosed within triple quotes).


#Comments in Python start like this

print(“Comments in Python start with a #”)

Output: Comments in Python start with a #

49.How can the ternary operators be used in python?

Ans: The Ternary operator is the operator that is used to show the conditional statements. This consists of the true or false values with a statement that has to be evaluated for it.


The Ternary operator will be given as:
[on_true] if [expression] else [on_false]x, y = 25, 50big = x if x < y else y


The expression gets evaluated like if x<y else y, in this case if x<y is true then the value is returned as big=x and if it is incorrect then big=y will be sent as a result.

50. What are negative indexes and why are they used?

Ans: 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 goes 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.

20. What is the output of the following program?











Ans​. Output:




22. What is the output of the following program?

















23. What is the output of the following program?











24. What is the purpose of ​#!/usr/bin/python​on the first line in the above code? Is there any advantage?

Ans: By specifying #!/usr/bin/pythonyou specify exactly which interpreter will be

used to run the script on a particular system. This is the hardcoded path to the python

interpreter for that particular system. The advantage of this line is that you can use a

specific python version to run your code.

25. What is the output of the following program?




Ans. Output:

IndexError.Or Error.

26. What is the output of the following program?




Ans​. Output:



As one would expect, attempting to access a member of a list using an index that

exceeds the number of members results in an IndexError

27. Do sets, dictionaries and tuples also support comprehensions?

Ans: Sets and dictionaries support it. However tuples are immutable and have

generators but not comprehensions.

Set Comprehension:



Dictionary Comprehension:





28. What are some mutable and immutable datatypes/datastructures in python?


Mutable Types Immutable Types

Dictionary number

List boolean



29. 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):


# output => 0 1 1 2 3 5 8

30. What can you use Python generator functions for?

Ans: One of the reasons to use generator is to make the solution clearer for some kind

of solutions.

The other is to treat results one at a time, avoiding building huge lists of results that you

would process separated anyway.

thiyagu 1

11. What type of a language is python? Interpreted or Compiled?

Ans: Beginner’s Answer:

Python is an interpreted, interactive, object oriented programming language.

Expert Answer:

Python is an interpreted language, as opposed to a compiled one, though the

distinction can be blurry because of the presence of the byte code compiler. This means

that source files can be run directly without explicitly creating an executable which is

then run.

12. What do you mean by python being an “interpreted language”? (Continues from previous question)

Ans: An interpreted language​is a programming language​for which most of its

implementations execute instructions directly, without previously compiling a program

into machinelanguage​instructions. In context of Python, it means that Python program

runs directly from the source code.

13.What is python’s standard way of identifying a block of code?

Ans: Indentation.

14. provide an example implementation of a function called “my_func” that returns the square of a given variable “x”. (Continues from previous question)




15. Is python statically typed or dynamically typed?

Ans: ​Dynamic.

In a statically typed language, the type of variables must be known (and usually

declared) at the point at which it is used. Attempting to use it will be an error. In a

dynamically typed language, objects still have a type, but it is determined at runtime.

You are free to bind names (variables) to different objects with a different type. So long

as you only perform operations valid for the type the interpreter doesn’t care what type

they actually are.

16. Is python strongly typed or weakly typed language?

Ans: ​Strong.

In a weakly typed language a compiler / interpreter will sometimes change the

type of a variable. For example, in some languages (like JavaScript) you can add

strings to numbers ‘x’ + 3 becomes ‘x3’. This can be a problem because if you have

made a mistake in your program, instead of raising an exception execution will continue

but your variables now have wrong and unexpected values.

In a strongly typed

language (like Python) you can’t perform operations inappropriate to the type of the

object attempting to add numbers to strings will fail. Problems like these are easier to

diagnose because the exception is raised at the point where the error occurs rather than

at some other, potentially far removed, place.

17. What is the python syntax for switch case statements?

Ans: Python doesn’t support switch case statements. You can use ifelse statements

for this purpose.

18. What are the rules for local and global variables in Python?

Ans: If a variable is defined outside function then it is implicitly global​. If variable is

assigned new value inside the function means it is local​. If we want to make it global we

need to explicitly define it as global. Variable referenced inside the function are implicit


19. What is the output of the following program?










Ans. Output:






Crampete offers specialized training courses for IT placement, Digital marketing, Full Stack Web Development, and IELTS

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store

Crampete offers specialized training courses for IT placement, Digital marketing, Full Stack Web Development, and IELTS