0% found this document useful (0 votes)
17 views72 pages

1

ast1

Uploaded by

ABUTALIBHK
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views72 pages

1

ast1

Uploaded by

ABUTALIBHK
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 72

Python Frequently asked Interview Questions

1) What is Python?

Python was created by Guido van Rossum, and released in 1991.

It is a general-purpose computer programming language. It is a high-level, object-oriented language which can run
equally on different platforms such as Windows, Linux, UNIX, and Macintosh. Its high-level built-in data structures,
combined with dynamic typing and dynamic binding. It is widely used in data science, machine learning and artificial
intelligence domain.

It is widely used for:

o Web development (server-side).


o Software development.
o Mathematics.
o System scripting.

3.What are the supported standard data types in python?


3. What are tuples?
Tuples are a sequence data type with immutable values in Python. The number of values i tuples is separated by commas.

4. What is the major difference between tuples and lists in Python?


There are several major differences between tuples and lists in Python, which include the following:
Tuples List

Tuples are similar to a list, but they are enclosed within parentheses, unlike the list The list is used to create a
sequence
The element and size can be changed The element and size cannot be changed

They can be updated


They cannot be updated

They act as a changeable list Lists use square brackets


They act as read-only lists

Example: L = [1, "a" , "string" , 1+2]


Tuples use parentheses

Example: tup = (1, "a", "string", 1+2)

5. What are positive and negative indices?


Positive indices are applied when the search begins from left to right. In negative indices, the search begins from right to
left. For example, in the array list of size n the positive index, the first index is 0, then comes 1, and until the last index is
n-1. However, in the negative index, the first index is -n, then -(n-1) until the last index -1.
s.

11. Define a function in Python.


A block of code that is executed when it is called is defined as a function. The keyword def is used to define a
Python function. 12. Define self in Python.
Self is an instance of a class or an object in Python. It is included as the first parameter. It helps differentiate between
the methods and attributes of a class with local variables.
13. What is the Pass statement?
A Pass statement in Python is used when we cannot decide what to do in our code, but we must type
something to make it syntactically correct.

22. Define slicing in Python.


Slicing refers to the mechanism to select the range of items from sequence types like lists,
tuples, strings. 23. What is docstring?
Docstring is a Python documentation string, it is a way of documenting Python functions, classes,
and modules. 24. How is a file deleted in Python?
The file can be deleted by either of these commands:

os.remove(filename)

os.unlink(filename)

25. What are the different stages of the life cycle of a thread?
The different stages of the life cycle of a thread are:

∙ Stage 1: Creating a class where we can override the run method of the Thread class.
∙ Stage 2: We make a call to start() on the new thread. The thread is taken forward for scheduling
purposes.
∙ Stage 3: Execution takes place wherein the thread starts execution, and it reaches the running
state.
∙ Stage 4: Thread waits until the calls to methods including join() and sleep() take place.
∙ Stage 5: After the waiting or execution of the thread, the waiting thread is sent for scheduling.
∙ Stage 6: Running thread is done by executing the terminates and reaches the dead state.
26. What are relational operators, assignment operators, and membership operators?

∙ The purpose of relational operators is to compare values.


∙ The assignment operators in Python can help in combining all the arithmetic operators with the
assignment symbol. ∙ Membership operators in Python with the purpose to validate the membership of a
value in a sequence.
30. Describe multithreading in Python.
Using Multithreading to speed up the code is not the go-to option, even though Python comes with a multi-threading package.
The package has the GIL or Global Interpreter Lock, which is a construct. It ensures that only one of the threads
executes at any given time. A thread acquires the GIL and then performs work before passing it to the next thread.
This happens so fast that to a user it seems that threads are executing in parallel. Obviously, this is not the case as
they are just taking turns while using the same CPU core. GIL passing adds to the overall overhead to the
execution.
As such, if you intend to use the threading package for speeding up the execution, using the package is not
recommended. .

36. Explain Inheritance.


Inheritance enables a class to acquire all members of another class. These members can be attributes,
methods, or both. By providing reusability, inheritance makes it easier to create as well as maintain an
application.

The class which acquires is known as the child class or the derived class. The one that it acquires from is known as the
superclass, base class, or the parent class. There are 4 forms of inheritance supported by Python:

∙ Single inheritance: A single derived class acquires members from one


superclass.

∙ Multi-Level inheritance: At least 2 different derived classes acquire members from two distinct base
classes. ∙ Hierarchical inheritance: A number of child classes acquire members from one
superclass
∙ Multiple inheritance: A derived class acquires members from several superclasses.

38. What is the difference between deep copy and shallow copy?
We use a shallow copy when a new instance type gets created. It keeps the values that are copied in the new
instance. Just like it copies the values, the shallow copy also copies the reference pointers.
Reference points copied in the shallow copy reference to the original objects. Any changes made in any member of the
class affect the original copy of the same. Shallow copy enables faster execution of the program.
Deep copy is used for storing values that are already copied. Unlike shallow copy, it doesn‟t copy the reference
pointers to the objects. Deep copy makes the reference to an object in addition to storing the new object that is
pointed by some other object.
Changes made to the original copy will not affect any other copy that makes use of the referenced or stored object.
Contrary to the shallow copy, deep copy makes the execution of a program slower. This is due to the fact that it makes
some copies for each object that is called.

[8, 64], [9, 81]]

41. Explain dictionaries with an example.


A dictionary in the Python programming language is an unordered collection of data values such as a map. Dictionary
holds the key:value pair. This helps define a one-to-one relationship between keys and values. Indexed by keys, a
typical dictionary contains a pair of keys and corresponding values.
Let us take an example with three keys, namely website, language, and offering. Their corresponding values are
hackr.io, Python, and Tutorials. The code for would be:

42. Python supports negative indexes. What are they and why are they used?
The sequences in Python are indexed. It consists of positive and negative numbers. Positive numbers use 0 as the
first index, 1 as the second index, and so on. Hence, any index for a positive number n is n-1.
Unlike positive numbers, index numbering for the negative numbers starts from -1 and it represents the last index in
the sequence. Likewise, -2 represents the penultimate index. These are known as negative indexes. Negative indexes
are used for:

∙ Removing any new-line spaces from the string, thus allowing the string to except the last character, represented
as S[:-1] ∙ Showing the index to representing the string in the correct order

48. What is the map() function used for?


The map() function applies a given function to each item of an iterable. It then returns a list of the results. The value
returned from the map() function can then be passed on to functions to the likes of the list() and set().
Typically, the given function is the first argument and the iterable is available as the second argument to a map()
function. Several tables are given if the function takes in more than one argument.
49. What is Pickling and Unpickling?

The Pickle module in Python allows accepting any object and then converting it into a string representation. It then
dumps the same into a file by means of the dump function. This process is known as pickling. Unpickling retrieves the
original Python objects from a stored string representation.
53. How is memory managed in Python?
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.
54. What is the lambda function?
A lambda function is an anonymous function. This function can have only one statement but can have any number of

parameters. a = lambda x,y : x+y

print(a(5, 6))

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


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.
56. What are the built-in types provided by Python?
Mutable built-in types:

∙ Lists
∙ Sets
∙ Dictionaries
Immutable built-in types:

∙ Strings
∙ Tuples
∙ Numbers

57. What are Python modules?


A file containing Python code like functions and variables is a Python module. A Python module is an executable
file with a .py extension. Some built-in modules are:

∙ os
∙ sys
∙ math
∙ random
∙ data time
∙ JSON

59. What is the split function used for?


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.

2) Why Python?

o Python is an interpreted, object-oriented, high-level programming language with dynamic semantics.


o Python is compatible with different platforms like Windows, Mac, Linux, Raspberry Pi, etc.
o Python has a simple syntax as compared to other languages.
o Python allows a developer to write programs with fewer lines than some other programming languages.
o Python runs on an interpreter system, means that the code can be executed as soon as it is written. It helps
to provide a prototype very quickly.
o Python can be described as a procedural way, an object-orientated way or a functional way.
o The Python interpreter and the extensive standard library are available in source or binary form without
charge for all major platforms, and can be freely distributed.

3) What are the applications of Python?

Python is used in various software domains some application areas are given below.

o Web and Internet Development


o Games
o Scientific and computational applications
o Language development
o Image processing and graphic design applications
o Enterprise and business applications development
o Operating systems
o GUI based desktop applications
Python provides various web frameworks to develop web applications. The popular python web frameworks
are Django, Pyramid, Flask.

Python's standard library supports for E-mail processing, FTP, IMAP, and other Internet protocols.

Python's SciPy and NumPy helps in scientific and computational application development.

Python's Tkinter library supports to create a desktop based GUI applications.

4) What are the advantages of Python?

Advantages of Python are:

o Python is Interpreted language

Interpreted: Python is an interpreted language. It does not require prior compilation of code and executes instructions
directly.

o It is Free and open source

Free and open source: It is an open-source project which is publicly available to reuse. It can be downloaded free of
cost.

o It is Extensible

Extensible: It is very flexible and extensible with any module.

o Object-oriented
Object-oriented: Python allows to implement the Object-Oriented concepts to build application solution.

o It has Built-in data structure

Built-in data structure: Tuple, List, and Dictionary are useful integrated data structures provided by the language.

o Readability
o High-Level Language
o Cross-platform

Portable: Python programs can run on cross platforms without affecting its performance.

5) What is PEP 8?

PEP 8 stands for Python Enhancement Proposal, it can be defined as a document that helps us to provide the
guidelines on how to write the Python code. It is basically a set of rules that specify how to format Python code for
maximum readability. It was written by Guido van Rossum, Barry Warsaw and Nick Coghlan in 2001.

6) What do you mean by Python literals?

Literals can be defined as a data which is given in a variable or constant. Python supports the following literals:

String Literals

String literals are formed by enclosing text in the single or double quotes. For example, string literals are string values.

Example:

1. # in single quotes
2. single = 'JavaTpoint'
3. # in double quotes
4. double = "JavaTpoint"
5. # multi-line String
6. multi = '''''Java
7. T
8. point'''
9.
10. print(single)
11. print(double)
12. print(multi)

Output:

JavaTpoint
JavaTpoint
Java
T
point

Numeric Literals

Python supports three types of numeric literals integer, float and complex.

Example:

1. # Integer literal
2. a = 10
3. #Float Literal
4. b = 12.3
5. #Complex Literal
6. x = 3.14j
7. print(a)
8. print(b)
9. print(x)

Output:

10
12.3
3.14j

Boolean Literals

Boolean literals are used to denote Boolean values. It contains either True or False.

Example:

1. p = (1 == True)
2. q = (1 == False)
3. r = True + 3
4. s = False + 7
5.
6. print("p is", p)
7. print("q is", q)
8. print("r:", r)
9. print("s:", s)

Output:

p is True
q is False
r: 4
s: 7

Special literals

Python contains one special literal, that is, 'None'. This special literal is used for defining a null variable. If 'None' is
compared with anything else other than a 'None', it will return false.

Example:

1. word = None
2. print(word)

Output:

None

7) Explain Python Functions?

A function is a section of the program or a block of code that is written once and can be executed whenever required
in the program. A function is a block of self-contained statements which has a valid name, parameters list, and body.
Functions make programming more functional and modular to perform modular tasks. Python provides several built-
in functions to complete tasks and also allows a user to create new functions as well.

There are three types of functions:

o Built-In Functions: copy(), len(), count() are the some built-in functions.
o User-defined Functions: Functions which are defined by a user known as user-defined functions.
o Anonymous functions: These functions are also known as lambda functions because they are not declared
with the standard def keyword.

Example: A general syntax of user defined function is given below.

1. def function_name(parameters list):


2. #--- statements---
3. return a_value
8) What is zip() function in Python?

Python zip() function returns a zip object, which maps a similar index of multiple containers. It takes an iterable,
convert into iterator and aggregates the elements based on iterables passed. It returns an iterator of tuples.

Signature

1. zip(iterator1, iterator2, iterator3 ...)

Parameters

iterator1, iterator2, iterator3: These are iterator objects that are joined together.

Return

It returns an iterator from two or more iterators.

Note: If the given lists are of different lengths, zip stops generating tuples when the first list ends. It means two lists are having 3,
and 5 lengths will create a 3-tuple.

9) What is Python's parameter passing mechanism?

There are two parameters passing mechanism in Python:

o Pass by references
o Pass by value

By default, all the parameters (arguments) are passed "by reference" to the functions. Thus, if you change the value of
the parameter within a function, the change is reflected in the calling function as well. It indicates the original variable.
For example, if a variable is declared as a = 10, and passed to a function where it's value is modified to a = 20. Both
the variables denote to the same value.

The pass by value is that whenever we pass the arguments to the function only values pass to the function, no
reference passes to the function. It makes it immutable that means not changeable. Both variables hold the different
values, and original value persists even after modifying in the function.
Python has a default argument concept which helps to call a method using an arbitrary number of arguments.

10) How to overload constructors or methods in Python?

Python's constructor: _init__ () is the first method of a class. Whenever we try to instantiate an object __init__() is
automatically invoked by python to initialize members of an object. We can't overload constructors or methods in
Python. It shows an error if we try to overload.

Example:

1. class student:
2. def __init__(self, name):
3. self.name = name
4. def __init__(self, name, email):
5. self.name = name
6. self.email = email
7.
8. # This line will generate an error
9. #st = student("rahul")
10.
11. # This line will call the second constructor
12. st = student("rahul", "[email protected]")
13. print("Name: ", st.name)
14. print("Email id: ", st.email)

Output:

Name: rahul
Email id: [email protected]

11) What is the difference between remove() function and del statement?

The user can use the remove() function to delete a specific object in the list.

Example:
1. list_1 = [ 3, 5, 7, 3, 9, 3 ]
2. print(list_1)
3. list_1.remove(3)
4. print("After removal: ", list_1)

Output:

[3, 5, 7, 3, 9, 3]
After removal: [5, 7, 3, 9, 3]

If you want to delete an object at a specific location (index) in the list, you can either use del or pop.

Example:

1. list_1 = [ 3, 5, 7, 3, 9, 3 ]
2. print(list_1)
3. del list_1[2]
4. print("After deleting: ", list_1)

Output:

[3, 5, 7, 3, 9, 3]
After deleting: [3, 5, 3, 9, 3]

Note: You don't need to import any extra module to use these functions for removing an element from the list.

We cannot use these methods with a tuple because the tuple is different from the list.

12) What is swapcase() function in the Python?

It is a string's function which converts all uppercase characters into lowercase and vice versa. It is used to alter the
existing case of the string. This method creates a copy of the string which contains all the characters in the swap case.
If the string is in lowercase, it generates a small case string and vice versa. It automatically ignores all the non-
alphabetic characters. See an example below.

Example:

1. string = "IT IS IN LOWERCASE."


2. print(string.swapcase())
3.
4. string = "it is in uppercase."
5. print(string.swapcase())

Output:

it is in lowercase.
IT IS IN UPPERCASE.
15) Why do we use join() function in Python?

The join() is defined as a string method which returns a string value. It is concatenated with the elements of an
iterable. It provides a flexible way to concatenate the strings. See an example below.

Example:

1. str = "Rohan"
2. str2 = "ab"
3. # Calling function
4. str2 = str.join(str2)
5. # Displaying result
6. print(str2)

Output:

aRohanb

16) Give an example of shuffle() method?

This method shuffles the given string or an array. It randomizes the items in the array. This method is present in the
random module. So, we need to import it and then we can call the function. It shuffles elements each time when the
function calls and produces different output.

Example:

1. # import the random module


2. import random
3. # declare a list
4. sample_list1 = ['Z', 'Y', 'X', 'W', 'V', 'U']
5. print("Original LIST1: ")
6. print(sample_list1)
7. # first shuffle
8. random.shuffle(sample_list1)
9. print("\nAfter the first shuffle of LIST1: ")
10. print(sample_list1)
11. # second shuffle
12. random.shuffle(sample_list1)
13. print("\nAfter the second shuffle of LIST1: ")
14. print(sample_list1)

Output:
Original LIST1:
['Z', 'Y', 'X', 'W', 'V', 'U']

After the first shuffle of LIST1:


['V', 'U', 'W', 'X', 'Y', 'Z']

After the second shuffle of LIST1:


['Z', 'Y', 'X', 'U', 'V', 'W']

17) What is the use of break statement?

The break statement is used to terminate the execution of the current loop. Break always breaks the current execution
and transfer control to outside the current block. If the block is in a loop, it exits from the loop, and if the break is in a
nested loop, it exits from the innermost loop.

Example:

1. list_1 = ['X', 'Y', 'Z']


2. list_2 = [11, 22, 33]
3. for i in list_1:
4. for j in list_2:
5. print(i, j)
6. if i == 'Y' and j == 33:
7. print('BREAK')
8. break
9. else:
10. continue
11. break

Output:

2
X 11
X 22
X 33
Y 11
Y 22
Y 33
BREAK
Python Break statement flowchart.

18) What is tuple in Python?

A tuple is a built-in data collection type. It allows us to store values in a sequence. It is immutable, so no change is
reflected in the original data. It uses () brackets rather than [] square brackets to create a tuple. We cannot remove
any element but can find in the tuple. We can use indexing to get elements. It also allows traversing elements in
reverse order by using negative indexing. Tuple supports various methods like max(), sum(), sorted(), Len() etc.

To create a tuple, we can declare it as below.

Example:

1. # Declaring tuple
2. tup = (2,4,6,8)
3. # Displaying value
4. print(tup)
5.
6. # Displaying Single value
7. print(tup[2])

Output:

(2, 4, 6, 8)
6

It is immutable. So updating tuple will lead to an error.

Example:

1. # Declaring tuple
2. tup = (2,4,6,8)
3. # Displaying value
4. print(tup)
5.
6. # Displaying Single value
7. print(tup[2])
8.
9. # Updating by assigning new value
10. tup[2]=22
11. # Displaying Single value
12. print(tup[2])

Output:

tup[2]=22
TypeError: 'tuple' object does not support item assignment
(2, 4, 6, 8)
19) Which are the file related libraries/modules in Python?

The Python provides libraries/modules that enable you to manipulate text files and binary files on the file system. It
helps to create files, update their contents, copy, and delete files. The libraries are os, os.path, and shutil.

Here, os and os.path - modules include a function for accessing the filesystem

while shutil - module enables you to copy and delete the files.

20) What are the different file processing modes supported by Python?

Python provides four modes to open files. The read-only (r), write-only (w), read-write (rw) and append mode (a). 'r' is
used to open a file in read-only mode, 'w' is used to open a file in write-only mode, 'rw' is used to open in reading
and write mode, 'a' is used to open a file in append mode. If the mode is not specified, by default file opens in read-
only mode.

o Read-only mode (r): Open a file for reading. It is the default mode.
o Write-only mode (w): Open a file for writing. If the file contains data, data would be lost. Other a new file is
created.
o Read-Write mode (rw): Open a file for reading, write mode. It means updating mode.
o Append mode (a): Open for writing, append to the end of the file, if the file exists.

21) What is an operator in Python?

An operator is a particular symbol which is used on some values and produces an output as a result. An operator
works on operands. Operands are numeric literals or variables which hold some values. Operators can be unary,
binary or ternary. An operator which requires a single operand known as a unary operator, which require two
operands known as a binary operator and which require three operands is called ternary operator.
Example:

1. # Unary Operator
2. A = 12
3. B = -(A)
4. print (B)
5. # Binary Operator
6. A = 12
7. B = 13
8. print (A + B)
9. print (B * A)
10. #Ternary Operator
11. A = 12
12. B = 13
13. min = A if A < B else B
14.
15. print(min)

Output:

# Unary Operator
-12
# Binary Operator
25
156
# Ternary Operator
12

22) What are the different types of operators in Python?

Python uses a rich set of operators to perform a variety of operations. Some individual operators like membership and
identity operators are not so familiar but allow to perform operations.

o Arithmetic OperatorsRelational Operators


o Assignment Operators
o Logical Operators
o Membership Operators
o Identity Operators
o Bitwise Operators

Arithmetic operators perform basic arithmetic operations. For example "+" is used to add and "?" is used for
subtraction.

Example:

1. # Adding two values


2. print(12+23)
3. # Subtracting two values
4. print(12-23)
5. # Multiplying two values
6. print(12*23)
7. # Dividing two values
8. print(12/23)

Output:

35
-11
276
0.5217391304347826

Relational Operators are used to comparing the values. These operators test the conditions and then returns a
boolean value either True or False.

# Examples of Relational Operators

Example:

1. a, b = 10, 12
2. print(a==b) # False
3. print(a<b) # True
4. print(a<=b) # True
5. print(a!=b) # True

Output:

False
True
True
True

Assignment operators are used to assigning values to the variables. See the examples below.

Example:

1. # Examples of Assignment operators


2. a=12
3. print(a) # 12
4. a += 2
5. print(a) # 14
6. a -= 2
7. print(a) # 12
8. a *=2
9. print(a) # 24
10. a **=2
11. print(a) # 576

Output:

12
14
12
24
576

Logical operators are used to performing logical operations like And, Or, and Not. See the example below.

Example:

1. # Logical operator examples


2. a = True
3. b = False
4. print(a and b) # False
5. print(a or b) # True
6. print(not b) # True

Output:

False
True
True

Membership operators are used to checking whether an element is a member of the sequence (list, dictionary,
tuples) or not. Python uses two membership operators in and not in operators to check element presence. See an
example.

Example:

1. # Membership operators examples


2. list = [2,4,6,7,3,4]
3. print(5 in list) # False
4. cities = ("india","delhi")
5. print("tokyo" not in cities) #True

Output:

False
True

Identity Operators (is and is not) both are used to check two values or variable which are located on the same part of
the memory. Two variables that are equal does not imply that they are identical. See the following examples.

Example:
1. # Identity operator example
2. a = 10
3. b = 12
4. print(a is b) # False
5. print(a is not b) # True

Output:

False
True

Bitwise Operators are used to performing operations over the bits. The binary operators (&, |, OR) work on bits. See
the example below.

Example:

1. # Identity operator example


2. a = 10
3. b = 12
4. print(a & b) # 8
5. print(a | b) # 14
6. print(a ^ b) # 6
7. print(~a) # -11

Output:

8
14
6
-11

23) How to create a Unicode string in Python?

In Python 3, the old Unicode type has replaced by "str" type, and the string is treated as Unicode by default. We can
make a string in Unicode by using art.title.encode("utf-8") function.

Example:

1. unicode_1 = ("\u0123", "\u2665", "\U0001f638", "\u265E", "\u265F", "\u2168")


2. print (unicode_1)

Output:

unicode_1: ('ģ', '♥', '�', '♞', '♟', 'Ⅸ')


24) is Python interpreted language?

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

Unlike Java or C, Python does not require compilation before execution.

25) How is memory managed in Python?

Memory is managed in Python in the following ways:

o Memory management in python is managed by Python private heap space. All Python objects and data
structures are located in a private heap. The programmer does not have access to this private heap. The
python interpreter takes care of this instead.
o The allocation of heap space for Python objects is done by Python's memory manager. The core API gives
access to some tools for the programmer to code.
o Python also has an inbuilt garbage collector, which recycles all the unused memory and so that it can be
made available to the heap space.

26) What is the Python decorator?

Decorators are very powerful and a useful tool in Python that allows the programmers to add functionality to an
existing code. This is also called metaprogramming because a part of the program tries to modify another part of the
program at compile time. It allows the user to wrap another function to extend the behaviour of the wrapped
function, without permanently modifying it.

Example:
1. def function_is_called():
2. def function_is_returned():
3. print("JavaTpoint")
4. return function_is_returned
5. new_1 = function_is_called()
6. # Outputs "JavaTpoint"
7. new_1()

Output:

JavaTpoint

Functions vs. Decorators

A function is a block of code that performs a specific task whereas a decorator is a function that modifies other
functions.

27) What are the rules for a local and global variable in Python?

Global Variables:

o Variables declared outside a function or in global space are called global variables.
o If a variable is ever assigned a new value inside the function, the variable is implicitly local, and we need to
declare it as 'global' explicitly. To make a variable globally, we need to declare it by using global keyword.
o Global variables are accessible anywhere in the program, and any function can access and modify its value.

Example:

1. A = "JavaTpoint"
2. def my_function():
3. print(A)
4. my_function()

Output:

JavaTpoint

Local Variables:

o Any variable declared inside a function is known as a local variable. This variable is present in the local space
and not in the global space.
o If a variable is assigned a new value anywhere within the function's body, it's assumed to be a local.
o Local variables are accessible within local body only.

Example:
1. def my_function2():
2. K = "JavaTpoint Local"
3. print(K)
4. my_function2()

Output:

JavaTpoint Local

28) What is the namespace in Python?

The namespace is a fundamental idea to structure and organize the code that is more useful in large projects.
However, it could be a bit difficult concept to grasp if you're new to programming. Hence, we tried to make
namespaces just a little easier to understand.

A namespace is defined as a simple system to control the names in a program. It ensures that names are unique and
won't lead to any conflict.

Also, Python implements namespaces in the form of dictionaries and maintains name-to-object mapping where
names act as keys and the objects as values.

29) What are iterators in Python?

In Python, iterators are used to iterate a group of elements, containers like a list. Iterators are the collection of items,
and it can be a list, tuple, or a dictionary. Python iterator implements __itr__ and next() method to iterate the stored
elements. In Python, we generally use loops to iterate over the collections (list, tuple).

In simple words: Iterators are objects which can be traversed though or iterated upon.

30) What is a generator in Python?

In Python, the generator is a way that specifies how to implement iterators. It is a normal function except that it yields
expression in the function. It does not implements __itr__ and next() method and reduce other overheads as well.

If a function contains at least a yield statement, it becomes a generator. The yield keyword pauses the current
execution by saving its states and then resume from the same when required.

31) What is slicing in Python?

Slicing is a mechanism used to select a range of items from sequence type like list, tuple, and string. It is beneficial
and easy to get elements from a range by using slice way. It requires a : (colon) which separates the start and end
index of the field. All the data collection types List or tuple allows us to use slicing to fetch elements. Although we can
get elements by specifying an index, we get only single element whereas using slicing we can get a group of
elements.

Example:

1. Q = "JavaTpoint, Python Interview Questions!"


2. print(Q[2:25])

Output:

vaTpoint, Python Interv

32) What is a dictionary in Python?

The Python dictionary is a built-in data type. It defines a one-to-one relationship between keys and values.
Dictionaries contain a pair of keys and their corresponding values. It stores elements in key and value pairs. The keys
are unique whereas values can be duplicate. The key accesses the dictionary elements.

Keys index dictionaries.

Example:

The following example contains some keys Country Hero & Cartoon. Their corresponding values are India, Modi, and
Rahul respectively.

1. dict = {'Country': 'India', 'Hero': 'Modi', 'Cartoon': 'Rahul'}


2. print ("Country: ", dict['Country'])
3. print ("Hero: ", dict['Hero'])
4. print ("Cartoon: ", dict['Cartoon'])

Output:

Country: India
Hero: Modi
Cartoon: Rahul
33) What is Pass in Python?

Pass specifies a Python statement without operations. It is a placeholder in a compound statement. If we want to
create an empty class or functions, the pass keyword helps to pass the control without error.

Example:

1. class Student:
2. pass # Passing class
3. class Student:
4. def info():
5. pass # Passing function

34) Explain docstring in Python?

The Python docstring is a string literal that occurs as the first statement in a module, function, class, or method
definition. It provides a convenient way to associate the documentation.

String literals occurring immediately after a simple assignment at the top are called "attribute docstrings".

String literals occurring immediately after another docstring are called "additional docstrings".

Python uses triple quotes to create docstrings even though the string fits on one line.

Docstring phrase ends with a period (.) and can be multiple lines. It may consist of spaces and other special chars.

Example:

1. # One-line docstrings
2. def hello():
3. """A function to greet."""
4. return "hello"

35) What is a negative index in Python and why are they used?

The sequences in Python are indexed and it consists of the positive as well as negative numbers. The numbers that
are positive uses '0' that is uses as first index and '1' as the second index and the process go on like that.

The index for the negative number starts from '-1' that represents the last index in the sequence and '-2' as the
penultimate index and the sequence carries forward like the positive number.

The negative index is used to remove any new-line spaces from the string and allow the string to except the last
character that is given as S[:-1]. The negative index is also used to show the index to represent the string in correct
order.
36) What is pickling and unpickling in Python?

The Python pickle is defined as a module which accepts any Python object and converts it into a string representation.
It dumps the Python object into a file using the dump function; this process is called Pickling.

The process of retrieving the original Python objects from the stored string representation is called as Unpickling.

37) Which programming language is a good choice between Java and Python?

Java and Python both are object-oriented programming languages. Let's compare both on some criteria given below:

Criteria Java Python

Ease of use Good Very Good

Coding Speed Average Excellent

Data types Static type Dynamic type

Data Science and Machine learning application Average Very Good

38) What is the usage of help() and dir() function in Python?

Help() and dir() both functions are accessible from the Python interpreter and used for viewing a consolidated dump
of built-in functions.

Help() function: The help() function is used to display the documentation string and also facilitates us to see the help
related to modules, keywords, and attributes.

Dir() function: The dir() function is used to display the defined symbols.

39) What are the differences between Python 2.x and Python 3.x?

Python 2.x is an older version of Python. Python 3.x is newer and latest version. Python 2.x is legacy now. Python 3.x is
the present and future of this language.

The most visible difference between Python2 and Python3 is in print statement (function). In Python 2, it looks like
print "Hello", and in Python 3, it is print ("Hello").

String in Python2 is ASCII implicitly, and in Python3 it is Unicode.

The xrange() method has removed from Python 3 version. A new keyword as is introduced in Error handling.
40) How Python does Compile-time and Run-time code checking?

In Python, some amount of coding is done at compile time, but most of the checking such as type, name, etc. are
postponed until code execution. Consequently, if the Python code references a user-defined function that does not
exist, the code will compile successfully. The Python code will fail only with an exception when the code execution
path does not exist.

41) What is the shortest method to open a text file and display its content?

The shortest way to open a text file is by using "with" command in the following manner:

Example:

1. with open("FILE NAME", "r") as fp:


2. fileData = fp.read()
3. # To print the contents of the file
4. print(fileData)

Output:

"The data of the file will be printed."

42) What is the usage of enumerate () function in Python?

The enumerate() function is used to iterate through the sequence and retrieve the index position and its
corresponding value at the same time.

Example:

1. list_1 = ["A","B","C"]
2. s_1 = "Javatpoint"
3. # creating enumerate objects
4. object_1 = enumerate(list_1)
5. object_2 = enumerate(s_1)
6.
7. print ("Return type:",type(object_1))
8. print (list(enumerate(list_1)))
9. print (list(enumerate(s_1)))

Output:

Return type:
[(0, 'A'), (1, 'B'), (2, 'C')]
[(0, 'J'), (1, 'a'), (2, 'v'), (3, 'a'), (4, 't'), (5, 'p'), (6, 'o'), (7,
'i'), (8, 'n'), (9, 't')]

43) Give the output of this example: A[3] if A=[1,4,6,7,9,66,4,94].

Since indexing starts from zero, an element present at 3rd index is 7. So, the output is 7.

44) What is type conversion in Python?

Type conversion refers to the conversion of one data type iinto 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,imag) - This functionconverts real numbers to complex(real,imag) number.

45) How to send an email in Python Language?

To send an email, Python provides smtplib and email modules. Import these modules into the created mail script and
send mail by authenticating a user.

It has a method SMTP(smtp-server, port). It requires two parameters to establish SMTP connection.

A simple example to send an email is given below.

Example:
1. import smtplib
2. # Calling SMTP
3. s = smtplib.SMTP('smtp.gmail.com', 587)
4. # TLS for network security
5. s.starttls()
6. # User email Authentication
7. s.login("sender@email_id", "sender_email_id_password")
8. # Message to be sent
9. message = "Message_sender_need_to_send"
10. # Sending the mail
11. s.sendmail("sender@email_id ", "receiver@email_id", message)

46) What is the difference between Python Arrays and lists?

Arrays and lists, in Python, have the same way of storing data. But, arrays can hold only a single data type elements
whereas lists can hold any data type elements.

Example:

1. import array as arr


2. User_Array = arr.array('i', [1,2,3,4])
3. User_list = [1, 'abc', 1.20]
4. print (User_Array)
5. print (User_list)

Output:

array('i', [1, 2, 3, 4])


[1, 'abc', 1.2]

47) What is lambda function in Python?

The anonymous function in python is a function that is defined without a name. The normal functions are defined
using a keyword "def", whereas, the anonymous functions are defined using the lambda function. The anonymous
functions are also called as lambda functions.

48) Why do lambda forms in Python not have the statements?

Lambda forms in Python does not have the statement because it is used to make the new function object and return
them in runtime.
49) What are functions in Python?

A function is a block of code which is executed only when it is called. To define a Python function, the def keyword is
used.

Example:

1. def New_func():
2. print ("Hi, Welcome to JavaTpoint")
3. New_func() #calling the function

Output:

Hi, Welcome to JavaTpoint

50) What is __init__?

The __init__ is a method or constructor in Python. This method is automatically called to allocate memory when a new
object/ instance of a class is created. All classes have the __init__ method.

Example:

1. class Employee_1:
2. def __init__(self, name, age,salary):
3. self.name = name
4. self.age = age
5. self.salary = 20000
6. E_1 = Employee_1("pqr", 20, 25000)
7. # E1 is the instance of class Employee.
8. #__init__ allocates memory for E1.
9. print(E_1.name)
10. print(E_1.age)
11. print(E_1.salary)

Output:

pqr
20
25000

51) What is self in Python?

Self is an instance or an object of a class. In Python, this is explicitly included as the first parameter. However, this is
not the case in Java where it's optional. It helps to differentiate between the methods and attributes of a class with
local variables.
The self-variable in the init method refers to the newly created object while in other methods, it refers to the object
whose method was called.

52) How can you generate random numbers in Python?

Random module is the standard module that is used to generate a random number. The method is defined as:

1. import random
2. random.random

The statement random.random() method return the floating point number that is in the range of [0, 1). The function
generates random float numbers. The methods that are used with the random class are the bound methods of the
hidden instances. The instances of the Random can be done to show the multi-threading programs that creates a
different instance of individual threads. The other random generators that are used in this are:

randrange(a, b): it chooses an integer and define the range in-between [a, b). It returns the elements by selecting it
randomly from the range that is specified. It doesn't build a range object.

uniform(a, b): it chooses a floating point number that is defined in the range of [a,b).Iyt returns the floating point
number

normalvariate(mean, sdev): it is used for the normal distribution where the mu is a mean and the sdev is a sigma
that is used for standard deviation.

The Random class that is used and instantiated creates independent multiple random number generators.

53) What is PYTHONPATH?

PYTHONPATH is an environment variable which is used when a module is imported. Whenever a module is imported,
PYTHONPATH is also looked up to check for the presence of the imported modules in various directories. The
interpreter uses it to determine which module to load.

54) What are python modules? Name some commonly used built-in modules in Python?

Python modules are files containing Python code. This code can either be functions classes or variables. A Python
module is a .py file containing executable code.

Some of the commonly used built-in modules are:

o os
o sys
o math
o random
o data time
o JSON

55) What is the difference between range & xrange?

For the most part, xrange and range are the exact same in terms of functionality. They both provide a way to generate
a list of integers for you to use, however you please. The only difference is that range returns a Python list object and
x range returns an xrange object.

This means that xrange doesn't actually generate a static list at run-time like range does. It creates the values as you
need them with a special technique called yielding. This technique is used with a type of object known as generators.
That means that if you have a really gigantic range you'd like to generate a list for, say one billion, xrange is the
function to use.

This is especially true if you have a really memory sensitive system such as a cell phone that you are working with, as
range will use as much memory as it can to create your array of integers, which can result in a Memory Error and
crash your program. It's a memory hungry beast.

56) What advantages do NumPy arrays offer over (nested) Python lists?

o Python's lists are efficient general-purpose containers. They support (fairly) efficient insertion, deletion,
appending, and concatenation, and Python's list comprehensions make them easy to construct and
manipulate.
o They have certain limitations: they don't support "vectorized" operations like elementwise addition and
multiplication, and the fact that they can contain objects of differing types mean that Python must store type
information for every element, and must execute type dispatching code when operating on each element.
o NumPy is not just more efficient; it is also more convenient. We get a lot of vector and matrix operations for
free, which sometimes allow one to avoid unnecessary work. And they are also efficiently implemented.
o NumPy array is faster and we get a lot built in with NumPy, FFTs, convolutions, fast searching, basic statistics,
linear algebra, histograms, etc.

57) Mention what the Django templates consist of.

The template is a simple text file. It can create any text-based format like XML, CSV, HTML, etc. A template contains
variables that get replaced with values when the template is evaluated and tags (% tag %) that control the logic of the
template.
58) Explain the use of session in Django framework?

Django provides a session that lets the user store and retrieve data on a per-site-visitor basis. Django abstracts the
process of sending and receiving cookies, by placing a session ID cookie on the client side, and storing all the related
data on the server side.

So, the data itself is not stored client side. This is good from a security perspective.

Statement 2: Python provides high-level data structures along with dynamic binding and typing for Rapid
Application Development and deployment.

Q1. What is the difference between list and tuples in Python?


Q2. What are the key features of Python?
Q3. What type of language is python?
Q4. How is Python an interpreted language?
Q5. What is pep 8?
Q6. How is memory managed in Python?
Q7. What is name space in Python?
Q8. What is PYTHON PATH?
Q9. What are python modules?
Q10. What are local variables and global variables in Python?

Python Interview Questions And Answers 2023


Q1. What is the difference between list and tuples in Python?

LIST vs TUPLES
LIST TUPLES

Tuples are immutable (tuples are lists which can’t be


Lists are mutable i.e they can be edited.
edited).

Lists are slower than tuples. Tuples are faster than list.

Syntax: list_1 = *10, ‘Chelsea’, 20+ Syntax: tup_1 = (10, ‘Chelsea’ , 20)

Q2. What are the key features of Python?

 Python is an interpreted language. That means that, unlike languages like C and its variants,
Python does not need to be compiled before it is run. Other interpreted languages
include PHP and Ruby.
 Python is dynamically typed, this means that you don’t need to state the types of variables
when you declare them or anything like that. You can do things like x=111 and then x="I'm a
string" without error
 Python is well suited to object orientated programming in that it allows the definition of classes
along with composition and inheritance. Python does not have access specifiers (like
C++’s public, private).
 In Python, functions are first-class objects. This means that they can be assigned to variables,
returned from other functions and passed into functions. Classes are also first class objects
 Writing Python code is quick but running it is often slower than compiled languages.
Fortunately,Python allows the inclusion of C-based extensions so bottlenecks can be optimized
away and often are. The numpy package is a good example of this, it’s really quite quick because
a lot of the number-crunching it does isn’t actually done by Python
 Python finds use in many spheres – web applications, automation, scientific modeling, big data
applications and many more. It’s also often used as “glue” code to get other languages and
components to play nice. Learn more about Big Data and its applications from the

Q3. What type of language is python? Programming or scripting?

Ans: Python is capable of scripting, but in general sense, it

is considered as a general-purpose programming language. To know more about Scripting, you


can refer to the Python Scripting Tutorial.

Q4.Python an interpreted language. Explain.

Ans: An interpreted language is any programming language which is not in machine-level code
before runtime. Therefore, Python is an interpreted language.

Q5.What is pep 8?

Ans: PEP stands for Python Enhancement Proposal. It is a set of rules that specify how to
format Python code for maximum readability.

Q6.What are the benefits of using Python?

Ans: The benefits of using python are-

1.
1. Easy to use– Python is a high-level programming language that is easy to use, read,
write and learn.
2. Interpreted language– Since python is interpreted language, it executes the code line by
line and stops if an error occurs in any line.
3. Dynamically typed– the developer does not assign data types to variables at the time of
coding. It automatically gets assigned during execution.
4. Free and open-source– Python is free to use and distribute. It is open source.
5. Extensive support for libraries– Python has vast libraries that contain almost any
function needed. It also further provides the facility to import other packages using
Python Package Manager(pip).
6. Portable– Python programs can run on any platform without requiring any change.
7. The data structures used in python are user friendly.
8. It provides more functionality with less coding.

Q7.What are Python namespaces?

Ans: A namespace in python refers to the name which is assigned to each object in python. The
objects are variables and functions. As each object is created, its name along with space(the
address of the outer function in which the object is), gets created. The namespaces are
maintained in python like a dictionary where the key is the namespace and value is the address of
the object. There 4 types of namespace in python-

1. Built-in namespace– These namespaces contain all the built-in objects in python and are
available whenever python is running.
2. Global namespace– These are namespaces for all the objects created at the level of the main
program.
3. Enclosing namespaces– These namespaces are at the higher level or outer function.
4. Local namespaces– These namespaces are at the local or inner function.
Q8.What are decorators in Python?

Ans: Decorators are used to add some design patterns to a function without changing its
structure. Decorators generally are defined before the function they are enhancing. To apply a
decorator we first define the decorator function. Then we write the function it is applied to and
simply add the decorator function above the function it has to be applied to. For this, we use the
@ symbol before the decorator.

Q9.What are Dict and List comprehensions?

Ans: Dictionary and list comprehensions are just another concise way to define dictionaries and
lists.

Example of list comprehension is-

1 x=[i for i in range(5)]

The above code creates a list as below-

1 4

2 [0,1,2,3,4]

Example of dictionary comprehension is-

1 x=[i : i+2 for i in range(5)]

The above code creates a list as below-

1 [0: 2, 1: 3, 2: 4, 3: 5, 4: 6]

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

Ans: The common built-in data types in python are-

Numbers– They include integers, floating-point numbers, and complex numbers. eg. 1, 7.9,3+4i

List– An ordered sequence of items is called a list. The elements of a list may belong to different
data types. Eg. [5,’market’,2.4]

Tuple– It is also an ordered sequence of elements. Unlike lists , tuples are immutable, which
means they can‟t be changed. Eg. (3,’tool’,1)

String– A sequence of characters is called a string. They are declared within single or double-
quotes. Eg. ‚Sana‛, ‘She is going to the market’, etc.

Set– Sets are a collection of unique items that are not in order. Eg. {7,6,8}
Dictionary– A dictionary stores values in key and value pairs where each value can be accessed
through its key. The order of items is not important. Eg. {1:’apple’,2:’mango}

Boolean– There are 2 boolean values- True and False.

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

Ans: The .py files are the python source code files. While the .pyc files contain the bytecode of
the python files. .pyc files are created when the code is imported from some other source. The
interpreter converts the source .py files to .pyc files which helps by saving time. You can get a
better understanding with the Data Engineering Course in Washington.

Q12.What is slicing in Python?

Ans: Slicing is used to access parts of sequences like lists, tuples, and strings. The syntax of
slicing is-[start:end:step]. The step can be omitted as well. When we write [start:end] this returns
all the elements of the sequence from the start (inclusive) till the end-1 element. If the start or
end element is negative i, it means the ith element from the end. The step indicates the jump or
how many elements have to be skipped. Eg. if there is a list- [1,2,3,4,5,6,7,8]. Then [-1:2:2] will
return elements starting from the last element till the third element by printing every second
element.i.e. [8,6,4].

Q13.What are Keywords in Python?

Ans: Keywords in python are reserved words that have special meaning.They are generally used
to define type of variables. Keywords cannot be used for variable or function names. There are
following 33 keywords in python-

 And
 Or
 Not
 If
 Elif
 Else
 For
 While
 Break
 As
 Def
 Lambda
 Pass
 Return
 True
 False
 Try
 With
 Assert
 Class
 Continue
 Del
 Except
 Finally
 From
 Global
 Import
 In
 Is
 None
 Nonlocal
 Raise
 Yield

Q14.What are Literals in Python and explain about different Literals

Ans: A literal in python source code represents a fixed value for primitive data types. There are 5
types of literals in python-

1. String literals– A string literal is created by assigning some text enclosed in single or double
quotes to a variable. To create multiline literals, assign the multiline text enclosed in triple
quotes. Eg.name=‛Tanya‛
2. A character literal– It is created by assigning a single character enclosed in double quotes.
Eg. a=’t’
3. Numeric literals include numeric values that can be either integer, floating point value, or a
complex number. Eg. a=50
4. Boolean literals– These can be 2 values- either True or False.
5. Literal Collections– These are of 4 types-

a) List collections-Eg. a=[1,2,3,’Amit’]

b) Tuple literals- Eg. a=(5,6,7,8)

c) Dictionary literals- Eg. dict={1: ’apple’, 2: ’mango, 3: ’banana`’}

d) Set literals- Eg. {‚Tanya‛, ‚Rohit‛, ‚Mohan‛}

6. Special literal- Python has 1 special literal None which is used to return a null variable.

Q15.How to combine dataframes in pandas?

Ans: The dataframes in python can be combined in the following ways-

1. Concatenating them by stacking the 2 dataframes vertically.


2. Concatenating them by stacking the 2 dataframes horizontally.
3. Combining them on a common column. This is referred to as joining.
The concat() function is used to concatenate two dataframes. Its syntax is- pd.concat([dataframe1,
dataframe2]).

Dataframes are joined together on a common column called a key. When we combine all the
rows in dataframe it is union and the join used is outer join. While, when we combine the
common rows or intersection, the join used is the inner join. Its syntax is- pd.concat([dataframe1,
dataframe2], axis=’axis’, join=’type_of_join)

Q16.What are the new features added in Python 3.9.0.0 version?

Ans: The new features in Python 3.9.0.0 version are-

 New Dictionary functions Merge(|) and Update(|=)


 New String Methods to Remove Prefixes and Suffixes
 Type Hinting Generics in Standard Collections
 New Parser based on PEG rather than LL1
 New modules like zoneinfo and graphlib
 Improved Modules like ast, asyncio, etc.
 Optimizations such as optimized idiom for assignment,
signal handling, optimized python built ins, etc.
 Deprecated functions and commands such as deprecated parser and symbol modules,
deprecated functions, etc.
 Removal of erroneous methods, functions, etc.

Q17. How is memory managed in Python?

Ans: Memory is managed in Python in the following ways:

1. Memory management in python is managed by Python private heap space. All Python objects
and data structures are located in a private heap. The programmer does not have access to this
private heap. The python interpreter takes care of this instead.
2. The allocation of heap space for Python objects is done by Python’s memory manager. The core
API gives access to some tools for the programmer to code.
3. Python also has an inbuilt garbage collector, which recycles all the unused memory and so that it
can be made available to the heap space.

Q18. What is namespace in Python?

Ans: A namespace is a naming system used to make sure that names are unique to avoid naming
conflicts.

Q19. What is PYTHONPATH?

Ans: It is an environment variable which is used when a module is imported. Whenever a


module is imported, PYTHONPATH is also looked up to check for the presence of the imported
modules in various directories. The interpreter uses it to determine which module to load.

Q20. What are python modules? Name some commonly used built-in modules in Python?

Ans: Python modules are files containing Python code. This code can either be functions classes
or variables. A Python module is a .py file containing executable code.

Some of the commonly used built-in modules are:

 os
 sys
 math
 random
 data time
 JSON

Q21.What are local variables and global variables in Python?

Global Variables:

Variables declared outside a function or in global space are called global variables. These
variables can be accessed by any function in the program.

Local Variables:

Any variable declared inside a function is known as a local variable. This variable is present in
the local space and not in the global space.

Example:

1 a=2

2 def add():

3 b=3

4 c=a+b

5 print(c)

add()
6

Output: 5

When you try to access the local variable outside the function add(), it will throw an error.

Q22. Is python case sensitive?


Ans: Yes. Python is a case sensitive language.

Q23.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,imag) – This function converts real numbers to complex(real,imag) number.

Q26. What is the difference between Python Arrays and lists?

Ans: Arrays and lists, in Python, have the same way of storing data. But, arrays can hold only a
single data type elements whereas lists can hold any data type elements.

Example:

1 import array as arr

2 My_Array=arr.array('i',[1,2,3,4])

3 My_list=[1,'abc',1.20]

4 print(My_Array)

print(My_list)
5

Output:
array(„i‟, [1, 2, 3, 4]) [1, „abc‟, 1.2]

Q27. What are functions in Python?

Ans: A function is a block of code which is executed only when it is called. To define a Python
function, the def keyword is used.

Example:

1 def Newfunc():

2 print("Hi, Welcome to Edureka")

3 Newfunc(); #calling the function

Output: Hi, Welcome to Edureka

Q28.What is __init__?

Ans: __init__ is a method or constructor in Python. This method is automatically called to


allocate memory when a new object/ instance of a class is created. All classes have the __init__
method.

Here is an example of how to use it.

1
class Employee:
2
def __init__(self, name, age,salary):
3
self.name = name
4 self.age = age

5 self.salary = 20000

6 E1 = Employee("XYZ", 23, 20000)

7 # E1 is the instance of class Employee.

#__init__ allocates memory for E1.


8
print(E1.name)
9
print(E1.age)
10
print(E1.salary)
11

Output:
XYZ

23

20000

Q29.What is a lambda function?

Ans: An anonymous function is known as a lambda function. This function can have any number
of parameters but, can have just one statement.

Example:

1 a = lambda x,y : x+y

2 print(a(5, 6))

Output: 11

Q30. What is self in Python?

Ans: Self is an instance or an object of a class. In Python, this is explicitly included as the first
parameter. However, this is not the case in Java where it‟s optional. It helps to differentiate
between the methods and attributes of a class with local variables.

The self variable in the init method refers to the newly created object while in other methods, it
refers to the object whose method was called.

Q31. How does break, continue and pass work?

Allows loop termination when some condition is met and the control is transferred to
Break
the next statement.

Allows skipping some part of a loop when some specific condition is met and the
Continue
control is transferred to the beginning of the loop

Used when you need some block of code syntactically, but you want to skip its
Pass
execution. This is basically a null operation. Nothing happens when this is executed.

Q32. What does [::-1} do?

Ans: [::-1] is used to reverse the order of an array or a sequence.

For example:
1 import array as arr

2 My_Array=arr.array('i',[1,2,3,4,5])

3 My_Array[::-1]

Output: array(„i‟, [5, 4, 3, 2, 1])

[::-1] reprints a reversed copy of ordered data structures such as an array or a list. the original array or
list remains unchanged.

['Flying', 'Keep', 'Blue', 'High', 'The', 'Flag']


Q34. What are python iterators?

Ans: Iterators are objects which can be traversed though or iterated upon.

Q35. How can you generate random numbers in Python?

Ans: Random module is the standard module that is used to generate a random number. The
method is defined as:

1 import random

2 random.random

The statement random.random() method return the floating-point number that is in the range of
[0, 1). The function generates random float numbers. The methods that are used with the random
class are the bound methods of the hidden instances. The instances of the Random can be done to
show the multi-threading programs that creates a different instance of individual threads. The
other random generators that are used in this are:

1. randrange(a, b): it chooses an integer and define the range in-between [a, b). It returns the
elements by selecting it randomly from the range that is specified. It doesn’t build a range
object.
2. uniform(a, b): it chooses a floating point number that is defined in the range of [a,b).Iyt returns
the floating point number
3. normalvariate(mean, sdev): it is used for the normal distribution where the mu is a mean and
the sdev is a sigma that is used for standard deviation.
4. The Random class that is used and instantiated creates independent multiple random number
generators.

Q39. What are the generators in python?

Ans: Functions that return an iterable set of items are called generators.
Q40. How will you capitalize the first letter of string?

Ans: In Python, the capitalize() method capitalizes the first letter of a string. If the string already
consists of a capital letter at the beginning, then, it returns the original string.

Q43.What are docstrings in Python?

Ans: Docstrings are not actually comments, but, they are documentation strings. These
docstrings are within triple quotes. They are not assigned to any variable and therefore, at times,
serve the purpose of comments as well.

Example:

1
"""
2 Using docstring as a comment.

3 This code divides 2 numbers

4 """

5 x=8

6 y=4

z=x/y
7
print(z)
8

Output: 2.0

Q44. What is the purpose of „is‟, „not‟ and „in‟ operators?

Ans: Operators are special functions. They take one or more values and produce a corresponding
result.

is: returns true when 2 operands are true (Example: “a” is „a‟)

not: returns the inverse of the boolean value

in: checks if some element is present in some sequence

Q46. Whenever Python exits, why isn’t all the memory de-allocated?

Ans:

1. Whenever Python exits, especially those Python modules which are having circular references to
other objects or the objects that are referenced from the global namespaces are not always de-
allocated or freed.
2. It is impossible to de-allocate those portions of memory that are reserved by the C library.
3. On exit, because of having its own efficient clean up mechanism, Python would try to de-
allocate/destroy every other object.

Q47. What is a dictionary in Python?

Ans: The built-in datatypes in Python is called dictionary. It defines one-to-one relationship
between keys and values. Dictionaries contain pair of keys and their corresponding values.
Dictionaries are indexed by keys.

Let‟s take an example:

The following example contains some keys. Country, Capital & PM. Their corresponding values
are India, Delhi and Modi respectively.

1 dict={'Country':'India','Capital':'Delhi','PM':'Modi'}

1 print dict[Country]

Output:India
1 print dict[Capital]

Output:Delhi
1 print dict[PM]

Output:Modi
Q48. 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.

Syntax:

The Ternary operator will be given as:


[on_true] if [expression] else [on_false]x, y = 25, 50big = x if x < y else y

Example:

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.

Q49. What does this mean: *args, **kwargs? And why would we use it?

Ans: We use *args when we aren‟t sure how many arguments are going to be passed to a
function, or if we want to pass a stored list or tuple of arguments to a function. **kwargs is used
when we don‟t know how many keyword arguments will be passed to a function, or it can be
used to pass the values of a dictionary as keyword arguments. The identifiers args and kwargs
are a convention, you could also use *bob and **billy but that would not be wise.

Q50. What does len() do?

Ans: It is used to determine the length of a string, a list, an array, etc.

Example:

1 stg='ABCD'

2 len(stg)

Output:4

Q51. Explain split(), sub(), subn() methods of “re” module in Python.

Ans: To modify the strings, Python‟s “re” module is providing 3 methods. They are:

 split() – uses a regex pattern to “split” a given string into a list.


 sub() – finds all substrings where the regex pattern matches and then replace them with a
different string
 subn() – it is similar to sub() and also returns the new string along with the no. of replacements.

Q53. What are Python packages?

Ans: Python packages are namespaces containing multiple modules.

Q54.How can files be deleted in Python?

Ans: To delete a file in Python, you need to import the OS Module. After that, you need to use
the os.remove() function.

Example:

1 import os

2 os.remove("xyz.txt")

Q55. What are the built-in types of python?

Ans: Built-in types in Python are as follows –

 Integers
 Floating-point
 Complex numbers
 Strings
 Boolean
 Built-in functions

Q56. What advantages do NumPy arrays offer over (nested) Python lists?

Ans:

1. Python’s lists are efficient general-purpose containers. They support (fairly) efficient insertion,
deletion, appending, and concatenation, and Python’s list comprehensions make them easy to
construct and manipulate.
2. They have certain limitations: they don’t support “vectorized” operations like elementwise
addition and multiplication, and the fact that they can contain objects of differing types mean
that Python must store type information for every element, and must execute type dispatching
code when operating on each element.
3. NumPy is not just more efficient; it is also more convenient. You get a lot of vector and matrix
operations for free, which sometimes allow one to avoid unnecessary work. And they are also
efficiently implemented.
4. NumPy array is faster and You get a lot built in with NumPy, FFTs, convolutions, fast searching,
basic statistics, linear algebra, histograms, etc.

Q57. How to add values to a python array?

Ans: Elements can be added to an array using the append(), extend() and the insert
(i,x) functions.

Example:

1
a=arr.array('d', [1.1 , 2.1 ,3.1] )
2 a.append(3.4)

3 print(a)

4 a.extend([4.5,6.3,6.8])

5 print(a)

a.insert(2,3.8)
6
print(a)
7

Output:

array(„d‟, [1.1, 2.1, 3.1, 3.4])


array(„d‟, [1.1, 2.1, 3.1, 3.4, 4.5, 6.3, 6.8])

array(„d‟, [1.1, 2.1, 3.8, 3.1, 3.4, 4.5, 6.3, 6.8])

Q58. How to remove values to a python array?

Ans: Array elements can be removed using pop() or remove() method. The difference between
these two functions is that the former returns the deleted value whereas the latter does not.

Example:

1 a=arr.array('d', [1.1, 2.2, 3.8, 3.1, 3.7, 1.2, 4.6])

2 print(a.pop())

3 print(a.pop(3))

4 a.remove(1.1)

print(a)
5

Output:

4.6

Python Certification Training Course

Weekday / We

3.1

array(„d‟, [2.2, 3.8, 3.7, 1.2])

Q59. Does Python have OOps concepts?


Ans: Python is an object-oriented programming language. This means that any program can be
solved in python by creating an object model. However, Python can be treated as a procedural as
well as structural language.

Q60. What is the difference between deep and shallow copy?

Ans: Shallow copy is used when a new instance type gets created and it keeps the values that are
copied in the new instance. Shallow copy is used to copy the reference pointers just like it copies
the values. These references point to the original objects and the changes made in any member of
the class will also affect the original copy of it. Shallow copy allows faster execution of the
program and it depends on the size of the data that is used.

Deep copy is used to store the values that are already copied. Deep copy doesn‟t copy the
reference pointers to the objects. It makes the reference to an object and the new object that is
pointed by some other object gets stored. The changes made in the original copy won‟t affect any
other copy that uses the object. Deep copy makes execution of the program slower due to making
certain copies for each object that is been called.

Q61. How is Multithreading achieved in Python?

Ans:

1. Python has a multi-threading package but if you want to multi-thread to speed your code up,
then it’s usually not a good idea to use it.
2. Python has a construct called the Global Interpreter Lock (GIL). The GIL makes sure that only one
of your ‘threads’ can execute at any one time. A thread acquires the GIL, does a little work, then
passes the GIL onto the next thread.
3. This happens very quickly so to the human eye it may seem like your threads are executing in
parallel, but they are really just taking turns using the same CPU core.
4. All this GIL passing adds overhead to execution. This means that if you want to make your code
run faster then using the threading package often isn’t a good idea.

Q63. What are Python libraries? Name a few of them.

Python libraries are a collection of Python packages. Some of the majorly used python libraries
are – Numpy, Pandas, Matplotlib, Scikit-learn and many more.

Q64. What is split used for?

The split() method is used to separate a given String in Python.

Example:

1 a="edureka python"
2 print(a.split())

Output: [„edureka‟, „python‟]

Q65. How to import modules in python?

Modules can be imported using the import keyword. You can import modules in three ways-

Example:

import array #importing using the original module name


1
import array as arr # importing using an alias name
2
from array import * #imports everything present in the array
3 module

Next, in this Python Interview Questions blog, let‟s have a look at Object Oriented Concepts in
Python.

OOPS Python Interview Questions


Q66. Explain Inheritance in Python with an example.

Ans: Inheritance allows One class to gain all the members(say attributes and methods) of another
class. Inheritance provides code reusability, makes it easier to create and maintain an application.
The class from which we are inheriting is called super-class and the class that is inherited is
called a derived / child class.

They are different types of inheritance supported by Python:

1. Single Inheritance – where a derived class acquires the members of a single super class.
2. Multi-level inheritance – a derived class d1 in inherited from base class base1, and d2 are
inherited from base2.
3. Hierarchical inheritance – from one base class you can inherit any number of child classes
4. Multiple inheritance – a derived class is inherited from more than one base class.

Q67. How are classes created in Python?

Ans: Class in Python is created using the class keyword.

Example:

1 class Employee:
2 def __init__(self, name):

3 self.name = name

E1=Employee("abc")
4
print(E1.name)
5

Output: abc

Q68. What is monkey patching in Python?

Ans: In Python, the term monkey patch only refers to dynamic modifications of a class or
module at run-time.

Consider the below example:

1 # m.py

2 class MyClass:

3 def f(self):

4 print "f()"

We can then run the monkey-patch testing like this:

1 import m

2 def monkey_f(self):

3 print "monkey_f()"

5 m.MyClass.f = monkey_f

6 obj = m.MyClass()

obj.f()
7

The output will be as below:

monkey_f()
As we can see, we did make some changes in the behavior of f() in MyClass using the function
we defined, monkey_f(), outside of the module m.

Q69. Does python support multiple inheritance?


Ans: Multiple inheritance means that a class can be derived from more than one parent classes.
Python does support multiple inheritance, unlike Java.

Q70. What is Polymorphism in Python?

Ans: Polymorphism means the ability to take multiple forms. So, for instance, if the parent class
has a method named ABC then the child class also can have a method with the same name ABC
having its own parameters and variables. Python allows polymorphism.

Q71. Define encapsulation in Python?

Ans: Encapsulation means binding the code and the data together. A Python class in an example
of encapsulation.

Q72. How do you do data abstraction in Python?

Ans: Data Abstraction is providing only the required details and hiding the implementation from
the world. It can be achieved in Python by using interfaces and abstract classes.

Q73.Does python make use of access specifiers?

Ans: Python does not deprive access to an instance variable or function. Python lays down the concept
of prefixing the name of the variable, function or method with a single or double underscore to imitate
the behavior of protected and private access specifiers.

Q74. How to create an empty class in Python?

Ans: An empty class is a class that does not have any code defined within its block. It can be created
using the pass keyword. However, you can create objects of this class outside the class itself. IN PYTHON
THE PASS command does nothing when its executed. it’s a null statement.

For example-

1 class a:

2 pass

3 obj=a()

4 obj.name="xyz"

print("Name = ",obj.name)
5

Output:

Name = xyz
Q75. What does an object() do?

Ans: It returns a featureless object that is a base for all classes. Also, it does not take any parameters.

Next, let us have a look at some Basic Python Programs in these Python Interview Questions.

Basic Python Programs – Python Interview Questions


Q76. Write a program in Python to execute the Bubble sort algorithm.

1
def bs(a):
2
# a = name of list
3 b=len(a)-1nbsp;

4 # minus 1 because we always compare 2 adjacent values

5 for x in range(b):

6 for y in range(b-x):

a[y]=a[y+1]
7

8
a=[32,5,3,6,7,54,87]
9
bs(a)
10

Output: [3, 5, 6, 7, 32, 54, 87]

Q79. Write a program in Python to check if a number is prime.

1 a=int(input("enter number"))

if a=1:
2
for x in range(2,a):
3
if(a%x)==0:
4
print("not prime")
5
break
6
else:
7 print("Prime")
8 else:

9 print("not prime")

10

Output:

enter number 3

Prime

Q80. Write a program in Python to check if a sequence is a Palindrome.

1 a=input("enter sequence")

2 b=a[::-1]

3 if a==b:

4 print("palindrome")

5 else:

print("Not a Palindrome")
6

Output:

enter sequence 323 palindrome

Q81. Write a one-liner that will count the number of capital letters in a file. Your
code should work even if the file is too big to fit in memory.

Ans: Let us first write a multiple line solution and then convert it to one-liner code.

1 with open(SOME_LARGE_FILE) as fh:

2 count = 0

3 text = fh.read()

4 for character in text:

5 if character.isupper():

count += 1
6

We will now try to transform this into a single line.


count sum(1 for line in fh for character in line if
1
character.isupper())

Q82. Write a sorting algorithm for a numerical dataset in Python.

Ans: The following code can be used to sort a list in Python:

1 list = ["1", "4", "0", "6", "9"]

2 list = [int(i) for i in list]

3 list.sort()

4 print (list)

Q83. Looking at the below code, write down the final values of A0, A1, …An.

1
A0 = dict(zip(('a','b','c','d','e'),(1,2,3,4,5)))
2 A1 = range(10)A2 = sorted([i for i in A1 if i in A0])

3 A3 = sorted([A0[s] for s in A0])

4 A4 = [i for i in A1 if i in A3]

5 A5 = {i:i*i for i in A1}

A6 = [[i,i*i] for i in A1]


6
print(A0,A1,A2,A3,A4,A5,A6)
7

Ans: The following will be the final outputs of A0, A1, … A6

A0 = {'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4} # the order may vary


A1 = range(0, 10)
A2 = []
A3 = [1, 2, 3, 4, 5]
A4 = [1, 2, 3, 4, 5]
A5 = {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
A6 = [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8, 64], [9, 81]]

Next, in this Python Interview Questions let's have a look at some Python Libraries

Python Libraries – Python Interview Questions


Web Scraping – Python Interview Questions
Q93. How To Save An Image Locally Using Python Whose URL Address I
Already Know?
Ans: We will use the following code to save an image locally from an URL address

1 import urllib.request

2 urllib.request.urlretrieve("URL", "local-filename.jpg")

Q94. How can you Get the Google cache age of any URL or web page?

Ans: Use the following URL format:

Be sure to replace “URLGOESHERE” with the proper web address of the page or site whose
cache you want to retrieve and see the time for. For example, to check the Google Webcache age
of edureka.co you‟d use the following URL:

Data Analysis – Python Interview Questions


Q96. What is map function in Python?

Ans: map function executes the function given as the first argument on all the elements of the
iterable given as the second argument. If the function given takes in more than 1 arguments, then
many iterables are given. #Follow the link to know more similar functions.

Q97. Is python numpy better than lists?

Ans: We use python numpy array instead of a list because of the below three reasons:

1. Less Memory
2. Fast
3. Convenient

For more information on these parameters, you can refer to this section – Numpy Vs List.

Q98. How to get indices of N maximum values in a NumPy array?

Ans: We can get the indices of N maximum values in a NumPy array using the below code:

1 import numpy as np

2 arr = np.array([1, 3, 2, 4, 5])

3 print(arr.argsort()[-3:][::-1])

Output

[ 4 3 1 ]
File Handling in Python Interview Questions and Answers
1. What is file handling in Python?

File handling is the process of reading, writing, and manipulating files in Python. This can be done with the built-in
open() function, which takes two arguments: the path to the file and the mode in which to open it. The mode
argument specifies how the file should be opened, and can be „r‟ for reading, „w‟ for writing, or „a‟ for appending.

2. Can you explain the different modes of opening a file in Python?

There are three different modes of opening a file in Python: read mode, write mode, and append mode. Read mode is
the default mode and allows you to read the contents of a file. Write mode will allow you to write to a file, and append
mode will allow you to add new data to the end of an existing file.

3. How do you create a text file using Python?

You can create a text file using Python by opening a new file in write mode. This will allow you to write data to the file.

4. How do you read and write to an existing file in Python?

To read an existing file in Python, you can use the built-in open() function. This function takes two arguments: the
name of the file to read, and the mode in which to open the file. The mode argument is optional, but it allows you to
specify how you want to interact with the file. The most common mode is „r‟, which stands for read-only. To write to an
existing file, you can use the same open() function, but you must specify the „w‟ mode argument. This will allow you to
write to the file.

5. Is it possible to open multiple files using Python? If yes, then how?

Yes, it is possible to open multiple files using Python. You can do this by using the built-in open() function. When you
call open(), you can specify the mode in which you want to open the file, as well as the name of the file. If you want to
open multiple files, you can do so by passing a list of filenames to open().

6. How should you handle exceptions when dealing with files in Python?

When working with files in Python, it is important to be aware of potential exceptions that could be raised. Some
common exceptions include IOError, which is raised when there is an error reading or writing to a file, and
ValueError, which is raised when there is an issue with the format of the data in the file. It is important to handle these
exceptions appropriately in order to avoid potential data loss or corruption.

7. What are some important methods used for reading from a file in Python?

Some important methods used for reading from a file in Python are the read() and readline() methods. The read()
method reads the entire contents of a file into a string, while the readline() method reads a single line from a file.

9. What‟s the difference between binary and text files in Python?


Binary files are files that are not meant to be read by humans – they are meant to be read by computers. Binary files
are typically faster to read and write than text files because the computer can read the entire file in one go, without
having to stop to process the data. Text files, on the other hand, are meant to be read by humans. They are typically
slower to read and write than binary files because the computer has to stop to process the data.

10. Why is it not recommended to use pickle or cPickle modules for serializing objects into a
file?

The pickle and cPickle modules are not recommended for use because they are insecure. Because these modules
can execute arbitrary code, they could be used by an attacker to compromise the security of your system.

11. Which functions allow us to check if we have reached the end of a file in Python?

The functions that allow us to check if we have reached the end of a file in Python are the eof() and tell() functions.
The eof() function returns true if we have reached the end of the file, and the tell() function returns the current position
of the file pointer.

12. When trying to open a file in Python, I get the error “FileNotFoundError: [Errno 2] No such
file or directory”. What could be the cause of this issue?

There are a few potential causes for this error. The first is that the file you are trying to open does not actually exist in
the directory you are looking in. The second is that you do not have permission to access the file. The third is that the
file is already open by another process.

13. How can you convert a CSV file to a dataframe in Pandas?

You can use the read_csv() function in Pandas to convert a CSV file to a dataframe.

14. How can you sort a list of strings alphabetically without using sorted()?

You can use the “sort” method.

15. List down the steps involved in processing a large file in Python?

There are a few steps involved in processing a large file in Python:

1. Open the file using the open() function.


2. Read in the file using either the read() or readline() function.
3. Process the data in the file as needed.
4. Close the file using the close() function.

16. What does the following code snippet do?

The following code snippet opens the file “myfile.txt” for reading, and then reads in the contents of the file line by line,
printing each line out as it goes.

17. a = open(“file”, „w‟)

The open() function opens the file in write mode. The „w‟ character stands for write. The file will be created if it doesn‟t
exist. If it exists, the data in the file will be overwritten.

21. What is the usage of yield keyword in Python?


The yield keyword is used in Python to define generators. Generators are a special type of function that allow the
programmer to return values one at a time, rather than returning all values at once. This can be useful when working
with large data sets, as it allows the programmer to process the data one piece at a time, rather than having to load
the entire data set into memory at once.

22. What is the purpose of enumerate() function in Python?

The enumerate() function is used to iterate over a list of items, while keeping track of the index of each item in the list.
This can be useful when you need to know not only the contents of the list, but also where each item is located in the
list.

23.What are Pickling and Unpickling?

Pickling Unpickling

 Converting a byte stream to


 Converting a Python object hierarchy to a byte a Python object hierarchy is
stream is called pickling called unpickling

 Pickling is also referred to as serialization  Unpickling is also referred to


as deserialization

If you just created a neural network model, you can save that model to your hard drive, pickle it, and then unpickle to
bring it back into another software program or to use it at a later time.

24. What Is the Difference Between Del and Remove() on Lists?

del remove()

 remove() removes the first


 del removes all elements of a list within a given
occurrence of a particular
range
character
 Syntax: del list[start:end]
 Syntax: list.remove(element)

Here is an example to understand the two statements -

>>lis=[„a‟, „b‟, „c‟, „d‟]

>>del lis[1:3]

>>lis

Output: [“a”,”d”]
>>lis=[„a‟, „b‟, „b‟, „d‟]

>>lis.remove(„b‟)

>>lis

Output: [„a‟, „b‟, „d‟]

Note that in the range 1:3, the elements are counted up to 2 and not 3.

25.Differentiate Between append() and extend().

append() extend()

 extend() adds elements from


 append() adds an element to the end of the list an iterable to the end of the
list
 Example -
 Example -
>>lst=[1,2,3]
>>lst=[1,2,3]
>>lst.append(4)
>>lst.extend([4,5,6])
>>lst
>>lst
Output:[1,2,3,4]
Output:[1,2,3,4,5,6]

26.What Are *args and *kwargs?

*args

 It is used in a function prototype to accept a varying number of arguments.

 It's an iterable object.

 Usage - def fun(*args)

*kwargs

 It is used in a function prototype to accept the varying number of keyworded arguments.


 It's an iterable object

 Usage - def fun(**kwargs):

fun(colour=”red”.units=2)

27. What Is a Numpy Array?


A numpy array is a grid of values, all of the same type, and is indexed by a tuple of non-negative integers. The
number of dimensions determines the rank of the array. The shape of an array is a tuple of integers giving the size of
the array along each dimension.

28.What are Python modules? Name a few Python built-in modules that are
often used.
Python modules are files that contain Python code. Functions, classes, or variables can be used in this code. A
Python module is a .py file that contains code that may be executed. The following are the commonly used built-in
modules:

 JSON

 data time

 random

 math

 sys

 OS

 29. What is the purpose of „not‟, „is‟, and „in‟ operators?

 Special functions are known as operators. They take one or more input values and output a result.

 not- returns the boolean value's inverse

 is- returns true when both operands are true

 in- determines whether a certain element is present in a series


HA Kubernetes and 99.95% uptime SLA? Yes, please! ->

Python Data Types


There are different types of data types in Python. Some built-in Python data types are:

 Numeric data types: int, float, complex


 String data types: str
 Sequence types: list, tuple, range
 Binary types: bytes, bytearray, memoryview
 Mapping data type: dict
 Boolean type: bool
 Set data types: set, frozenset
1. Python Numeric Data Type
Python numeric data type is used to hold numeric values like;

1. int - holds signed integers of non-limited length.


2. long- holds long integers(exists in Python 2.x, deprecated in Python 3.x).
3. float- holds floating precision numbers and it‟s accurate up to 15 decimal places.
4. complex- holds complex numbers.

In Python, we need not declare a datatype while declaring a variable like C or C++. We can simply just assign values
in a variable. But if we want to see what type of numerical value is it holding right now, we can use type(), like this:

#create a variable with integer value.

a=100

print("The type of variable having value", a, " is ", type(a))

#create a variable with float value.

b=10.2345

print("The type of variable having value", b, " is ", type(b))

#create a variable with complex value.

c=100+3j

print("The type of variable having value", c, " is ", type(c))

If you run the above code you will see output like the below image.
2. Python String Data Type
The string is a sequence of characters. Python supports Unicode characters. Generally, strings are represented by
either single or double-quotes.

a = "string in a double quote"

b= 'string in a single quote'

print(a)

print(b)

# using ',' to concatenate the two or several strings

print(a,"concatenated with",b)

#using '+' to concate the two or several strings

print(a+" concated with "+b)

The above code produces output like the below picture-


3. Python List Data Type
The list is a versatile data type exclusive in Python. In a sense, it is the same as the array in C/C++. But the
interesting thing about the list in Python is it can simultaneously hold different types of data. Formally list is an
ordered sequence of some data written using square brackets([]) and commas(,).

#list of having only integers

a= [1,2,3,4,5,6]

print(a)

#list of having only strings

b=["hello","john","reese"]

print(b)

#list of having both integers and strings

c= ["hey","you",1,2,3,"go"]

print(c)

#index are 0 based. this will print a single character


print(c[1]) #this will print "you" in list c

The above code will produce output like this-

4. Python Tuple
The tuple is another data type which is a sequence of data similar to a list. But it is immutable. That means data in a
tuple is write-protected. Data in a tuple is written using parenthesis and commas.

#tuple having only integer type of data.

a=(1,2,3,4)

print(a) #prints the whole tuple

#tuple having multiple type of data.

b=("hello", 1,2,3,"go")

print(b) #prints the whole tuple

#index of tuples are also 0 based.

print(b[4]) #this prints a single element in a tuple, in this case "go"

The output of this above python data type tuple example code will be like the below image.
5. Python Dictionary
Python Dictionary is an unordered sequence of data of key-value pair form. It is similar to the hash table type.
Dictionaries are written within curly braces in the form key:value. It is very useful to retrieve data in an optimized way
among a large amount of data.

#a sample dictionary variable

a = {1:"first name",2:"last name", "age":33}

#print value having key=1

print(a[1])

#print value having key=2

print(a[2])

#print value having key="age"

print(a["age"])

If you run this python dictionary data type example code, the output will be like the below image.

You might also like