Top Python Interview Questions and Answers

Last updated on Feb 18 2022
Shankar Shankar Trivedi

Table of Contents

Top Python Interview Questions and Answers

How is Memory managed in Python?

Python has a private heap space that stores all the objects. The Python memory manager regulates various aspects of this heap, such as sharing, caching, segmentation, and allocation. The user has no control over the heap; only the Python interpreter has access.

How Is Multithreading Achieved in Python?

Multithreading usually implies that multiple threads are executed concurrently. The Python Global Interpreter Lock doesn’t allow more than one thread to hold the Python interpreter at that particular point of time. So, multithreading in python is achieved through context switching. It is quite different from multiprocessing which actually opens up multiple processes across multiple threads.

What is the Difference Between a Shallow Copy and Deep Copy?

Deepcopy creates a different object and populates it with the child objects of the original object. Therefore, changes in the original object are not reflected in the copy.

copy.deepcopy() creates a Deep Copy.

Shallow copy creates a different object and populates it with the references of the child objects within the original object. Therefore, changes in the original object are reflected in the copy.

copy.copy creates a Shallow Copy.

Discuss Django Architecture.

Django is a web service used to build your web pages. Its architecture is as shown.

  • Template. the front end of the web page
  • Model. the back end where the data is stored
  • View. It interacts with the model and template and maps it to the URL
  • Django. serves the page to the user

What Advantage Does the Numpy Array Have over a Nested List?

Numpy is written in C so that all its complexities are backed into a simple to use a module. Lists, on the other hand, are dynamically typed. Therefore, Python must check the data type of each element every time it uses it. This makes Numpy arrays much faster than lists.

Numpy has a lot of additional functionality that list doesn’t offer; for instance, a lot of things can be automated in Numpy.

What are Pickling and Unpickling?

Pickling  Unpickling 
  • Converting a Python object hierarchy to a byte stream is called pickling
  • Pickling is also referred to as serialization
  • Converting a byte stream to a Python object hierarchy is called unpickling
  • 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.

Are Arguments in Python Passed by Value or by Reference?

Arguments are passed in python by a reference. This means that any changes made within a function are reflected in the original object.

Consider two sets of code shown below.

In the first example, we only assigned a value to one element of ‘l’, so the output is [, , , ].

In the second example, we have created a whole new object for ‘l’. But, the values [, , , ] doesn’t show up in the output as it is outside the definition of the function.

How Would You Generate Random Numbers in Python?

To generate random numbers in Python, you must first import the random module.

The random() function generates a random float value between & .

> random.random()

The randrange() function generates a random number within a given range.

Syntax. randrange(beginning, end, step)

Example – > random.randrange(,,)

What Does the // Operator Do?

In Python, the / operator performs division and returns the quotient in the float.

For example. / returns .

The // operator, on the other hand, returns the quotient in integer.

For example. // returns

What Does the ‘is’ Operator Do?

The ‘is’ operator compares the id of the two objects.

list=[,,]

list=[,,]

list=list

list == list 🡪 True

list is list 🡪 False

list is list 🡪 True

What Is the Purpose of the Pass Statement?

The pass statement is used when there’s a syntactic but not an operational requirement. For example – The program below prints a string ignoring the spaces.

var="Te cklea rn"
for i in var.
if i==" ".
pass
else.
print(i,end="")

Here, the pass statement refers to ‘no action required.’

How Will You Check If All the Characters in a String Are Alphanumeric?

Python has an inbuilt method isalnum() which returns true if all characters in the string are alphanumeric.

Example –

>> “abcd”.isalnum()

Output. True

>>”abcd@#”.isalnum()

Output. False

Another way is to use regex as shown.

>>import re

>>bool(re.match(‘[A-Za-z-]+$’,’abcd’))

Output. True

>> bool(re.match(‘[A-Za-z-]+$’,’abcd@’))

Output. False

How Will You Merge Elements in a Sequence?

There are three types of sequences in Python.

  • Lists
  • Tuples
  • Strings

Example of Lists –

>>l=[,,]

>>l=[,,]

>>l+l

Output. [,,,,,]

Example of Tuples –

>>t=(,,)

>>t=(,,)

>>t+t

Output. (,,,,,)

Example of String –

>>s=“Teck”

>>s=“learn”

>>s+s

Output. ‘Tecklearn’

How Would You Remove All Leading Whitespace in a String?

Python provides the inbuilt function lstrip() to remove all leading spaces from a string.

>>“      Python”.lstrip

Output. Python

How Would You Replace All Occurrences of a Substring with a New String?

The replace() function can be used with strings for replacing a substring with a given string. Syntax.

str.replace(old, new, count)

replace() returns a new string without modifying the original string.

Example –

>>”Hey John. How are you, John?”.replace(“john”,“John”,)

Output. “Hey John. How are you, John?

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

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

Here is an example to understand the two statements –

>>lis=[‘a’, ‘b’, ‘c’, ‘d’]

>>del lis[.]

>>lis

Output. [“a”,”d”]

>>lis=[‘a’, ‘b’, ‘b’, ‘d’]

>>lis.remove(‘b’)

>>lis

Output. [‘a’, ‘b’, ‘d’]

Note that in the range ., the elements are counted up to and not .

How Do You Display the Contents of a Text File in Reverse Order?

You can display the contents of a text file in reverse order using the following steps.

  • Open the file using the open() function
  • Store the contents of the file into a list
  • Reverse the contents of the list
  • Run a for loop to iterate through the list

Differentiate Between append() and extend().

append() extend()
  • append() adds an element to the end of the list
  • Example –

>>lst=[,,]

>>lst.append()

>>lst

Output.[,,,]

  • extend() adds elements from an iterable to the end of the list
  • Example –

>>lst=[,,]

>>lst.extend([,,])

>>lst

Output.[,,,,,]

What Is the Output of the below Code? Justify Your

>>def addToList(val, list=[]).

>> list.append(val)

>> return list

>>list = addToList()

>>list = addToList(,[])

>>list = addToList(‘a’)

>>print (“list = %s” % list)

>>print (“list = %s” % list)

>>print (“list = %s” % list)

Output.

list = [,’a’]

list = []

lilst = [,’a’]

Note that list and list are equal. When we passed the information to the addToList, we did it without a second value. If we don’t have an empty list as the second value, it will start off with an empty list, which we then append. For list, we appended the value to an empty list, so its value becomes [].

For list, we’re adding ‘a’ to the list. Because we didn’t designate the list, it is a shared value. It means the list doesn’t reset and we get its value as [, ‘a’].

Remember that a default list is created only once during the function and not during its call number.

What Is the Difference Between a List and a Tuple?

Lists are mutable while tuples are immutable.

Example.

List 

>>lst = [,,]

>>lst[] =

>>lst

Output.[,,]

Tuple 

>>tpl = (,,)

>>tpl[] =

>>tpl

Output.TypeError. ‘tuple’

the object does not support item

assignment

There is an error because you can’t change the tuple into . You have to completely reassign tuple to a new value.

What Is Docstring in Python?

Docstrings are used in providing documentation to various Python modules, classes, functions, and methods.

Example –

def add(a,b).

” ” “This function adds two numbers.” ” “

sum=a+b

return sum

sum=add(,)

print(“Accessing doctstring method .”,add.__doc__)

print(“Accessing doctstring method .”,end=””)

help(add)

Output –

Accessing docstring method . This function adds two numbers.

Accessing docstring method . Help on function add-in module __main__.

add(a, b)

This function adds two numbers.

How Do You Use Print () Without the Newline?

The solution to this depends on the Python version you are using.

Python v

>>print(“Hi. ”),

>>print(“How are you?”)

Output. Hi. How are you?

Python v

>>print(“Hi”,end=“ ”)

>>print(“How are you?”)

Output. Hi. How are you?

How Do You Use the Split() Function in Python?

The split() function splits a string into a number of strings based on a specific delimiter.

Syntax –

string.split(delimiter, max)

Where.

the delimiter is the character based on which the string is split. By default it is space.

max is the maximum number of splits

Example –

>>var=“Red,Blue,Green,Orange”

>>lst=var.split(“,”,)

>>print(lst)

Output.

[‘Red’,’Blue’,’Green, Orange’]

Here, we have a variable var whose values are to be split with commas. Note that ‘’ indicates that only the first two values will be split.

Is Python Object-oriented or Functional Programming?

Python is considered a multi-paradigm language.

Python follows the object-oriented paradigm

  • Python allows the creation of objects and their manipulation through specific methods
  • It supports most of the features of OOPS such as inheritance and polymorphism

Python follows the functional programming paradigm

  • Functions may be used as the first-class object
  • Python supports Lambda functions which are characteristic of the functional paradigm

Write a Function Prototype That Takes a Variable Number of Arguments.

The function prototype is as follows.

def function_name(*list)

>>def fun(*var).

>> for i in var.

print(i)

>>fun()

>>fun(,,)

In the above code, * indicates that there are multiple arguments of a variable.

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=)

in Python, Functions Are First-class Objects.” What Do You Infer from This?

It means that a function can be treated just like an object. You can assign them to variables, or pass them as arguments to other functions. You can even return them from other functions.

What Is the Output Of. Print(__name__)? Justify Your

__name__ is a special variable that holds the name of the current module. Program execution starts from main or code with indentations. Thus, __name__ has a value __main__ in the above case. If the file is imported from another module, __name__ holds the name of this module.

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.

What Is the Difference Between Matrices and Arrays?

Matrices Arrays
  • A matrix comes from linear algebra and is a two-dimensional representation of data
  • It comes with a powerful set of mathematical operations that allow you to manipulate the data in interesting ways
  • An array is a sequence of objects of similar data type
  • An array within another array forms a matrix

How Do You Get Indices of N Maximum Values in a Numpy Array?

>>import numpy as np

>>arr=np.array([, , , , ])

>>print(arr.argsort( ) [ -N. ][. . -])

How Would You Obtain the Res_set from the Train_set and the Test_set from Below?

>>train_set=np.array([, , ])

>>test_set=np.array([[, , ], [, , ])

Res_set 🡪 [[, , ], [, , ], [, , ]]

Choose the correct option.

  1. res_set = train_set.append(test_set)
  2. res_set = np.concatenate([train_set, test_set]))
  3. resulting_set = np.vstack([train_set, test_set])
  4. None of these

Here, options a and b would both do horizontal stacking, but we want vertical stacking. So, option c is the right statement.

resulting_set = np.vstack([train_set, test_set])

How Would You Import a Decision Tree Classifier in Sklearn? Choose the Correct Option.

  1. from sklearn.decision_tree import DecisionTreeClassifier
  2. from sklearn.ensemble import DecisionTreeClassifier
  3. from sklearn.tree import DecisionTreeClassifier
  4. None of these

Answer – . from sklearn.tree import DecisionTreeClassifier

You Have Uploaded the Dataset in Csv Format on Google Spreadsheet and Shared It Publicly. How Can You Access This in Python?

We can use the following code.

>>link = https.//docs.google.com/spreadsheets/d/…

>>source = StringIO.StringIO(requests.get(link).content))

>>data = pd.read_csv(source)

What Is the Difference Between the Two Data Series given Below?

df[‘Name’] and df.loc[., ‘Name’], where.

df = pd.DataFrame([‘aa’, ‘bb’, ‘xx’, ‘uu’], [, , , ], columns = [‘Name’, ‘Age’])

Choose the correct option.

  1. is the view of original dataframe and is a copy of original dataframe
  2. is the view of original dataframe and is a copy of original dataframe
  3. Both are copies of original dataframe
  4. Both are views of original dataframe

Answer – . Both are copies of the original dataframe.

You Get the Error “temp.Csv” While Trying to Read a File Using Pandas. Which of the Following Could Correct It?

Error.

Traceback (most recent call last). File “<input>”, line , in<module> UnicodeEncodeError.

‘ascii’ codec can’t encode character.

Choose the correct option.

  1. pd.read_csv(“temp.csv”, compression=’gzip’)
  2. pd.read_csv(“temp.csv”, dialect=’str’)
  3. pd.read_csv(“temp.csv”, encoding=’utf-′)
  4. None of these

The error relates to the difference between utf- coding and a Unicode.

So option . pd.read_csv(“temp.csv”, encoding=’utf-′) can correct it.

How Do You Set a Line Width in the Plot given Below?

>>import matplotlib.pyplot as plt

>>plt.plot([,,,])

>>plt.show()

Choose the correct option.

  1. In line two, write plt.plot([,,,], width=)
  2. In line two, write plt.plot([,,,], line_width=
  3. In line two, write plt.plot([,,,], lw=)
  4. None of these

Answer – . In line two, write plt.plot([,,,], lw=)

How Would You Reset the Index of a Dataframe to a given List? Choose the Correct Option.

  1. df.reset_index(new_index,)
  2. df.reindex(new_index,)
  3. df.reindex_like(new_index,)
  4. None of these

Answer – . df.reindex_like(new_index,)

How Can You Copy Objects in Python?

The function used to copy objects in Python are.

copy.copy for shallow copy and

copy.deepcopy() for deep copy

What Is the Difference Between range() and xrange() Functions in Python?

range() xrange()
  • range returns a Python list object
  • xrange returns an xrange object

How Can You Check Whether a Pandas Dataframe Is Empty or Not?

The attribute df.empty is used to check whether a pandas data frame is empty or not.

>>import pandas as pd

>>df=pd.DataFrame({A.[]})

>>df.empty

Output. True

Write a Code to Sort an Array in Numpy by the (N-)Th Column.

This can be achieved by using argsort() function. Let us take an array X; the code to sort the (n-)th column will be x[x [. n-].argsoft()]

The code is as shown below.

>>import numpy as np

>>X=np.array([[,,],[,,],[,,]])

>>X[X[.,].argsort()]

Output.array([[,,],[,,],[,,]])

How Do You Create a Series from a List, Numpy Array, and Dictionary?

The code is as shown.

>> #Input

>>import numpy as np

>>import pandas as pd

>>mylist = list(‘abcedfghijklmnopqrstuvwxyz’)

>>myarr = np.arange()

>>mydict = dict(zip(mylist, myarr))

>> #Solution

>>ser = pd.Series(mylist)

>>ser = pd.Series(myarr)

>>ser = pd.Series(mydict)

>>print(ser.head())

How Do You Get the Items Not Common to Both Series a and Series B?

>> #Input

>>import pandas as pd

>>ser = pd.Series([, , , , ])

>>ser = pd.Series([, , , , ])

>> #Solution

>>ser_u = pd.Series(np.uniond(ser, ser)) # union

>>ser_i = pd.Series(np.intersectd(ser, ser)) # intersect

>>ser_u[~ser_u.isin(ser_i)]

How Do You Keep Only the Top Two Most Frequent Values as It Is and Replace Everything Else as ‘other’ in a Series?

>> #Input

>>import pandas as pd

>>np.random.RandomState()

>>ser = pd.Series(np.random.randint(, , []))

>> #Solution

>>print(“Top Freq.”, ser.value_counts())

>>ser[~ser.isin(ser.value_counts().index[.])] = ‘Other’

>>ser

How Do You Find the Positions of Numbers That Are Multiples of Three from a Series?

>> #Input

>>import pandas as pd

>>ser = pd.Series(np.random.randint(, , ))

>>ser

>> #Solution

>>print(ser)

>>np.argwhere(ser % ==)

How Do You Compute the Euclidean Distance Between Two Series?

The code is as shown.

>> #Input

>>p = pd.Series([, , , , , , , , , ])

>>q = pd.Series([, , , , , , , , , ])

>> #Solution

>>sum((p – q)**)**.

>> #Solution using func

>>np.linalg.norm(p-q)

You can see that the Euclidean distance can be calculated using two ways.

How Do You Reverse the Rows of a Data Frame?

>> #Input

>>df = pd.DataFrame(np.arange().reshape(, -))

>> #Solution

>>df.iloc[..-, .]

If You Split Your Data into Train/Test Splits, Is It Possible to over Fit Your Model?

Yes. One common beginner mistake is re-tuning a model or training new models with different parameters after seeing its performance on the test set.

Which Python Library Is Built on Top of Matplotlib and Pandas to Ease Data Plotting?

Seaborn is a Python library built on top of matplotlib and pandas to ease data plotting. It is a data visualization library in Python that provides a high-level interface for drawing statistical informative graphs.

What is Python?

Python is a high-level and object-oriented programming language with unified semantics designed primarily for developing apps and the web. It is the core language in the field of Rapid Application Development (RAD) as it offers options such as dynamic binding and dynamic typing.

What are the benefits of Python?

The benefits of Python are as follows.

  • Speed and Productivity. Utilizing the productivity and speed of Python will enhance the process control capabilities and possesses strong integration.
  • Extensive Support for Libraries. Python provides a large standard library that includes areas such as operating system interfaces, web service tools, internet protocols, and string protocols. Most of the programming tasks are already been scripted in the standard library which reduces effort and time.
  • User-friendly Data Structures. Python has an in-built dictionary of data structures that are used to build fast user-friendly data structures.
  • Existence of Third Party Modules. The presence of third party modules in the Python Package Index (PyPI) will make Python capable to interact with other platforms and languages.
  • Easy Learning. Python provides excellent readability and simple syntaxes to make it easy for beginners to learn.

What are the key features of Python?

The following are the significant features of Python, and they are.

  • Interpreted Language. Python is an interpreted language that is used to execute the code line by line at a time. This makes debugging easy.
  • Highly Portable. As Python can run on different platforms such as Unix, Macintosh, Linux, Windows, and so on. So, we can say that it is a highly portable language.
  • Extensible. It ensures that the Python code can be compiled on various other languages such as C, C++ and so on.
  • GUI programming Support. It implies that Python provides support to develop graphical user interfaces

What type of language is Python? Programming or Scripting?

Python is suitable for scripting, but in general it is considered as a general-purpose programming language.

What are the applications of Python?

The applications of Python are as follows.

  • GUI based desktop applications
  • Image processing applications
  • Business and Enterprise applications
  • Prototyping
  • Web and web framework applications

What is the difference between list and tuple in Python?

The difference between tuple and list are as follows.

List  Tuple
The list is mutable (can be changed) A tuple is immutable (remains constant)
These lists performance is slower Tuple performance is faster when compared to lists
Syntax. list_ = [, ‘Mindmajix’, ] Syntax. tup_ = (, ‘Mindmajix’, )

What are the global and local variables in Python?

Global Variables in Python. The variables that are declared outside the function are called global variables. These variables can be accessed or invoked by any function in the program.

Example. 

 

 

 

 

def v() .

print g

g = “welcome to mindmajix”

v()

Output.

Welcome to mindmajix

Local Variables in Python. The variables that are declared inside a function are called local variables. These type of variables can be accessed only inside the function.

Define PYTHON PATH?

PYTHONPATH is an environmental variable that is used when we import a module. Suppose at any time we import a module, PYTHONPATH is used to check the presence of the modules that are imported in different directories. Loading of the module will be determined by interpreters.

Java vs Python

The major difference between Java and Python are as follows.

Function Java  Python
Coding In Java, we need to write a long code to print something. In Python coding is simple and smaller when compared to Java
Syntax In Java we need to put a semicolon at the end of the statement and also code must be placed in curly braces. Whereas, in Python indentation is mandatory as it improves the readability of the code.
Dynamic In Java, we need to declare the type for each variable In this case, codes are dynamically typed and this is also known as duck typing
Easy to use Java is not easy to use because of its larger coding In Python, it is very easy to code and perform very easily.
Databases Java Database Connectivity (JDBC) is more popular and used most commonly. In Python database access layers are weaker when compared to Java.

Define modules in Python?

Module is defined as a file that includes a set of various functions and Python statements that we want to add in our application.

Example of creating` a module. 

In order to create a module first, we need to save the code that we want in a file with .py extension.

Save the module with module.py

 

 

def wishes(name).

Print(“Hi, ” + name)

What are the built-in types available in Python?

The built-in types in Python are as follows.

  • Integer
  • Complex numbers
  • Floating-point numbers
  • Strings
  • Built-in functions

What are Python Decorators?

Decorator is the most useful tool in Python as it allows programmers to alter the changes in the behavior of class or function.

An example for Python Decorator is.

 

 

 

@gfg_decorator

def hi_decorator().

print(“Gfg”)

How do we find bugs and statistical problems in Python?

We can detect bugs in python source code using a static analysis tool named PyChecker. Moreover, there is another tool called PyLint that checks whether the Python modules meet their coding standards or not.

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

.py files are Python source files. .pyc files are the compiled bytecode files that are generated by the Python compiler

How do you invoke the Python interpreter for interactive use?

By using python or pythonx.y we can invoke Python interpreter. where x.y is the version of the Python interpreter.

Define String in Python?

String in Python is formed using a sequence of characters. Value once assigned to a string cannot be modified because they are immutable objects. String literals in Python can be declared using double quotes or single quotes.

Example.

 

 

print(“Hi”)

print(‘Hi’)

What do you understand by the term namespace in Python?

A namespace in Python can be defined as a system that is designed to provide a unique name for every object in python. Types of namespaces that are present in Python are.

  • Local namespace
  • Global namespace
  • Built-in namespace

Scope of an object in Python. 

Scope refers to the availability and accessibility of an object in the coding region.

How do you create a Python function?

Functions are defined using the def statement.

An example might be def foo(bar)

What happens when a function doesn’t have a return statement? Is this valid?

Yes, this is valid. The function will then return a None object. The end of a function is defined by the block of code is executed (i.e., the indenting) not by any explicit keyword.

Define package in Python?

In Python packages are defined as the collection of different modules.

How can we make a Python script executable on Unix?

In order to make a Python script executable on Unix, we need to perform two things. They are.

Script file mode must be executable and

The first line should always begin with #.

Which command is used to delete files in Python?

OS.unlink(filename) or OS.remove(filename) are the commands used to delete files in Python Programming.

Example.

 

 

import OS

OS.remove(“abc.txt”)

Define pickling and unpickling in Python?

Pickling in Python. The process in which the pickle module accepts various Python objects and converts into a string representation and dumps the file accordingly using dump function is called pickling.

Unpickling in Python. The process of retrieving actual Python objects from the stored string representation is called unpickling.

Explain the difference between local and global namespaces?

Local namespaces are created within a function when that function is called. Global namespaces are created when the program starts.

 

What are Dict and List comprehensions in Python?

These are mostly used as syntax constructions to ease the creation of list and dictionaries based on existing iterable.

Define the term lambda?

Lambda is the small anonymous function in Python that is often used as an inline function.

When would you use triple quotes as a delimiter?

Triple quotes ‘’”” or ‘“ are string delimiters that can span multiple lines in Python. Triple quotes are usually used when spanning multiple lines, or enclosing a string that has a mix of single and double quotes contained therein.

Define self in Python?

In Python self is defined as an object or an instance of a class. This self is explicitly considered as the first parameter in Python. Moreover, we can also access all the methods and attributes of the classes in Python programming using self-keyword.

In the case of the init method, self refers to the newer creation of the object. Whereas in the case of other methods self refers to the object whose method was called.

What is _init_?

The _init_ is a special type of method in Python that is called automatically when the memory is allocated for a new object. The main role of _init_ is to initialize the values of instance members for objects.

Example.

 

 

 

 

 

 

 

 

 

 

 

class  Student.

def _init_ (self, name, age, marks).

self.name = name

self.age = age

self.marks =

S = Student(“ABC”, , )

# S is the instance of class Student.

# _init allocates memory for S.

print(S.name)

print(S.age)

print(S.marks)

Output. 

 

 

 

ABC

 

Define generators in Python?

The way of implementing an effective representation of iterators is known as generators. It is only the normal function that yields expression in the function.

Define docstring in Python?

The docstring in Python is also called a documentation string, it provides a way to document the Python classes, functions, and modules.

How do we convert the string to lowercase?

lower() function is used to convert string to lowercase.

Example.

 

 

str = ‘XYZ’

print(str.lower())

Output.

xyz

How to remove values from a Python array?

The elements can be removed from a Python array using remove() or pop() function. The difference between pop() and remove() will be explained in the below example.

Example.

 

 

 

 

 

x = arr.array(‘d’,  [ ., ., ., ., ., ., .])

print(x.pop())

print(x.pop())

x.remove(.)

print(a)

Output.

 

 

 

.

.

array(‘d’, [., ., ., .])

What is Try Block?

A block which is preceded by the try keyword is known as a try block

Syntax.

 

 

 

try{

//statements that may cause an exception

}

Why do we use the split method in Python?

split() method in Python is mainly used to separate a given string.

Example.

 

 

x = “Mindmajix Online Training”

print(a.split())

Output.

[‘Mindmajix’, ‘Online’, ‘Training’]

How can we access a module written in Python from C?

We can access the module written in Python from C by using the following method.

Module == PyImport_ImportModule(“<modulename>”);

How do you copy an object in Python?

To copy objects in Python we can use methods called copy.copy() or copy.deepcopy().

How do we reverse a list in Python?

By using list.reverse(). we can reverse the objects of the list in Python.

How can we debug a Python program?

By using the following command we can debug the Python program

$ python -m pdb python-script.py

Write a program to count the number of capital letters in a file?

 

 

 

 

 

 

with open(SOME_LARGE_FILE) as countletter.

count =

text = countletter.read()

for character in text.

if character.isupper().

count +=

Write a program to display the Fibonacci sequence in Python?

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

# Displaying Fibonacci sequence

n =

# first two terms

n =

n =

#Count

x =

# check if the number of terms is valid

if n <= .

print(“Enter positive integer”)

elif n == .

print(“Numbers in Fibonacci sequence upto”,n,”.”)

print(n)

else.

print(“Numbers in Fibonacci sequence upto”,n,”.”)

while x < n.

print(n,end=’, ‘)

nth = n + n

n = n

n = nth

x +=

Output.

, , , , , , , , , ,

Write a program in Python to produce Star triangle?

The code to produce star triangle is as follows.

 

 

 

 

def pyfun(r).

for a in range(r).

print(‘ ‘*(r-x-)+’*’*(*x+))

pyfun()

Output. 

 

 

 

 

 

 

 

 

 

        *

***

*****

*******

*********

***********

*************

***************

*****************

Write a program to check whether the given number is prime or not?

The code to check prime number is as follows.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

# program to check the number is prime or not

n =

# num = int(input(“Enter any one number. “))

# prime number is greater than

if n > .

# check the following factors

for x is in range of(,num).

if (n % x) == .

print(n,”is not a prime number”)

print(x,”times”,n//x,”is”,num)

break

else.

print(n,”is a prime number”)

# if input number is smaller than

# or equal to the value , then it is not prime number

else.

print(n,”is not a prime number”)

Output.

is a prime number

Write Python code to check the given sequence is a palindrome or not?

 

 

 

 

 

 

 

 

 

 

 

# Python code to check a given sequence

#  is palindrome or not

my_string = ‘MOM’

My_string = my_string.casefold()

# reverse the given string

rev_string  = reversed(my_string)

# check whether the string is equal to the reverse of it or not

if list(my_string) == list(rev_string).

print(“It is a palindrome”)

else.

print(“It is not a palindrome”)

Output.

it is a palindrome

Write Python code to sort a numerical dataset?

The code to sort a numerical dataset is as follows.

 

 

 

 

list = [ “”, “”, “”, “” , “”]

list = [int(x) for x in the list]

list.sort()

print(list)

Output. 

, , , ,

What is the output of the following code?

 

 

x = [‘ab’,’cd’]

print(list(map(list, x)))

The output of the following code is

[ [‘a’, ‘b’], [‘c’, ‘d’]

What is the procedure to install Python on Windows and set path variable?

We need to implement the following steps to install Python on Windows, and they are.

  • First you need to install Python from https.//www.python.org/downloads/
  • After installing Python on your PC, find the place where it is located in your PC using the cmd python command.
  • Then visit advanced system settings on your PC and add new variable. Name the new variable as PYTHON_NAME then copy the path and paste it.
  • Search for the path variable and select one of the values for it and click on ‘edit’.
  • Finally we need to add a semicolon at the end of the value and if the semicolon is not present then type %PYTHON_NAME%.

Differentiate between SciPy and NumPy?

The difference between SciPy and NumPy is as follows.

NumPy SciPy
Numerical Python is called NumPy Scientific Python is called SciPy
It is used for performing general and efficient computations on numerical data which is saved in arrays. For example, indexing, reshaping, sorting, and so on This is an entire collection of tools in Python mainly used to perform operations like differentiation, integration and many more.
There are some of the linear algebraic functions present in this module but they are not fully fledged. For performing algebraic computations this module contains some of the fully fledged operations

How do Python arrays and lists differ from each other?

The difference between Python array and Python list are as follows.

Arrays Lists
Array is defined as a linear structure that is used to store only homogeneous data. List are used to store arbitrary and heterogenous data
Since array stores only similar type of data so it occupies less amount of memory when compared to list. List stores different types of data so it requires huge amount of memory
Length of the array is fixed at the time of designing and no more elements can be added in the middle. Length of the list is no fixed, and adding items in the middle is possible in lists.

Can we make multi-line comments in Python?

In python there is no specific syntax to display multi-line comments like other languages. In order to display multi-line comments in Python, programmers use triple-quoted (docstrings) strings. If the docstring is not used as the first statement in the present method, it will not be considered by the Python parser.

. What is the difference between range and xrange?

These both the methods are mainly used in Python to iterate the for loop for a fixed number of times. They differ only when we talk regarding Python versions.

The difference between range and xrange are as follows.

Range() method Xrange() method
The xrange() method is not supported in Python so that the range() method is used for iteration in for loops. The xrange() method is used only in the Python version for the iteration in for loops.
List is returned by this range() method It only returns the generator object because it doesn’t produce a static list during run time.
It occupies a huge amount of memory as it stores the complete list of iterating numbers in memory. It occupies less memory because it only stores one number at the time in memory.

. What is Django?

Django is an advanced python web framework that supports agile growth and clean pragmatic design, built through experienced developers, this cares much about the trouble of web development, so you can concentrate on writing your app without wanting to reinvent that wheel.

. List the features of Django?

  • Excellent documentation
  • Python web framework
  • SEO optimised
  • High scalability
  • Versatile in nature
  • Offers high security
  • Thoroughly tested
  • Provides rapid Development

. Which level framework does Django belong to?

Django is a high-level Python web framework which was developed for realistic design, clean, rapid development.

. What are the advantages of Django?

  • One of the important advantages of Django is it is a framework of python language which is very simple to learn
  • Django is a multifaceted framework
  • When it comes to security Django is the best framework
  • Scalability is added advantage of Django

. Why should we use Django framework?

The main goal to design Django is to make it simple to its users, to do this Django uses.

  • The principles concerning rapid development, which implies developers can complete more than one iteration at a time without beginning the full schedule from scratch;
  • DRY philosophy — Do not Replicate Yourself — that means developers can reuse surviving code and also focus on the individual one.

. List the common security issues that can be avoided by using Django?

Few common security issues that can be avoided by using Django are.

  • Clickjacking
  • Cross-site scripting and
  • SQL injection

. List a few of the famous companies that are using Django?

Few well-known companies that are using the Django framework are

  • Instagram
  • Spotify
  • Mozilla
  • Dropbox
  • NASA

. What can we do with the Django framework?

Here is an exciting reality. Django has first created to power a web application as a newspaper publisher, the Lawrence Journal-World. You all can demand it to be very good about handling projects by volumes from the text files, media, including extremely high traffic or else something that operates as a web publication.

. List steps for setting up static files in Django?

There are only three main steps for setting up Django static files

  • Firstly set STATIC_ROOT in settings.py
  • Run manage.py collect static
  • Setting up a static file entry pythonAnywhere tab

. Is Django stable?

Yes, Django is used by many famous companies because it is quite stable.

. Differentiate Django reusability code with other frameworks?

Django web framework is operated and also maintained by an autonomous and non-profit organization designated as Django Software Foundation (DSF). The initial foundation goal is to promote, support, and advance this Django Web framework.

How can we handle URLs in Django?

 

 

 

 

 

 

 

 

 

from django.contrib import admin

from django.urls import path

urlpatterns = [

path(‘appmajix/’, appmajix.site.urls),

 

]

List the mandatory files if Django project?

  • manage.py
  • settings.py
  • __init__.py
  • urls.py
  • wsgi.py

Explain about Django session?

A session comprises a mechanism to store information on specific server-side at the interaction by the web application. By default, session reserves in the database and allows file-based and cache-based sessions.

Why do we use a cookie in Django?

A cookie is a piece of information that is stored in a client browser for a specific time. When the specific time is completed cookie gets automatically removed from the client browser.

Mentions the methods used for setting and getting cookie values?

The two methods to set and get cookie values are

  • Set_cookie this method is used to set the values of the cookie
  • Get_cookie this method is used to get the values of the cookie

What is the use of Django-admin.py?

Django-admin.py is a command-line argument which is utilised for administrative tasks

What is the use of manage.py?

It is an automatically built file inside each Django project. It is a flat wrapper encompassing the Django-admin.py. It possesses the following usage.

  • It establishes your project’s package on sys.path.
  • It fixes the DJANGO_SETTING_MODULE environment variable to point to your project’s setting.py file.

Why is Django loosely packed?

Django has described as a loosely coupled framework because concerning the MTV architecture it’s based upon. Django’s architecture means a variant of MVC architecture and also MTV is helpful because this completely separates the server code of the client’s machine.

List the ways we add view functions to urls.py?

  • Adding a function view
  • Adding a class-based view

Explain how can we build or set up the database in Django?

we can make use of edit mysite/setting.py command, it is a simple Python module consists of levels for presenting or displaying Django settings.

By default Django uses SQLite; this also makes easy for Django users in case of any other type of installations. For example, if your database choice is different then you need to follow certain keys in the DATABASE like default items to match database connection settings.

  • Engines. By these engines you change the database by using commands such as ‘django.db.backends.postgresql_psycopg’, ‘django.db.backends.sqlite’, ‘django.db.backends.oracle’, ‘django.db.backends.mysql’, and so on.
  • Name. This represents the name of your own database. If you are familiar with using SQLite as your database, in such case database is available as a file on your particular system. Moreover, the name should be as a fully absolute or exact path along with the file name of the particular file.
  • Suppose if we are not using SQlite as your database then additional settings such password, user, the host must be added.

Django mainly uses SQLite as its default database to store entire information in a single file of the filesystem. If you want to use different database servers rather than SQLite, then make use of database administration tools to create a new database for the Django project.  Another way is by using your own database in that place, and remaining is to explain Django about how to use it. This is the place in which Python’s project settings.py file comes into the picture.

We need to add the below code to the setting.py file.

 

 

 

 

 

 

DATABASE  = {

‘Default’ . {

‘ENGINE’ .  ‘django.db.backends.sqlite’,

‘NAME’ . os.path.join(BASE_DIR, ‘db.sqlite’),

}

}

 List out the inheritance styles in Django?

There are three possible inheritance styles in Django, and they are.

  • Proxy models. This style is mainly used for those who want to modify the Python level behaviour of the model, without modifying the model’s fields.
  • Abstract Base Classes. This inheritance style is used only when we want to make parent class hold the data which they don’t want to repeat it again in the child class.
  • Multi-table Inheritance. This inheritance style is used only when we want to subclass an existing model and there must a database table designed for each model on its own.

How to save an image locally using Python in which we already know the URL address?

The following code is used to save the image locally from the URL address which we know.

 

 

import urllib.request

urllib.request.urlretrieve(“URL”, “local-filename.jpg”)

How can we access sessions in flask?

A session will basically allow us to remember information from one request to another. In a flask, a signed cookie is used to make the user look at the session contents and modify them. Moreover, the user can change the session only when the secret key named Flask.secret_key is present.

 Is flask an MVC model? If yes, justify your answer by showing an example of your application with the help of MVC pattern?

Basically, flask is a minimalistic framework that behaves the same as MVC framework. So MVC will be perfectly suitable for the flask and we will consider the MVC pattern in the below example.

 

 

 

 

 

 

 

from flask import Flask

In this code your,

app = Flask(_name_)

@app.route(“/”)

Def hey().

return “Welcome to Appmajix”

app.run(debug = True)

The following code can be fragmented into

Configuration part will be,

 

 

In this code your,

app = Flask(_name_)

View part will be,

 

 

 

@app.route(“/”)

Def hey().

return “Welcome to Appmajix”

While your main part will be,

app.run(debug = True)

What are the database connections in Python Flask, explain?

Database powered applications are supported by flask. The relational database systems need to create a schema that requires piping the schema.sql file into a SQLite command. So, in this case you need to install SQLite command on your system to initiate and create the database in the flask.

We can request a database using flask in three ways, and they are.

  • before_request(). Using this we can request database before only without passing arguments.
  • after_request(). This method is called after requesting the database and also send the response to client.
  • teardown_request(). This method is called in the cases where the responses are not guaranteed and the exception is raised. They have no access to modify the request.

Explain the procedure to minimize or lower the outages of Memcached server in your Python development?

The following are the steps used to minimize the outages of the Memcached server in your Python development, and they are.

  • When a single instance fails, this will impact on larger load of the database server. The client makes the request when the data is reloaded. In order to avoid this, the code that you have written must be used to lower cache stampedes then it will used to leave a minimal impact.
  • The other way is to bring out the instance of the memcached on a new machine by using the IP address of the lost machine.
  • Another important option is to lower the server outages is code. This code provides you the liberty to modify the memcached server list with minimal work
  • Another way is by setting timeout value that will be one of the options for memcac
 

 

 

 

 

Class Student.

def __init__(self, name).

self.name = name

S=Student(“XYZ”)

print(S.name)

  • hed clients to implement the memcached server outage. When the performance of the server goes down, the client keeps on sending a request until the timeout limit is reached.

What is Dogpile effect?

This is defined as an occurrence of event when the cache expires and also when the websites are hit with more number of requests by the client at a time. This dogpile effect can be averted by the use of a semaphore lock. If in the particular system the value expires then, first of all, the particular process receives the lock and begin generating new value.

What are the OOPS concepts available in Python?

Python is also object-oriented programming language like other programming languages. It also contains different OOPS concepts, and they are

  • Object
  • Class
  • Method
  • Encapsulation
  • Abstraction
  • Inheritance
  • Polymorphism

Define object in Python?

An object in Python is defined as an instance that has both state and behaviour. Everything in Python is made of objects.

What is a class in Python?

Class is defined as a logical entity that is a huge collection of objects and it also contains both methods and attributes.

How to create a class in Python?

In Python programming, the class is created using a class keyword. The syntax for creating a class is as follows.

 

 

class ClassName.

#code (statement-suite)

Example of creating a class in Python.

Output.

XYZ

. What is the syntax for creating an instance of a class in Python?

The syntax for creating an instance of a class is as follows.

<object-name> = <class-name>(<arguments>)

Define what is “Method” in Python programming?

The Method is defined as the function associated with a particular object. The method which we define should not be unique as a class instance. Any type of objects can have methods.

Does multiple inheritances is supported in Python?

Multiple inheritance is supported in python. It is a process that provides flexibility to inherit multiple base classes in a child class.

Example of multiple inheritance in Python is as follows.

 

 

 

 

 

 

 

 

 

 

 

 

 

class Calculus.

def Sum(self,a,b).

return a+b;

class Calculus.

def Mul(self,a,b).

return a*b;

class Derived(Calculus,Calculus).

def Div(self,a,b).

return a/b;

d = Derived()

print(d.Sum(,))

print(d.Mul(,))

print(d.Div(,))

Output.

 

 

 

 

 

.

What is data abstraction in Python?

In simple words, abstraction can be defined as hiding of unnecessary data and showing or executing necessary data. In technical terms, abstraction can be defined as hiding internal process and showing only the functionality. In Python abstraction can be achieved using encapsulation.

Define encapsulation in Python?

Encapsulation is one of the most important aspects of object-oriented programming. Binding or wrapping of code and data together into a single cell is called encapsulation. Encapsulation in Python is mainly used to restrict access to methods and variables.

What is polymorphism in Python?

By using polymorphism in Python we will understand how to perform a single task in different ways. For example, designing a shape is the task and various possible ways in shapes are a triangle, rectangle, circle, and so on.

Does Python make use of access specifiers?

Python does not make use of access specifiers and also it does not provide a way to access an instance variable. Python introduced a concept of prefixing the name of the method, function, or variable by using a double or single underscore to act like the behaviour of private and protected access specifiers.

How can we create an empty class in Python?

Empty class in Python is defined as a class that does not contain any code defined within the block. It can be created using pass keyword and object to this class can be created outside the class itself.

Example.

 

 

 

 

 

class x.

&nbsp; pass

obj=x()

obj.id=””

print(“Id = “,obj.id)

Output.

Define Constructor in Python?

Constructor is a special type of method with a block of code to initialize the state of instance members of the class. A constructor is called only when the instance of the object is created. It is also used to verify that they are sufficient resources for objects to perform a specific task.

There are two types of constructors in Python, and they are.

  • Parameterized constructor
  • Non-parameterized constructor

How can we create a constructor in Python programming?

The _init_ method in Python stimulates the constructor of the class. Creating a constructor in Python can be explained clearly in the below example.

 

 

 

 

 

 

 

 

 

 

 

 

class Student.

def __init__(self,name,id).

self.id = id;

self.name = name;

def display (self).

print(“ID. %d nName. %s”%(self.id,self.name))

stu =Student(“nirvi”,)

stu = Student(“tanvi”,)

#accessing display() method to print employee information

stu.display();

#accessing display() method to print employee information

stu.display();

Output.

 

 

 

 

ID.

Name. nirvi

ID.

Name. Tanvi

Define Inheritance in Python?

When an object of child class has the ability to acquire the properties of a parent class then it is called inheritance. It is mainly used to acquire runtime polymorphism and also it provides code reusability.

What is the difference between a module and a package in Python?

Each Python program file is a module that imports other modules like objects. Thus, a module is a way to structure the program. The folder of a Python program is called a package of modules.

What are the built-in types available in Python?

One of the most common python interview question, there are mutable and immutable built-in types.

The mutable ones include.

  • List
  • Sets
  • Dictionaries

The immutable types include.

  • Strings
  • Tuples
  • Numbers

What is lambda function in Python?

It is often used as an inline function and is a single expression anonymous function. It is used to make a new function object and return them at runtime.

Lambda is an anonymous function in Python that can accept any number of arguments and can have any number of parameters. However, the lambda function can have only a single expression or statement. Usually, it is used in situations that require an anonymous function for a short time period. Lambda functions can be used in either of the two ways.

Here’s an example of the lambda function.

a = lambda x,y . x+y

print(a(, ))

Output.

What is meant by namespace?

A namespace refers to a naming system that is used to ensure that all object names in a Python program are unique, to avoid any conflicts. In Python, these namespaces are implemented as dictionaries with ‘name as key’ mapped to a corresponding ‘object as value.’ As a result, multiple namespaces can use the same name and map it to a different object.

Below are the three types of namespaces in Python. 

  • Local namespace – It includes local names inside a function. A local namespace is temporarily created for a function call and is cleared when the function returns.
  • Global namespace – It consists of the names from various imported packages/ modules that are currently being used in a project. A global namespace is created when a package is imported in the script, and it lasts until the script is executed.
  • Built-in namespace – It includes built-in functions of core Python and built-in names for the different types of exceptions.

Explain the difference between a list and a tuple?

The list is mutable while the tuple is not. Tuples can be hashed as in the case of making keys for dictionaries.

What is the use of %s?

%s is a format specifier which transmutes any value into a string.

Is it mandatory for a Python function to return a value?

No

Does Python have a main() function?

Yes, it does. It is executed automatically whenever we run a Python script. To override this natural flow of things, we can also use the if statement.

What is GIL?

GIL or the Global Interpreter Lock is a mutex, used to limit access to Python objects. It synchronizes threads and prevents them from running at the same time.

Before the use of the ‘in’ operator, which method was used to check the presence of a key in a dictionary?

The has_key(). method

How do you change the data type of a list?

To change a list into a tuple, we use the tuple() function

To change it into a set, we use the set() function

To change it into a dictionary, we use the dict() function

To change it into a string, we use the .join() method

What are the key features of Python?

It is one of the common python interview questions. Python is an open-source, high-level, general-purpose programming language. Since it is a general-purpose programming language and it comes with an assortment of libraries, you can use Python for developing almost any type of application.

Some of its key features are.

  • Interpreted
  • Dynamically-typed
  • Object-oriented
  • English-like syntax

Explain memory management in Python.

In Python, the Python Memory Manager takes care of memory management. It allocates the memory in the form of a private heap space that stores all Python objects and data structures, there are built in data structure in python. This private space is inaccessible to the programmer. However, the core API allows the programmer to access some tools for coding purposes. Plus, Python is equipped with an in-built garbage collector that recycles the unused memory for the private heap space.

What is PYTHONPATH?

PYTHONPATH is an environment variable that is used to incorporate additional directories when a module/package is imported. Whenever a module/package is imported, PYTHONPATH is used to check if the imported modules are present in the existing directories. Usually, the interpreter uses PYTHONPATH to determine which module to load.

Is Python case-sensitive?

A programming language is deemed to be case-sensitive if it distinguishes between identifiers like “myname” and “Myname.” In simple words, it cares about the case – lowercase or uppercase.

Let’s see an example.

  1. >>> myname=’John’
  2. >>> Myname

Traceback (most recent call last).

File “<pyshell#>”, line , in <module>

Myname

NameError. name ‘Myname’ is not defined

Since it raises a NameError, it means that Python is a case-sensitive language.

Explain the use of “help()” and “dir()” functions.

In Python, the help() function is used for showing the documentation of modules, classes, functions, keywords, and so on. If the help() function receives no parameter, it launches an interactive help utility on the console.

The dir() function is used to return a valid list of attributes and methods of the object it is called upon. Since the function aims to produce the most relevant data (instead of showing the complete information), it behaves differently with different objects.

  • For modules/library objects, the dir() function returns a list of all attributes contained in that module.
  • For class objects, the dir() function returns a list of all valid attributes and base attributes.
  • When no parameters are passed to it, the dir() function returns a list of attributes in the current scope.

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

Python modules are files containing Python code that can be either function classes or variables. These modules are Python files having a .py extension. Modules can include a set of functions, classes, or variables that are both defined and implemented. You can import and initialize a module using the import statement, learning python tutorial will let us know more about python modules.

Here are some of the commonly used built-in modules in Python.

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

Explain “self” in Python.

In Python, “self” is a keyword used to define an instance or object of a class. Unlike in Java, where the self is optimal, in Python, it is primarily used as the first parameter. Self helps to distinguish between the methods and attributes of a class from its local variables.

The self-variable in the __init__ method refers to the newly created object or instance, while in other methods, it pertains to the object or instance whose method was called.

 What is PEP ?

PEP or Python Enhancement Proposal is a set of rules that specify how to format Python code for maximum readability. It is an official design document that provides relevant information to the Python Community, such as describing a new Python feature or a Python process. PEP is an important document that includes the style guidelines for Python Code. Anyone who wishes to contribute to the Python open-source community must strictly abide by these style guidelines.

Is indentation mandatory in Python?

Yes, indentation is necessary for Python. Indentation helps specify a block of code. Thus, in a Python code, everything within loops, classes, functions, etc., is specified within an indented block. If your Python code isn’t indented correctly, there’ll be problems during the execution, and it will raise errors.

Explain the difference between Python arrays and lists.

In Python, both arrays and lists are used to store data. However,

  • Arrays can only contain elements of the same data types, meaning the data types of an array should be homogeneous.
  • Lists can contain elements of different data types, which means that the data types of lists can be heterogeneous. Lists consume much more memory than arrays.

Here’s an example.

import array as arr

My_Array=arr.array(‘i’,[,,,])

My_list=[,’abc’,.]

print(My_Array)

print(My_list)

. What is __init__?

In Python,__init__ is a method or constructor. It is automatically called to allocate memory when a new object or instance of a class is created. All classes have the __init__ method.

Here’s how to use the __init__ method in Python.

# class definition

class Student.

def __init__(self, fname, lname, age, section).

self.firstname = fname

self.lastname = lname

self.age = age

self.section = section

# creating a new object

stu = Student(“Sara”, “Ansh”, , “A”)

Explain the functionality of “break,” “continue,” and “pass.”

It is one of the common questions in python interview questions and answers guide. Let’s see break, continue and pass in detail.

The break statement is used for terminating a loop when a specific condition is met, and the control is transferred to the following statement.

  • The continue statement helps to terminate the current iteration of the statement when a particular condition is met, skips the rest of the code in the current iteration, and passes the control to the next iteration of the loop.
  • The pass statement is essentially a null operation that is used to fill up empty blocks of code that may execute during runtime but are yet to be written. It is represented by a semi-colon.

How to write comments in Python?

In Python, comments start with a # character. However, sometimes, you can also write comments using docstrings(strings enclosed within triple quotes). Unlike C++, Python does not support multiline comments.

Here’s how a comment is written in Python.

>>> #line of comment

>>> #line of comment

What are the generators in Python?

Generators are most important python functions that return an iterable collection of items, one at a time, in an organized manner. Generally, generators are used to create iterators with a different approach – they use of yield keyword rather than return to return a generator object.

How can you capitalize the first letter of a string in Python?

In Python, you can use the capitalize() method to capitalize the first letter of a string. However, if a string already consists of a capital letter at the beginning, it will return the original string.

What are “docstrings” in Python?

Docstrings or documentation strings are multiline strings used to document a specific code segment. Docstrings usually come within triple quotes and should ideally describe what a function or method does. Although they are not comments, docstrings sometimes serve the purpose of comments since they are not assigned to any variable.

Explain the functions of “is,” “not,” and “in” operators?

Again, one of the popular python interview questions. Operators are special functions in Python that can take one or more values to produce a corresponding result.

  • The “is” operator returns true when two operands are true.
  • The “not” operator returns the inverse of the boolean value.
  • The “in” operator checks if some element is present in some sequence.

How to copy an object in Python?

In Python, the assignment statement (= operator) does not copy objects, but instead, it creates a binding between the existing object and the target variable name. Thus, if you wish to create copies of an object in Python, you need to use the copy module. There are two ways to create copies for a particular object using the copy module.

  • Shallow copy – It is a bit-wise copy of an object. The copied object will have an exact replica of the values contained in the original object. If any of the values are references to other objects, only the reference addresses for the same will be copied.
  • Deep copy — It copies all values recursively from source to target object, meaning, it will duplicate even the objects that are referenced by the source object.

What is an Expression?

An expression Can be defined as a combination of variables, values operators a call to functions. It is a sequence of operands or operators like a + B – is called an expression. Python supports many such operators for combining data object into an express.

What is a statement in Python?

It is an instruction that Python can interpret and execute when you type the statement in the command line Python execute and displays the result if there is one.

What is == in Python?

It is an operator which is used to check or compare the values  of two objects

What are the escape sequences in Python?

Python strings, the backslash “\” could be a special character, also called the “escape” character. it’s utilized in representing certain whitespace characters. “\t” may be a tab, “\n” could be a newline, and “\r” could be a printing operation. Conversely, prefixing a special character with “\” turns it into a standard character.

what is encapsulation?

Encapsulation is the binding of data and functions that manipulate the data.
It is a process of wrapping up data and variables together.

example
class playercharacter().
def __init__(self,name,age).
self.name = name
self.age = age

player = playercharacter(‘leo’,)
print(player.name)
print(player.age)

How do you do data abstraction in Python?

An abstraction means hiding away information or showing only information that’s necessary.
Example
print(len((,,,)))
#in this example we dont want to learn how len was introduced in python

What is a dictionary in python?

Dictionary is a data structure as well as a data type in python.It is enclosed in curly brackets{}.
Dictionary contains elements – key and value
key is a string for us to grab a value.

Example
dictionary = {
‘a’. ,
‘b’.
}

print(dictionary[‘b’])

What are functions?

Functions are a set of code used when we want to run the same method for more than time.It reduces the length of program.Functions are defined into categories –
)function defination
)function calling

Example
def dog().
print(“my name is tommy”)

dog();

What is the difference between list and tuples in Python?

LIST vs TUPLES
LIST TUPLES
Lists are mutable i.e they can be edited. Tuples are immutable (tuples are lists which can’t be edited).
Lists are slower than tuples. Tuples are faster than list.
Syntax. list_ = [, ‘Chelsea’, ] Syntax. tup_ = (, ‘Chelsea’ , )

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

What type of language is python? Programming or scripting?

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.

Python an interpreted language. Explain.

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

.What is pep ?

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

How is memory managed in Python?

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.

What is namespace in Python?

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

What is PYTHONPATH?

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.

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.

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

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.

 

 

 

 

 

 

a=

def add().

b=

c=a+b

print(c)

add()

Output. 

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

Is python case sensitive?

Yes. Python is a case sensitive language.

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.

How to install Python on Windows and set path variable?

To install Python on Windows, follow the below steps.

  • Install python from this link. https.//www.python.org/downloads/
  • After this, install it on your PC. Look for the location where PYTHON has been installed on your PC using the following command on your command prompt. cmd python.
  • Then go to advanced system settings and add a new variable and name it as PYTHON_NAME and paste the copied path.
  • Look for the path variable, select its value and select ‘edit’.
  • Add a semicolon towards the end of the value if it’s not present and then type %PYTHON_HOME%

Is indentation required in python?

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

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.

 

 

 

 

 

import array as arr

My_Array=arr.array(‘i’,[,,,])

My_list=[,’abc’,.]

print(My_Array)

print(My_list)

Output.

array(‘i’, [, , , ]) [, ‘abc’, .]

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.

 

 

 

def Newfunc().

print(“Hi, Welcome to Tecklearn”)

Newfunc(); #calling the function

Output. Hi, Welcome to Tecklearn

What is __init__?

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

 

 

 

 

 

 

 

 

 

 

 

class Employee.

def __init__(self, name, age,salary).

self.name = name

self.age = age

self.salary =

E = Employee(“XYZ”, , )

# E is the instance of class Employee.

#__init__ allocates memory for E.

print(E.name)

print(E.age)

print(E.salary)

Output.

XYZ

What is a lambda function?

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

Example.

 

 

a = lambda x,y . x+y

print(a(, ))

Output. 

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.

How does break, continue and pass work?

Break Allows loop termination when some condition is met and the control is transferred to the next statement.
Continue Allows skipping some part of a loop when some specific condition is met and the control is transferred to the beginning of the loop
Pass Used when you need some block of code syntactically, but you want to skip its execution. This is basically a null operation. Nothing happens when this is executed.

What does [..-} do?

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

For example.

 

 

 

import array as arr

My_Array=arr.array(‘i’,[,,,,])

My_Array[..-]

Output. array(‘i’, [, , , , ])

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

 How can you randomize the items of a list in place in Python?

Consider the example shown below.

 

 

 

 

from random import shuffle

x = [‘Keep’, ‘The’, ‘Blue’, ‘Flag’, ‘Flying’, ‘High’]

shuffle(x)

print(x)

The output of the following code is as below.

[‘Flying’, ‘Keep’, ‘Blue’, ‘High’, ‘The’, ‘Flag’]

What are python iterators?

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

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.

 

 

import random

random.random

The statement random.random() method return the floating point number that is in the range of [, ). 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.

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.

How do you write comments in python?

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

Example.

#Comments in Python start like this

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

Output.  Comments in Python start with a #

What is pickling and unpickling?

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

What are the generators in python?

Functions that return an iterable set of items are called generators.

How will you capitalize the first letter of string?

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.

How will you convert a string to all lowercase?

To convert a string to lowercase, lower() function can be used.

Example.

 

 

stg=’ABCD’

print(stg.lower())

Output. abcd

How to comment multiple lines in python?

Multi-line comments appear in more than one line. All the lines to be commented are to be prefixed by a #. You can also a very good shortcut method to comment multiple lines. All you need to do is hold the ctrl key and left click in every place wherever you want to include a # character and type a # just once. This will comment all the lines where you introduced your cursor.

What are docstrings in Python?

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.

 

 

 

 

 

 

 

 

“””

Using docstring as a comment.

This code divides numbers

“””

x=

y=

z=x/y

print(z)

Output. .

What is the purpose of is, not and in operators?

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

  1. returns true when operands are true  (Example. “a” is ‘a’)

not. returns the inverse of the boolean value

  1. checks if some element is present in some sequence

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.

  1. Help() function. The help() function is used to display the documentation string and also facilitates you to see the help related to modules, keywords, attributes, etc.
  2. Dir() function. The dir() function is used to display the defined symbols.

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

  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.

What is a dictionary in Python?

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.

dict={‘Country’.’India’,’Capital’.’Delhi’,’PM’.’Modi’}
print dict[Country]

India

print dict[Capital]

Delhi

print dict[PM]

Modi

How can the ternary operators be used in python?

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 = , big = 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.

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

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.

. What does len() do?

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

Example.

 

 

stg=’ABCD’

len(stg)

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

To modify the strings, Python’s “re” module is providing 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.

What are negative indexes 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 ‘’ that is uses as first index and ‘’ as the second index and the process goes on like that.

The index for the negative number starts from ‘-’ that represents the last index in the sequence and ‘-’ 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[.-]. The negative index is also used to show the index to represent the string in correct order.

What are Python packages?

Python packages are namespaces containing multiple modules.

How can files be deleted in Python?

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

Example.

 

 

import os

os.remove(“xyz.txt”)

What are the built-in types of python?

Built-in types in Python are as follows –

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

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

  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.

How to add values to a python array?

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

Example.

 

 

 

 

 

 

 

a=arr.array(‘d’, [. , . ,.] )

a.append(.)

print(a)

a.extend([.,.,.])

print(a)

a.insert(,.)

print(a)

Output.

array(‘d’, [., ., ., .])

array(‘d’, [., ., ., ., ., ., .])

array(‘d’, [., ., ., ., ., ., ., .])

How to remove values to a python array?

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.

 

 

 

 

 

a=arr.array(‘d’, [., ., ., ., ., ., .])

print(a.pop())

print(a.pop())

a.remove(.)

print(a)

Output.

.

.

array(‘d’, [., ., ., .])

Does Python have OOps concepts?

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 procedural as well as structural language.

. What is the difference between deep and shallow copy?

 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.

How is Multithreading achieved in Python?

 

  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.

What is the process of compilation and linking in python?

The compiling and linking allows the new extensions to be compiled properly without any error and the linking can be done only when it passes the compiled procedure. If the dynamic loading is used then it depends on the style that is being provided with the system. The python interpreter can be used to provide the dynamic loading of the configuration setup files and will rebuild the interpreter.

The steps that are required in this as.

  1. Create a file with any name and in any language that is supported by the compiler of your system. For example file.c or file.cpp
  2. Place this file in the Modules/ directory of the distribution which is getting used.
  3. Add a line in the file Setup.local that is present in the Modules/ directory.
  4. Run the file using spam file.o
  5. After a successful run of this rebuild the interpreter by using the make command on the top-level directory.
  6. If the file is changed then run rebuildMakefile by using the command as ‘make Makefile’.

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.

What is split used for?

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

Example.

 

 

a=”Tecklearn python”

print(a.split())

Output.  [‘Tecklearn’, ‘python’]

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

import array as arr    # importing using an alias name

from array import *    #imports everything present in the array module

Explain Inheritance in Python with an example.

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 d in inherited from base class base, and d are inherited from base.
  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.

How are classes created in Python? 

Class in Python is created using the class keyword.

Example.

 

 

 

 

 

class Employee.

def __init__(self, name).

self.name = name

E=Employee(“abc”)

print(E.name)

Output. abc

What is monkey patching in Python?

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

Consider the below example.

 

 

 

 

# m.py

class MyClass.

def f(self).

print “f()”

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

 

 

 

 

 

 

 

import m

def monkey_f(self).

print “monkey_f()”

 

m.MyClass.f = monkey_f

obj = m.MyClass()

obj.f()

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.

Does python support multiple inheritance?

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

What is Polymorphism in Python?

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.

Define encapsulation in Python?

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

How do you do data abstraction in Python?

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.

Does python make use of access specifiers?

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.

How to create an empty class in Python? 

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-

 

 

 

 

 

class a.

&amp;amp;amp;nbsp; pass

obj=a()

obj.name=”xyz”

print(“Name = “,obj.name)

Output. 

Name = xyz

What does an object() do?

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

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

 

 

 

 

 

 

 

 

 

 

def bs(a). a = name of list;

b=len(a)-;

#minus because we always compare adjacent values

for x in range(b).

for y in range(b-x).

if a[y]&amp;amp;gt;a[y+].

a[y],a[y+]=a[y+],a[y]

return a;

a=[,,,,,,];

bs(a)

Output.  [, , , , , , ]

Write a program in Python to produce Star triangle.

 

 

 

 

def pyfunc(r).

for x in range(r).

print(‘ ‘*(r-x-)+’*’*(*x+))

pyfunc()

Output.

*

***

*****

*******

*********

***********

*************

***************

*****************

 

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

 

 

 

 

 

 

a=input(“enter sequence”)

b=a[..-]

if a==b.

&amp;amp;amp;nbsp; print(“palindrome”)

else.

&amp;amp;amp;nbsp; print(“Not a Palindrome”)

Output.

enter sequence palindrome

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.

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

 

 

 

 

 

 

with open(SOME_LARGE_FILE) as fh.

count =

text = fh.read()

for character in text.

if character.isupper().

count +=

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

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

Write a sorting algorithm for a numerical dataset in Python.

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

 

 

 

 

list = [“”, “”, “”, “”, “”]

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

list.sort()

print (list)

Looking at the below code, write down the final values of A, A, …An.

 

 

 

 

 

 

 

A = dict(zip((‘a’,’b’,’c’,’d’,’e’),(,,,,)))

A = range()A = sorted([i for i in A if i in A])

A = sorted([A[s] for s in A])

A = [i for i in A if i in A]

A = {i.i*i for i in A}

A = [[i,i*i] for i in A]

print(A,A,A,A,A,A,A)

The following will be the final outputs of A, A, … A

A = {‘a’. , ‘c’. , ‘b’. , ‘e’. , ‘d’. } # the order may vary

A = range(, )

A = []

A = [, , , , ]

A = [, , , , ]

A = {. , . , . , . , . , . , . , . , . , . }

A = [[, ], [, ], [, ], [, ], [, ], [, ], [, ], [, ], [, ], [, ]]

Explain what Flask is and its benefits?

Flask is a web microframework for Python based on “Werkzeug, Jinja and good intentions” BSD license. Werkzeug and Jinja are two of its dependencies. This means it will have little to no dependencies on external libraries.  It makes the framework light while there is a little dependency to update and fewer security bugs.

A session basically allows you to remember information from one request to another. In a flask, a session uses a signed cookie so the user can look at the session contents and modify. The user can modify the session if only it has the secret key Flask.secret_key.

Is Django better than Flask?

Django and Flask map the URL’s or addresses typed in the web browsers to functions in Python.

Flask is much simpler compared to Django but, Flask does not do a lot for you meaning you will need to specify the details, whereas Django does a lot for you wherein you would not need to do much work. Django consists of prewritten code, which the user will need to analyze whereas Flask gives the users to create their own code, therefore, making it simpler to understand the code. Technically both are equally good and both contain their own pros and cons.

Mention the differences between Django, Pyramid and Flask.

Flask is a “microframework” primarily build for a small application with simpler requirements. In flask, you have to use external libraries. Flask is ready to use.

  • Pyramid is built for larger applications. It provides flexibility and lets the developer use the right tools for their project. The developer can choose the database, URL structure, templating style and more. Pyramid is heavy configurable.
  • Django can also be used for larger applications just like Pyramid. It includes an ORM.

Discuss Django architecture.

Django MVT Pattern.

Figure.  Python Interview Questions – Django Architecture

The developer provides the Model, the view and the template then just maps it to a URL and Django does the magic to serve it to the user.

Explain how you can set up the Database in Django.

You can use the command edit mysite/setting.py, it is a normal python module with module level representing Django settings.

Django uses SQLite by default; it is easy for Django users as such it won’t require any other type of installation. In the case your database choice is different that you have to the following keys in the DATABASE ‘default’ item to match your database connection settings.

  • Engines. you can change the database by using ‘django.db.backends.sqlite’ , ‘django.db.backeneds.mysql’, ‘django.db.backends.postgresql_psycopg’, ‘django.db.backends.oracle’ and so on
  • Name. The name of your database. In the case if you are using SQLite as your database, in that case, database will be a file on your computer, Name should be a full absolute path, including the file name of that file.
  • If you are not choosing SQLite as your database then settings like Password, Host, User, etc. must be added.

Django uses SQLite as a default database, it stores data as a single file in the filesystem. If you do have a database server—PostgreSQL, MySQL, Oracle, MSSQL—and want to use it rather than SQLite, then use your database’s administration tools to create a new database for your Django project. Either way, with your (empty) database in place, all that remains is to tell Django how to use it. This is where your project’s settings.py file comes in.

We will add the following lines of code to the setting.py file.

 

 

 

 

 

 

DATABASES = {

‘default’. {

‘ENGINE’ . ‘django.db.backends.sqlite’,

‘NAME’ . os.path.join(BASE_DIR, ‘db.sqlite’),

}

}

Give an example how you can write a VIEW in Django?

This is how we can use write a view in Django.

 

 

 

 

 

 

 

from django.http import HttpResponse

import datetime

 

def Current_datetime(request).

now = datetime.datetime.now()

html = “&amp;amp;lt;html&amp;amp;gt;&amp;amp;lt;body&amp;amp;gt;It is now %s&amp;amp;lt;/body&amp;amp;gt;&amp;amp;lt;/html&amp;amp;gt; % now

return HttpResponse(html)

Returns the current date and time, as an HTML document

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.

Figure. Python Interview Questions – Django Template

Explain the use of session in Django framework?

Django provides a session that lets you 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.

Figure. Python Interview Questions – Django Framework

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

List out the inheritance styles in Django.

In Django, there are three possible inheritance styles.

  1. Abstract Base Classes. This style is used when you only want parent’s class to hold information that you don’t want to type out for each child model.
  2. Multi-table Inheritance. This style is used If you are sub-classing an existing model and need each model to have its own database table.
  3. Proxy models. You can use this model, If you only want to modify the Python level behavior of the model, without changing the model’s fields.

How To Save An Image Locally Using Python Whose URL Address I Already Know?

We will use the following code to save an image locally from an URL address

 

 

import urllib.request

urllib.request.urlretrieve(“URL”, “local-filename.jpg”)

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

Use the following URL format.

http.//webcache.googleusercontent.com/search?q=cache.URLGOESHERE

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 Tecklearn.co you’d use the following URL.

http.//webcache.googleusercontent.com/search?q=cache.Tecklearn.co

You are required to scrap data from IMDb top movies page. It should only have fields movie name, year, and rating.

We will use the following lines of code.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

from bs import BeautifulSoup

 

import requests

import sys

 

url = ‘<a href=”http.//www.imdb.com/chart/top”>http.//www.imdb.com/chart/top</a>’

response = requests.get(url)

soup = BeautifulSoup(response.text)

tr = soup.findChildren(“tr”)

tr = iter(tr)

next(tr)

 

for movie in tr.

title = movie.find(‘td’, {‘class’. ‘titleColumn’} ).find(‘a’).contents[]

year = movie.find(‘td’, {‘class’. ‘titleColumn’} ).find(‘span’, {‘class’. ‘secondaryInfo’}).contents[]

rating = movie.find(‘td’, {‘class’. ‘ratingColumn imdbRating’} ).find(‘strong’).contents[]

row = title + ‘ – ‘ + year + ‘ ‘ + ‘ ‘ + rating

 

print(row)

The above code will help scrap data from IMDb’s top list

What is map function in Python?

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 arguments, then many iterables are given. #Follow the link to know more similar functions.

Is python numpy better than lists?

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.

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

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

 

 

 

import numpy as np

arr = np.array([, , , , ])

print(arr.argsort()[-.][..-])

Output

[ ]

How do you calculate percentiles with Python/ NumPy?

We can calculate percentiles with the following code

 

 

 

 

import numpy as np

a = np.array([,,,,])

p = np.percentile(a, ) #Returns th percentile, e.g. median

print(p)

Output

What is the difference between NumPy and SciPy?

  1. In an ideal world, NumPy would contain nothing but the array data type and the most basic operations. indexing, sorting, reshaping, basic elementwise functions, et cetera.
  2. All numerical code would reside in SciPy. However, one of NumPy’s important goals is compatibility, so NumPy tries to retain all features supported by either of its predecessors.
  3. Thus NumPy contains some linear algebra functions, even though these more properly belong in SciPy. In any case, SciPy contains more fully-featured versions of the linear algebra modules, as well as many other numerical algorithms.
  4. If you are doing scientific computing with python, you should probably install both NumPy and SciPy. Most new features belong in SciPy rather than NumPy.

How do you make D plots/visualizations using NumPy/SciPy?

Like D plotting, D graphics is beyond the scope of NumPy and SciPy, but just as in the D case, packages exist that integrate with NumPy. Matplotlib provides basic D plotting in the mplotd subpackage, whereas Mayavi provides a wide range of high-quality D visualization features, utilizing the powerful VTK engine.

Which of the following statements create a dictionary?

  1. a) d = {}
    b) d = {“john”., “peter”.}
    c) d = {.”john”, .”peter”}
    d) d = (.”john”, .””)

b, c & d.

 

#output.

Count the occurrences of each item in the list.

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

weekdays = [‘sun’,’mon’,’tue’,’wed’,’thu’,’fri’,’sun’,’mon’,’mon’]

print([[x,weekdays.count(x)] for x in set(weekdays)])

#output. [[‘wed’, ], [‘sun’, ], [‘thu’, ], [‘tue’, ], [‘mon’, ], [‘fri’, ]]

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

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

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

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

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

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

The first method to create an empty array.

import numpy

numpy.array([])

The second method to create an empty array.

# Make an empty NumPy array

numpy.empty(shape=(,))

 

Which one of these is floor division?

  1. a) /
    b) //
    c) %
    d) None of the mentioned
  2. b) //

When both of the operands are integer then python chops out the fraction part and gives you the round off value, to get the accurate answer use floor division. For ex, / = . but both of the operands are integer so answer of this expression in python is . To get the . as the answer, use floor division using //. So, // = .

What is the maximum possible length of an identifier?

  1. a) characters
    b) characters
    c) characters
    d) None of the above
  2. d) None of the above

Identifiers can be of any length.

What is a boolean in Python?

Boolean is one of the built-in data types in Python, it mainly contains two values, and they are true and false.

Python bool() is the method used to convert a value to a boolean value.

Syntax for bool() method. bool([a])

What is Python String format and Python String replace?

Python String Format. The String format() method in Python is mainly used to format the given string into an accurate output or result.

Syntax for String format() method.

template.format(p, p, …, k=v, k=v, …)

Python String Replace. This method is mainly used to return a copy of the string in which all the occurrence of the substring is replaced by another substring.

Syntax for String replace() method. 

str.replace(old, new [, count])

Name some of the built-in modules in Python?

The built-in modules in Python are.

  • sys module
  • OS module
  • random module
  • collection module
  • JSON
  • Math module

What are the functions in Python?

In Python, functions are defined as a block of code that is executable only when it is called. The def keyword is used to define a function in Python.

Example.

 

 

 

def Func().

print(“Hello, Welcome toMindmajix”)

Func(); #calling the function

Output. Hello, Welcome to Mindmajix

Why are local variable names beginning with an underscore discouraged?

  1. a) they are used to indicate a private variable of a class
    b) they confuse the interpreter
    c) they are used to indicate global variables
    d) they slow down execution
  2. a) they are used to indicate a private variable of a class

As Python has no concept of private variables, leading underscores are used to indicate variables that must not be accessed from outside the class.

Which of the following is an invalid statement?

  1. a) abc = ,,
    b) a b c =
    c) a,b,c = , ,
    d) a_b_c = ,,
  2. b) a b c =

Spaces are not allowed in variable names.

What is the output of the following?

 

 

 

 

 

 

 

try.

if ” != .

raise “someError”

else.

print(“someError has not occured”)

except “someError”.

print (“someError has occured”)

  1. a) someError has occured
    b) someError has not occured
    c) invalid code
    d) none of the above
  2. c) invalid code

A new exception class must inherit from a BaseException. There is no such inheritance here.

Suppose list is [, , , , ], What is list[-] ?

  1. a) Error
    b) None
    c)
    d)
  2. c)

The index – corresponds to the last index in the list.

To open a file c.scores.txt for writing, we use

  1. a) outfile = open(“c.scores.txt”, “r”)
    b) outfile = open(“c.scores.txt”, “w”)
    c) outfile = open(file = “c.scores.txt”, “r”)
    d) outfile = open(file = “c.scores.txt”, “o”)
  2. b) The location contains double slashes ( ) and w is used to indicate that file is being written to.

What is the output of the following?

 

 

 

 

 

 

 

 

f = None

 

for i in range ().

with open(“data.txt”, “w”) as f.

if i &amp;amp;gt; .

break

 

print f.closed

  1. a) True
    b) False
    c) None
    d) Error
  2. a) True

The WITH statement when used with open file guarantees that the file object is closed when the with block exits.

When will the else part of try-except-else be executed?

  1. a) always
    b) when an exception occurs
    c) when no exception occurs
    d) when an exception occurs into except block
  2. c) when no exception occurs

The else part is executed when no exception occurs.

What is Python?

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

What are the benefits of using Python?

Python is a general-purpose programming language that has simple, easy-to-learn syntax which emphasizes readability and therefore reduces the cost of program maintenance. Moreover, the language is capable of scripting, completely open-source and supports third-party packages encouraging modularity and code-reuse.
Its high-level data structures, combined with dynamic typing and dynamic binding, attract a huge community of developers for Rapid Application Development and deployment.

What is a dynamically typed language?

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

Type-checking can be done at two stages –

  1. Static – Data Types are checked before execution.
  2. Dynamic – Data Types are checked during execution.

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

What is an Interpreted language?

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

What is PEP and why is it important?

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

How is memory managed in Python?

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

What are Python namespaces? Why are they used?

A namespace in Python ensures that object names in a program are unique and can be used without any conflict. Python implements these namespaces as dictionaries with ‘name as key’ mapped to a corresponding ‘object as value’. This allows for multiple namespaces to use the same name and map it to a separate object. A few examples of namespaces are as follows.

  • Local Namespace includes local names inside a function. the namespace is temporarily created for a function call and gets cleared when the function returns.
  • Global Namespace includes names from various imported packages/ modules that is being used in the current project. This namespace is created when the package is imported in the script and lasts until the execution of the script.
  • Built-in Namespace includes built-in functions of core Python and built-in names for various types of exceptions.

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

What is Scope in Python?

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

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

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

What is Scope Resolution in Python?

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

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

temp = # global-scope variable

 

def func().

temp = # local-scope variable

print(temp)

 

print(temp) # output =>

func() # output =>

print(temp) # output =>

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

temp = # global-scope variable

 

def func().

global temp

temp = # local-scope variable

print(temp)

 

print(temp) # output =>

func() # output =>

print(temp) # output =>

. What are decorators in Python?

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

# decorator function to convert to lowercase

def lowercase_decorator(function).

def wrapper().

func = function()

string_lowercase = func.lower()

return string_lowercase

return wrapper

 

# decorator function to split words

def splitter_decorator(function).

def wrapper().

func = function()

string_split = func.split()

return string_split

return wrapper

 

@splitter_decorator # this is executed next

@lowercase_decorator # this is executed first

def hello().

return ‘Hello World’

 

hello() # output => [ ‘hello’ , ‘world’ ]

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

# decorator function to capitalize names

def names_decorator(function).

def wrapper(arg, arg).

arg = arg.capitalize()

arg = arg.capitalize()

string_hello = function(arg, arg)

return string_hello

return wrapper

 

@names_decorator

def say_hello(name, name).

return ‘Hello ‘ + name + ‘! Hello ‘ + name + ‘!’

 

say_hello(‘sara’, ‘ansh’) # output => ‘Hello Sara! Hello Ansh!’

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

Lists and Tuples are both sequence data types that can store a collection of objects in Python. The objects stored in both sequences can have different data types. Lists are represented with square brackets [‘sara’, , .], while tuples are represented with parantheses (‘ansh’, , .).
But what is the real difference between the two? The key difference between the two is that while lists are mutable, tuples on the other hand are immutable objects. This means that lists can be modified, appended or sliced on-the-go but tuples remain constant and cannot be modified in any manner. You can run the following example on Python IDLE to confirm the difference.

my_tuple = (‘sara’, , , .)

my_list = [‘sara’, , , .]

 

print(my_tuple[]) # output => ‘sara’

print(my_list[]) # output => ‘sara’

 

my_tuple[] = ‘ansh’ # modifying tuple => throws an error

my_list[] = ‘ansh’ # modifying list => list modified

 

print(my_tuple[]) # output => ‘sara’

print(my_list[]) # output => ‘ansh’

What are Dict and List comprehensions?

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

  • Performing mathematical operations on the entire list
  • my_list = [, , , , ]
  • squared_list = [x** for x in my_list] # list comprehension
  • # output => [ , , , , ]
  • squared_dict = {x.x** for x in my_list} # dict comprehension
  • # output => {. , . , . , . , . }
  • Performing conditional filtering operations on the entire list
  • my_list = [, , , , ]
  • squared_list = [x** for x in my_list if x% != ] # list comprehension
  • # output => [ , , , ]
  • squared_dict = {x.x** for x in my_list if x% != } # dict comprehension
  • # output => {. , . , . , . }
  • Combining multiple lists into one
    Comprehensions allow for multiple iterators and hence, can be used to combine multiple lists into one.
  • a = [, , ]
  • b = [, , ]
  • [(x + y) for (x,y) in zip(a,b)] # parallel iterators
  • # output => [, , ]
  • [(x,y) for x in a for y in b] # nested iterators
  • # output => [(, ), (, ), (, ), (, ), (, ), (, ), (, ), (, ), (, )]
  • Flattening a multi-dimensional list
    A similar approach of nested iterators (as above) can be applied to flatten a multi-dimensional list or work upon its inner elements.
  • my_list = [[,,],[,,],[,,]]
  • flattened = [x for temp in my_list for x in temp]
  • # output => [, , , , , , , , ]

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

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

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

  • None Type
    None keyword represents the null values in Python. Boolean equality operation can be performed using these NoneType objects.
Class Name Description
NoneType Represents the NULL values in Python
  • Numeric Types
    There are three distint numeric types – integers, floating-point numbers, and complex numbers. Additionally, booleans are a sub-type of integers.
Class Name Description
int Stores integer literals including hex, octal and binary numbers as integers
float Stores literals containing decimal values and/or exponent sign as floating-point numbers
complex Stores complex number in the form (A + Bj) and has attributes. real and imag
bool Stores boolean value (True or False)
  • Note. The standard library also includes fractions to store rational numbers and decimal to store floating-point numbers with user-defined precision.
  • Sequence Types
    According to Python Docs, there are three basic Sequence Types – lists, tuples, and range objects. Sequence types have the in and not in operators defined for their traversing their elements. These operators share the same priority as the comparison operations.
Class Name Description
list Mutable sequence used to store collection of items.
tuple Immutable sequence used to store collection of items.
range Represents an immutable sequence of numbers generated during execution.
str Immutable sequence of Unicode code points to store textual data.
  • Note. The standard library also includes additional types for processing.
    . Binary data such as bytearray bytes memoryview , and
    . Text strings such as str .
  • Mapping Types
    A mapping object can map hashable values to random objects in Python. Mappings objects are mutable and there is currently only one standard mapping type, the dictionary.
Class Name Description
dict Stores comma-separated list of key. value pairs
  • Set Types
    Currently, Python has two built-in set types – set and frozenset. set type is mutable and supports methods like add() and remove(). frozenset type is immutable and can’t be modified after creation.
Class Name Description
set Mutable unordered collection of distinct hashable objects
frozenset Immutable collection of distinct hashable objects
  • Note. set is mutable and thus cannot be used as key for a dictionary. On the other hand, frozenset is immutable and thus, hashable, and can be used as a dictionary key or as an element of another set.
  • Modules
    Module is an additional built-in type supported by the Python Interpreter. It supports one special operation, i.e., attribute access. mymod.myobj, where mymod is a module and myobj references a name defined in m’s symbol table. The module’s symbol table resides in a very special attribute of the module __dict__, but direct assignment to this module is neither possible nor recommended.
  • Callable Types
    Callable types are the types to which function call can be applied. They can be user-defined functions, instance methods, generator functions, and some other built-in functions, methods and classes.
    Refer the documentation at docs.python.org for a detailed view into the callable types.

What is lambda in Python? Why is it used?

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

  • Assigning lambda functions to a variable
  • mul = lambda a, b . a * b
  • print(mul(, )) # output =>
  • Wrapping lambda functions inside another function
  • def myWrapper(n).
  • return lambda a . a * n
  • mulFive = myWrapper()
  • print(mulFive()) # output =>

What is pass in Python?

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

def myEmptyFunc().

# do nothing

pass

 

myEmptyFunc() # nothing happens

 

## Without the pass keyword

# File “<stdin>”, line

# IndentationError. expected an indented block

How do you copy an object in Python?

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

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

from copy import copy, deepcopy

 

list_ = [, , [, ], ]

 

## shallow copy

 

list_ = copy(list_)

list_[] =

list_[].append()

 

list_ # output => [, , [, , ], ]

list_ # output => [, , [, , ], ]

 

## deep copy

 

list_ = deepcopy(list_)

list_[] =

list_[].append()

 

list_ # output => [, , [, , , ], ]

list_ # output => [, , [, , ], ]

What is the difference between xrange and range in Python?

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

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

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

for i in xrange(). # numbers from o to

print i # output =>

 

for i in xrange(,). # numbers from to

print i # output =>

 

for i in xrange(, , ). # skip by two for next

print i # output =>

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

What are modules and packages in Python?

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

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

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

Packages allow for hierarchial structuring of the module namespace using dot notation. As, modules help avoid clashes between global variable names, in a similary manner, packages help avoid clashes between module names.
Creating a package is easy since it makes use of the system’s inherent file structure. So just stuff the modules into a folder and there you have it, the folder name as the package name. Importing a module or its contents from this package requires the package name as prefix to the module name joined by a dot.

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

What are global, protected and private attributes in Python?

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

What is self in Python?

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

. What is __init__?

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

# class definition

class Student.

def __init__(self, fname, lname, age, section).

self.firstname = fname

self.lastname = lname

self.age = age

self.section = section

 

# creating a new object

stu = Student(“Sara”, “Ansh”, , “A”)

What is break, continue and pass in Python?

Break The break statement terminates the loop immediately
and the control flows to the statement after the body of the loop.
Continue The continue statement terminates the current iteration of the statement,
skips the rest of the code in the current iteration and the control flows to the next iteration of the loop.
Pass As explained above, pass keyword in Python is generally used to fill-up empty blocks
and is similar to an empty statement represented by a semi-colon in languages such as Java, C++, Javascript etc.

 

pat = [, , , , , , , , , ]

 

for p in pat.

pass

if (p == ).

current = p

break

elif (p % == ).

continue

print(p) # output =>

 

print(current) # output =>

What is pickling and unpickling?

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

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

Unpickling
Unpickling is the complete inverse of pickling. It deserializes the byte stream to recreate the objects stored in the file, and loads the object to memory.
The function used for the above process is pickle.load().

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

What are generators in Python?

Generators are functions that return an iterable collection of items, one at a time, in a set manner. Generators, in general, are used to create iterators with a different approach. They employ the use of yield keyword rather than return to return a generator object.
Let’s try and build a generator for fibonacci numbers –

## generate fibonacci numbers upto n

def fib(n).

p, q = ,

while(p < n).

yield p

p, q = q, p + q

 

x = fib() # create generator object

## iterating using __next__(), for Python, use next()

x.__next__() # output =>

x.__next__() # output =>

x.__next__() # output =>

x.__next__() # output =>

x.__next__() # output =>

x.__next__() # output =>

x.__next__() # output =>

x.__next__() # error

## iterating using loop

for i in fib().

print(i) # output =>

What is PYTHONPATH in Python?

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

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

help() function in Python is used to display the documentation of modules, classes, functions, keywords, etc. If no parameter is passed to the help() function, then an interactive help utility is launched on the console.
dir() function tries to return a valid list of attributes and methods of the object it is called upon. It behaves differently with different objects, as it aims to produce the most relevant data, rather than the complete information.

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

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

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

How Python is interpreted?

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

What are unittests in Python?

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

What is docstring in Python?

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

How are arguments passed by value or by reference in python?

  • Pass by value. Copy of the actual object is passed. Changing the value of the copy of the object will not change the value of the original object.
  • Pass by reference. Reference to the actual object is passed. Changing the value of the new object will change the value of the original object.

In Python, arguments are passed by reference, i.e., reference to the actual object is passed.

def appendNumber(arr).

arr.append()

 

arr = [, , ]

 

print(arr) #Output. => [, , ]

appendNumber(arr)

print(arr) #Output. => [, , , ]

What are iterators in Python?

  • Iterator is an object.
  • It remembers its state i.e., where it is during iteration (see code below to see how)
  • __iter__() method initializes an iterator.
  • It has a __next__() method which returns the next item in iteration and points to the next element. Upon reaching the end of iterable object __next__() must return StopIteration exception.
  • It is also self iterable.
  • Iterators are objects with which we can iterate over iterable objects like lists, strings, etc.

class ArrayList.

def __init__(self, number_list).

self.numbers = number_list

 

def __iter__(self).

self.pos =

return self

 

def __next__(self).

if(self.pos < len(self.numbers)).

self.pos +=

return self.numbers[self.pos – ]

else.

raise StopIteration

 

array_obj = ArrayList([, , ])

 

it = iter(array_obj)

 

print(next(it)) #output.

print(next(it)) #output.

 

print(next(it))

#Throws Exception

#Traceback (most recent call last).

#…

#StopIteration

What is slicing in Python?

  • As the name suggests, ‘slicing’ is taking parts of.
  • Syntax for slicing is [start . stop . step]
  • start is the starting index from where to slice a list or tuple
  • stop is the ending index or where to sop.
  • step is the number of steps to jump.
  • Default value for start is , stop is number of items, step is .
  • Slicing can be done on strings, arrays, lists, and tuples.

numbers = [, , , , , , , , , ]

print(numbers[ . . ]) #output . [, , , , ]

Explain how can you make a Python Script executable on Unix?

  • Script file must begin with #!/usr/bin/env python

Explain how to delete a file in Python?

  • Use command os.remove(file_name)

import os

os.remove(“ChangedFile.csv”)

print(“File Removed!”)

Explain split() and join() functions in Python?

  • You can use split() function to split a string based on a delimiter to a list of strings.
  • You can use join() function to join a list of strings based on a delimiter to give a single string.

string = “This is a string.”

string_list = string.split(‘ ‘) #delimiter is ‘space’ character or ‘ ‘

print(string_list) #output. [‘This’, ‘is’, ‘a’, ‘string.’]

print(‘ ‘.join(string_list)) #output. This is a string.

. What is the difference between Python Arrays and lists?

  • Arrays in python can only contain elements of same data types i.e., data type of array should be homogeneous. It is a thin wrapper around C language arrays and consumes far less memory than lists.
  • Lists in python can contain elements of different data types i.e., data type of lists can be heterogeneous. It has the disadvantage of consuming large memory.

import array

 

a = array.array(‘i’, [, , ])

 

for i in a.

print(i, end=‘ ‘) #OUTPUT.

 

a = array.array(‘i’, [, , ‘string’]) #OUTPUT. TypeError. an integer is required (got type str)

 

a = [, , ‘string’]

 

for i in a.

print(i, end=‘ ‘) #OUTPUT. string

What does *args and **kwargs mean?

*args

  • *args is a special syntax used in function definition to pass variable-length argument.
  • “*” means variable length and “args” is the name used by convention. You can use any other.

def multiply(a, b, *argv).

mul = a * b

 

for num in argv.

mul *= num

 

return mul

 

print(multiply(, , , , )) #output.

**kwargs

  • **kwargs is a special syntax used in function definition to pass variable-length keyworded argument.
  • Here, also, “kwargs” is used just by convention. You can use any other name.
  • Keyworded argument means a variable which has a name when passed to a function.
  • It is actually a dictionary of variable name and its value.

def tellArguments(**kwargs).

for key, value in kwargs.items().

print(key + “. ” + value)

tellArguments(arg = “argument “, arg = “argument “, arg = “argument “)

#output.

# arg. argument

# arg. argument

# arg. argument

What are negative indexes and why are they used?

  • Negative indexes are the indexes from the end of the list or tuple or string.
  • Arr[-] means last element of array Arr[]

arr = [, , , , , ]

 

#get the last element

print(arr[-]) #output

 

#get the second last element

print(arr[-]) #output

What is Python?

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

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. It is widely used in data science, machine learning and artificial intelligence domain.

It is easy to learn and require less code to develop the applications.

It is widely used for.

  • Web development (server-side).
  • Software development.
  • Mathematics.
  • System scripting.

Why Python?

  • Python is compatible with different platforms like Windows, Mac, Linux, Raspberry Pi, etc.
  • Python has a simple syntax as compared to other languages.
  • Python allows a developer to write programs with fewer lines than some other programming languages.
  • 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.
  • Python can be described as a procedural way, an object-orientated way or a functional way.

What are the applications of Python?

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

  • Web and Internet Development
  • Games
  • Scientific and computational applications
  • Language development
  • Image processing and graphic design applications
  • Enterprise and business applications development
  • Operating systems
  • 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.

What are the advantages of Python?

  • Interpreted
  • Free and open source
  • Extensible
  • Object-oriented
  • Built-in data structure
  • Readability
  • High-Level Language
  • Cross-platform
    Interpreted. Python is an interpreted language. It does not require prior compilation of code and executes instructions directly.
  • Free and open source. It is an open-source project which is publicly available to reuse. It can be downloaded free of cost.
  • Portable. Python programs can run on cross platforms without affecting its performance.
  • Extensible. It is very flexible and extensible with any module.
  • Object-oriented. Python allows to implement the Object-Oriented concepts to build application solution.
  • Built-in data structure. Tuple, List, and Dictionary are useful integrated data structures provided by the language.

 

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

What is Python’s parameter passing mechanism?

There are two parameters passing mechanism in Python.

  • Pass by references
  • 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 = , and passed to a function where it?s value is modified to a = . 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.

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.

  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. # This line will generate an error
  8. #st = student(“rahul”)
  9. # This line will call the second constructor
  10. st = student(“rahul”, “rahul@gmail.com”)
  11. print(st.name)
  12. Output.
  13. rahul

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

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

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

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.

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.

  1. string = “IT IS IN LOWERCASE.”
  2. print(string.swapcase())
  3. string = “it is in uppercase.”
  4. print(string.swapcase())

it is in lowercase.

IT IS IN UPPERCASE.

How to remove whitespaces from a string in Python?

To remove the whitespaces and trailing spaces from the string, Python providies strip([str]) built-in function. This function returns a copy of the string after removing whitespaces if present. Otherwise returns original string.

  1. string = ”  tecklearn “
  2. string = ”    tecklearn        “
  3. string = ”       tecklearn”
  4. print(string)
  5. print(string)
  6. print(string)
  7. print(“After stripping all have placed in a sequence.”)
  8. print(string.strip())
  9. print(string.strip())
  10. print(string.strip())

tecklearn

tecklearn

tecklearn

After stripping all have placed in a sequence.

tecklearn

tecklearn

tecklearn

How to remove leading whitespaces from a string in the Python?

To remove leading characters from a string, we can use lstrip() function. It is Python string function which takes an optional char type parameter. If a parameter is provided, it removes the character. Otherwise, it removes all the leading spaces from the string.

  1. string = ”  tecklearn “
  2. string = ”    tecklearn        “
  3. print(string)
  4. print(string)
  5. print(“After stripping all leading whitespaces.”)
  6. print(string.lstrip())
  7. print(string.lstrip())

tecklearn

tecklearn

After stripping all leading whitespaces.

tecklearn

tecklearn

 

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.

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

Output.

aRohanb

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.

  1. import random
  2. list = [,,,,,,,];
  3. print(list)
  4. random.shuffle(list)
  5. print (“Reshuffled list . \n”,  list)

[, , , , , , ]

Reshuffled list .

[, , , , , , ]

What is the use of break statement?

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

  1. even = [,,,,,,,]
  2. odd =
  3. for val in even.
  4.     if val%!=.
  5.         odd = val
  6.         break
  7.     print(val)
  8. print(“odd value found”,odd)

 

 

 

odd value found

Python Break statement flowchart.

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.

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

(, , , )

 

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

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

tup[]=

TypeError. ‘tuple’ object does not support item assignment

(, , , )

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.

What are the different file processing modes supported by Python?

Python provides three modes to open files. The read-only, write-only, read-write and append mode. ‘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.

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

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

For example.

  1. -a # Unary
  2.  +  =  # Binary
  3. Here, “+” and “=” are operators.
  4. a, b = ,
  5. # Assign minimum value using ternary operator
  6. min = a if a < b else b
  7. print(min)

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.

  • Arithmetic OperatorsRelational Operators
  • Assignment Operators
  • Logical Operators
  • Membership Operators
  • Identity Operators
  • Bitwise Operators

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

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

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

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

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

  1. # Examples of Assignment operators
  2. a=
  3. print(a) #
  4. a +=
  5. print(a) #
  6. a -=
  7. print(a) #
  8. a *=
  9. print(a) #
  10. a **=
  11. print(a) #

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

  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

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.

  1. # Membership operators examples
  2. list = [,,,,,]
  3. print( in list) # False
  4. cities = (“india”,”delhi”)
  5. print(“tokyo” not in cities) #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.

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

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

  1. # Identity operator example
  2. a =
  3. b =
  4. print(a & b) #
  5. print(a | b) #
  6. print(a ^ b) #
  7. print(~a) # –

How to create a Unicode string in Python?

In Python , 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-“) function.

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.

What is the Python decorator?

Decorators are very powerful and a useful tool in Python that allows the programmers to modify the behaviour of any class or function. It allows us to wrap another function to extend the behaviour of the wrapped function, without permanently modifying it.

  1. # Decorator example
  2. def decoratorfun().
  3.     return another_fun

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.

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

In Python, variables that are only referenced inside a function are called implicitly global. If a variable is assigned a new value anywhere within the function’s body, it’s assumed to be a local. 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. Local variables are accessible within local body only. Global variables are accessible anywhere in the program, and any function can access and modify its value.

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.

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.

Let’s take an 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 dict[Country]
  3. India
  4. >>>print dict[Hero]
  5. Modi
  6. >>>print dict[Cartoon]
  7. Rahul

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, this pass keyword helps to pass the control without error.

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

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”

What is a negative index in Python?

Python sequences are accessible using an index in positive and negative numbers. For example, is the first positive index, is the second positive index and so on. For negative indexes – is the last negative index, – is the second last negative index and so on.

Index traverses from left to right and increases by one until end of the list.

Negative index traverse from right to left and iterate one by one till the start of the list. A negative index is used to traverse the elements into reverse order.

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.

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

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.

How can we make forms in Python?

You have to import CGI module to access form fields using FieldStorage class.

Attributes of class FieldStorage for the form.

form.name. The name of the field, if specified.

form.filename. If an FTP transaction, the client-side filename.

form.value. The value of the field as a string.

form.file. file object from which data read.

form.type. The content type, if applicable.

form.type_options. The options of the ‘content-type’ line of the HTTP request, returned as a dictionary.

form.disposition. The field ‘content-disposition’; None, if unspecified.

form.disposition_options. The options for ‘content-disposition’.

form.headers. All of the HTTP headers returned as a dictionary.

  1. import cgi
  2. form = cgi.FieldStorage()
  3. if not (form.has_key(“name”) and form.has_key(“age”)).
  4. print “<H>Name & Age not Entered</H>”
  5. print “Fill the Name & Age accurately.”
  6. return
  7. print “<p>name.”, form[“name”].value
  8. print “<p>Age.”, form[“age”].value

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.

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.

  1. with open(“file-name”, “r”) as fp.
  2. fileData = fp.read()
  3. #to print the contents of the file
  4. print(fileData)

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.

  1. For i,v in enumerate([‘Python’,’Java’,’C++’]).
  2. print(i,v)
  3.  Python
  4.  Java
  5.  C++
  6. # enumerate using an index sequence
  7. for count, item in enumerate([‘Python’,’Java’,’C++’], ).

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.

  1. import smtplib
  2. # Calling SMTP
  3. s = smtplib.SMTP(‘smtp.gmail.com’, )
  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_you_need_to_send”
  10. # sending the mail
  11. s.sendmail(“sender_email_id”, “receiver_email_id”, message)

It will send an email to the receiver after authenticating sender username and password.

What is the difference between list and tuple?

The difference between list and tuple is that a list is mutable while tuple is not.

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.

Why do lambda forms in Python not have the statements?

Because it is used to make the new function object and return them in runtime.

How can you convert a number to string?

We can use the inbuilt function str() to convert a number into a string. If you want an octal or hexadecimal representation, we can use the oct() or hex() inbuilt function.

Mention the rules for local and global variables in Python?

Local variables. If a new value is assigned by a variable within the function’s body, it is assumed to be local.

Global variables. These are the variables that are only referenced inside a function are implicitly global.

Explain Python?

Python is a highly comprehensive, interactive, and object-oriented scriptwriting language. It is specifically developed with the purpose of making the content highly readable among the net surfers. Python makes use of various English keywords other than just punctuations. It also has lesser syntactical constructions like in other languages.

What are the distinct features of Python?

The distinct features of Python include the following.

  1. Structured and functional programmings are supported.
  2. It can be compiled to byte-code for creating larger applications.
  3. Develops high-level dynamic data types.
  4. Supports checking of dynamic data types.
  5. Applies automated garbage collection.
  6. It could be used effectively along with Java, COBRA, C, C++, ActiveX, and COM.

What is Pythonpath?

A Pythonpath tells the Python interpreter to locate the module files that can be imported into the program. It includes the Python source library directory and source code directory.

Can we preset Pythonpath?

Yes, we can preset Pythonpath as a Python installer.

Why do we use Pythonstartup environment variable?

We use the Pythonstartup environment variable because it consists of the path in which the initialization file carrying Python source code can be executed to start the interpreter.

What is the Pythoncaseok environment variable?

Pythoncaseok environment variable is applied in Windows with the purpose to direct Python to find the first case insensitive match in an import statement.

What are the supported standard data types in Python?

The supported standard data types in Python include the following.

  1. List.
  2. Number.
  3. String.
  4. Dictionary.
  5. Tuples.

Define tuples in Python?

Tuples is a sequence data type in Python. The number of values in tuples are separated by commas.

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 Lists
Tuples are similar to a list, but they are enclosed within parenthesis, 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 cannot be updated. They can be updated.
They act as read-only lists. They act as a changeable list.
Tuples are surrounded by ( ) Lists are surrounded by [ ]
Example of Tuple Code is, tup = (, “a”, “string”, +) Example of Lists Code is, L = [, “a” , “string” , +]

What are the positive and negative indices?

In the positive indices are applied the search beings from left to the right. In the case of the 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 , then comes and until the last index is n-. However, in the negative index, the first index is -n, then -(n-) until the last index will be -.

What can be the length of the identifier in Python?

The length of the identifier in Python can be of any length. The longest identifier will violate from PEP – and PEP – .

Define Pass statement in Python?

A Pass statement in Python is used when we cannot decide what to do in our code, but we must type something for making syntactically correct.

What are the limitations of Python?

There are certain limitations of Python, which include the following.

  1. It has design restrictions.
  2. It is slower when compared with C and C++ or Java.
  3. It is inefficient in mobile computing.
  4. It consists of an underdeveloped database access layer.

Do runtime errors exist in Python? Give an example?

Yes, runtime errors exist in Python. For example, if you are duck typing and things look like a duck, then it is considered as a duck even if that is just a flag or stamp or any other thing. The code, in this case, would be A Run-time error. For example, Print “Hackr io”, then the runtime error would be the missing parenthesis that is required by print ( ).

Can we reverse a list in Python?

Yes, we can reserve a list in Python using the reverse() method. The code can be depicted as follows.

def reverse(s).
str = “”
for i in s.
str = i + str
return str

Why do we need a break in Python?

Break helps in controlling the Python loop by breaking the current loop from execution and transfer the control to the next block.

Why do we need a continue in Python?

A continue also helps in controlling the Python loop but by making jumps to the next iteration of the loop without exhausting it.

Can we use a break and continue together in Python? How?

Break and continue can be used together in Python. The break will stop the current loop from execution, while jump will take to another loop.

Does Python support an intrinsic do-while loop?

No Python does not support an intrinsic do-while loop.

How many ways can be applied for applying reverse string?

There are five ways in which the reverse string can be applied which include the following.

  1. Loop
  2. Recursion
  3. Stack
  4. Extended Slice Syntax
  5. Reversed

What are the different stages of the Life Cycle of a Thread?

The different stages of the Life Cycle of a Thread can be stated as follows.

  • Stage . Creating a class where we can override the run method of the Thread class.
  • Stage . We make a call to start() on the new thread. The thread is taken forward for scheduling purposes.
  • Stage . Execution takes place wherein the thread starts execution, and it reaches the running state.
  • Stage . Thread wait until the calls to methods including join() and sleep() takes place.
  • Stage . After the waiting or execution of the thread, the waiting thread is sent for scheduling.
  • Stage . Running thread is done by executing the terminates and reaches the dead state.

What is the purpose of relational operators in Python?

The purpose of relational operators in Python is to compare values.

What are assignment operators in Python?

The assignment operators in Python can help in combining all the arithmetic operators with the assignment symbol.

Why do we need membership operators in Python?

We need membership operators in Python with the purpose to confirm if the value is a member in another or not.

How are identity operators different than the membership operators?

Unlike membership operators, the identity operators compare the values to find out if they have the same value or not.

Describe how multithreading is achieved in Python.

Even though Python comes with a multi-threading package, if the motive behind multithreading is to speed the code then using the package is not the go-to option.

The package has something called the GIL or Global Interpreter Lock, which is a construct. It ensures that one and only one of the threads execute at any given time. A thread acquires the GIL and then do some 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. Moreover, GIL passing adds to the overall overhead to the execution.

Hence, if you intend to use the threading package for speeding up the execution, using the package is not recommended.

Draw a comparison between the range and xrange in Python.

In terms of functionality, both range and xrange are identical. Both allow for generating a list of integers. The main difference between the two is that while range returns a Python list object, xrange returns an xrange object.

Xrange is not able to generate a static list at runtime the way range does. On the contrary, it creates values along with the requirements via a special technique called yielding. It is used with a type of object known as generators.

If you have a very enormous range for which you need to generate a list, then xrange is the function to opt for. This is especially relevant for scenarios dealing with a memory-sensitive system, such as a smartphone.

The range is a memory beast. Using it requires much more memory, especially if the requirement is gigantic. Hence, in creating an array of integers to suit the needs, it can result in a Memory Error and ultimately lead to crashing the program.

Explain Inheritance and its various types in Python?

Inheritance enables a class to acquire all the 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 or base class or the parent class. There are forms of inheritance supported by Python.

  • Single Inheritance – A single derived class acquires from on single superclass.
  • Multi-Level Inheritance – At least different derived classes acquire from two distinct base classes.
  • Hierarchical Inheritance – A number of child classes acquire from one superclass
  • Multiple Inheritance – A derived class acquires from several superclasses.

Explain how is it possible to Get the Google cache age of any URL or webpage using Python.

In order to Get the Google cache age of any URL or webpage using Python, the following URL format is used.

http.//webcache.googleusercontent.com/search?q=cache.URLGOESHERE

Simply replace URLGOESHERE with the web address of the website or webpage whose cache you need to retrieve and see in Python.

Give a detailed explanation about setting up the database in Django.

The process of setting up a database is initiated by using the command edit mysite/setting.py. This is a normal Python module with a module-level representation of Django settings. Django relies on SQLite by default, which is easy to be used as it doesn’t require any other installation.

SQLite stores data as a single file in the filesystem. Now, you need to tell Django how to use the database. For this, the project’s setting.py file needs to be used. Following code must be added to the file for making the database workable with the Django project.

DATABASES = {

‘default’. {

‘ENGINE’ . ‘django.db.backends.sqlite’,

‘NAME’ . os.path.join(BASE_DIR, ‘db.sqlite’),

}

}

If you need to use a database server other than the SQLite, such as MS SQL, MySQL, and PostgreSQL, then you need to use the database’s administration tools to create a brand new database for your Django project.

You have to modify the following keys in the DATABASE ‘default’ item to make the new database work with the Django project.

  • ENGINE – For example, when working with a MySQL database replace ‘django.db.backends.sqlite’ with ‘django.db.backends.mysql’
  • NAME – Whether using SQLite or some other database management system, the database is typically a file on the system. The NAME should contain the full path to the file, including the name of that particular file.

NOTE. – Settings like Host, Password, and User needs to be added when not choosing SQLite as the database.

How will you differentiate 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 execution of a program slower. This is due to the fact that it makes some copies for each object that is called.

How will you distinguish between NumPy and SciPy?

Typically, NumPy contains nothing but the array data type and the most basic operations, such as basic element-wise functions, indexing, reshaping, and sorting. All the numerical code resides in SciPy.

As one of NumPy’s most important goals is compatibility, the library tries to retain all features supported by either of its predecessors. Hence, NumPy contains a few linear algebra functions despite the fact that these more appropriately belong to the SciPy library.

SciPy contains fully-featured versions of the linear algebra modules available to NumPy in addition to several other numerical algorithms.

Observe the following code.

A = dict(zip((‘a’,’b’,’c’,’d’,’e’),(,,,,)))

A = range()A = sorted([i for i in A if i in A])

A = sorted([A[s] for s in A])

A = [i for i in A if i in A]

A =

A = [[i,i*i] for i in A]

print(A,A,A,A,A,A,A)

Write down the output of the code.

 

A = {‘a’. , ‘c’. , ‘b’. , ‘e’. , ‘d’. } # the order may vary
A = range(, )
A = []
A = [, , , , ]
A = [, , , , ]
A =
A = [[, ], [, ], [, ], [, ], [, ], [, ], [, ], [, ], [, ], [, ]]

Python has something called the dictionary. Explain using an example.

A dictionary in Python programming language is an unordered collection of data values such as a map. Dictionary holds key.value pair. It helps in defining 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 the example will be.

dict={‘Website’.‘hackr.io’,‘Language’.‘Python’.‘Offering’.‘Tutorials’}

print dict[Website] #Prints hackr.io

print dict[Language] #Prints Python

print dict[Offering] #Prints Tutorials

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 as the first index, as the second index, and so on. Hence, any index for a positive number n is n-.

Unlike positive numbers, index numbering for the negative numbers start from – and it represents the last index in the sequence. Likewise, – 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[.-]
  • Showing the index to representing the string in the correct order

Suppose you need to collect and print data from IMDb top Movies page. Write a program in Python for doing so. (NOTE. – You can limit the displayed information for fields; namely movie name, release year, and rating.)

 

from bs import BeautifulSoup

import requests

import sys

url = ‘http.//www.imdb.com/chart/top’

response = requests.get(url)

soup = BeautifulSoup(response.text)

tr = soup.findChildren(“tr”)

tr = iter(tr)

next(tr)

for movie in tr.

title = movie.find(‘td’, {‘class’. ‘titleColumn’} ).find(‘a’).contents[]

year = movie.find(‘td’, {‘class’. ‘titleColumn’} ).find(‘span’, {‘class’. ‘secondaryInfo’}).contents[]

rating = movie.find(‘td’, {‘class’. ‘ratingColumn imdbRating’} ).find(‘strong’).contents[]

row = title + ‘ – ‘ + year + ‘ ‘ + ‘ ‘ + rating

print(row)

Take a look at the following code.

try. if ” != .
raise “someError”
else. print(“someError has not occured”)
except “someError”. pr
int (“someError has occured”)

What will be the output?

The output of the program will be “invalid code.” This is because a new exception class must inherit from a BaseException.

What do you understand by monkey patching in Python?

The dynamic modifications made to a class or module at runtime are termed as monkey patching in Python. Consider the following code snippet.

# m.py

class MyClass.

def f(self).

print “f()”

We can monkey-patch the program something like this.

import m

def monkey_f(self).

print “monkey_f()”

m.MyClass.f = monkey_f

obj = m.MyClass()

obj.f()

The output for the program will be monkey_f().

The examples demonstrate changes made in the behavior of f() in MyClass using the function we defined i.e. monkey_f() outside of the module m.

What do you understand by the process of compilation and linking in Python?

In order to compile new extensions without any error, compiling and linking is used in Python. Linking initiates only and only when the compilation is complete.

In the case of dynamic loading, the process of compilation and linking depends on the style that is provided with the concerned system. In order to provide dynamic loading of the configuration setup files and rebuilding the interpreter, the Python interpreter is used.

What is Flask and what are the benefits of using it?

Flask is a web microframework for Python with Jinja and Werkzeug as its dependencies. As such, it has some notable advantages.

  • Flask has little to no dependencies on external libraries
  • Because there is a little external dependency to update and fewer security bugs, the web microframework is lightweight to use.
  • Features an inbuilt development server and a fast debugger.

What is the map() function used for in Python?

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

What is Pickling and Unpickling in Python?

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.

The reverse process of pickling is known as unpickling i.e. retrieving original Python objects from a stored string representation.

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

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

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

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

Write a program in Python for getting indices of N maximum values in a NumPy array.

 

import numpy as np

arr = np.array([, , , , ])

print(arr.argsort()[-.][..-])

Output.

[ ]

Write code to show randomizing the items of a list in place in Python along with the output.

from random import shuffle

x = [‘hackr.io’, ‘Is’, ‘The’, ‘Best’, ‘For’, ‘Learning’, ‘Python’]

shuffle(x)

print(x)

Output.

[‘For’, ‘Python’, ‘Learning’, ‘Is’, ‘Best’, ‘The’, ‘hackr.io’]

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

What is the lambda function?

An anonymous function is known as a lambda function. This function can have only one statement but can have any number of parameters.

a = lambda x,y . x+y
print(a(, ))

What are Python decorators?

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

Differentiate between list and tuple.

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

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.

What are the built-in types provided by the Python?

Mutable built-in types.

  • Lists
  • Sets
  • Dictionaries

Immutable built-in types.

  • Strings
  • Tuples
  • Numbers

How a file is deleted in Python?

The file can be deleted by either of these commands.

os.remove(filename)
os.unlink(filename)

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.

Python has built-in modules some of which are.

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

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

The // is a Floor Divisionoperator used for dividing two operands with the result as quotient displaying digits before the decimal point. For instance, // = and .//. = ..

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.

Explain the Dogpile effect.

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

What is a pass in Python?

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

Is Python a case sensitive language?

Yes Python is a case sensitive language.

Define slicing in Python.

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

What are docstring?

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

What is [..-} used for?

[..-} reverses the order of an array or a sequence. However, the original array or the list remains unchanged.

import array as arr
Num_Array=arr.array(‘k’,[,,,,])
Num_Array[..-]

Define Python Iterators.

Group of elements, containers or objects that can be traversed.

How are comments written in Python?

Comments in Python start with a # character, they can also be written within docstring(String within triple quotes)

How to capitalize the first letter of string?

Capitalize() method capitalizes the first letter of the string, and if the letter is already capital it returns the original string

What is, not and in operators?

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

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

How are files deleted in Python?

To delete a file in Python.

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

How are modules imported in Python?

Modules are imported using the import keyword by either of the following three ways.

import array
import array as arr
from array import *

What is monkey patching?

Dynamic modifications of a class or module at run-time refers to a monkey patch.

Does Python supports multiple inheritances?

Yes, in Python a class can be derived from more than one parent class.

What does the method object() do?

The method returns a featureless object that is base for all classes. This method does not take any parameters.

What is pep ?

Python Enhancement Proposal or pep is a set of rules that specify how to format Python code for maximum readability.

What is namespace in Python?

A naming system used to make sure that names are unique to avoid naming conflicts refers to as Namespace.

Is indentation necessary in Python?

Indentation is required in Python if not done properly the code is not executed properly and might throw errors. Indentation is usually done using four space characters.

Define a function in Python

A block of code that is executed when it is called is defined as a function. Keyword def is used to define a Python function.

Define self in Python

An instance of a class or an object is self in Python. It is included as the first parameter. It helps to differentiate between the methods and attributes of a class with local variables.

What is Python, what are the benefits of using it, and what do you understand of PEP ?

Python is one of the most successful interpreted languages. When you write a Python script, it doesn’t need to get compiled before execution. Few other interpreted languages are PHP and Javascript.

Benefits of Python Programming

  • Python is a dynamic-typed language. It means that you don’t need to mention the data type of variables during their declaration. It allows to set variables like var= and var =” You are an engineer.” without any error.
  • Python supports object orientated programming as you can define classes along with the composition and inheritance. It doesn’t use access specifiers like public or private).
  • Functions in Python are like first-class objects. It suggests you can assign them to variables, return from other methods and pass as arguments.
  • Developing using Python is quick but running it is often slower than compiled languages. Luckily, Python enables to include the “C” language extensions so you can optimize your scripts.
  • Python has several usages like web-based applications, test automation, data modeling, big data analytics and much more. Alternatively, you can utilize it as a “glue” layer to work with other languages.

PEP .

PEP is the latest Python coding standard, a set of coding recommendations. It guides to deliver more readable Python code.

What is the output of the following Python code fragment? Justify your

def extendList(val, list=[]).

list.append(val)

return list

 

list = extendList()

list = extendList(,[])

list = extendList(‘a’)

 

print “list = %s” % list

print “list = %s” % list

print “list = %s” % list

The result of the above Python code snippet is.

list = [, ‘a’]

list = []

list = [, ‘a’]

You may erroneously expect list to be equal to [] and list to match with [‘a’], thinking that the list argument will initialize to its default value of [] every time there is a call to the extendList.

However, the flow is like that a new list gets created once after the function is defined. And the same get used whenever someone calls the extendList method without a list argument. It works like this because the calculation of expressions (in default arguments) occurs at the time of function definition, not during its invocation.

The list and list are hence operating on the same default list, whereas list is running on a separate object that it has created on its own (by passing an empty list as the value of the list parameter).

The definition of the extendList function can get changed in the following manner.

def extendList(val, list=None).

if list is None.

list = []

list.append(val)

return list

With this revised implementation, the output would be.

list = []

list = []

list = [‘a’]

What is the statement that can be used in Python if the program requires no action but requires it syntactically?

The pass statement is a null operation. Nothing happens when it executes. You should use “pass” keyword in lowercase. If you write “Pass,” you’ll face an error like “NameError. name Pass is not defined.” Python statements are case sensitive.

letter = “hai sethuraman”

for i in letter.

if i == “a”.

pass

print(“pass statement is execute …………..”)

else.

print(i)

What’s the process to get the home directory using ‘~’ in Python?

You need to import the os module, and then just a single line would do the rest.

import os

print (os.path.expanduser(‘~’))

Output.

/home/runner

What are the built-in types available in Python?

Here is the list of most commonly used built-in types that Python supports.

  • Immutable built-in datatypes of Python
    • Numbers
    • Strings
    • Tuples
  • Mutable built-in datatypes of Python
    • List
    • Dictionaries
    • Sets

How to find bugs or perform static analysis in a Python application?

  • You can use PyChecker, which is a static analyzer. It identifies the bugs in Python project and also reveals the style and complexity related bugs.
  • Another tool is Pylint, which checks whether the Python module satisfies the coding standard.

When is the Python decorator used?

Python decorator is a relative change that you do in Python syntax to adjust the functions quickly.

What is the principal difference between a list and the tuple?

List vs. Tuple.

The principal difference between a list and the tuple is that the former is mutable while the tuple is not.

A tuple is allowed to be hashed, for example, using it as a key for dictionaries.

How does Python handle memory management?

  • Python uses private heaps to maintain its memory. So the heap holds all the Python objects and the data structures. This area is only accessible to the Python interpreter; programmers can’t use it.
  • And it’s the Python memory manager that handles the Private heap. It does the required allocation of the memory for Python objects.
  • Python employs a built-in garbage collector, which salvages all the unused memory and offloads it to the heap space.

What are the principal differences between the lambda and def?

Lambda vs. def.

  • Def can hold multiple expressions while lambda is a uni-expression function.
  • Def generates a function and designates a name to call it later. Lambda forms a function object and returns it.
  • Def can have a return statement. Lambda can’t have return statements.
  • Lambda supports to get used inside a list and dictionary.

Write a reg expression that confirms an email id using the python reg expression module “re”?

Python has a regular expression module “re.”

Check out the “re” expression that can check the email id for .com and .co.in subdomain.

import re

print(re.search(r”[-a-zA-Z.]+@[a-zA-Z]+\.(com|co\.in)$”,”micheal.pages@mp.com”))

What do you think is the output of the following code fragment? Is there any error in the code?

list = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]

print (list[.])

The result of the above lines of code is []. There won’t be any error like an IndexError.

You should know that trying to fetch a member from the list using an index that exceeds the member count (for example, attempting to access list[] as given in the question) would yield an IndexError. By the way, retrieving only a slice at the starting index that surpasses the no. of items in the list won’t result in an IndexError. It will just return an empty list.

Is there a switch or case statement in Python? If not then what is the reason for the same?

No, Python does not have a Switch statement, but you can write a Switch function and then use it.

What is a built-in function that Python uses to iterate over a number sequence?

Range() generates a list of numbers, which is used to iterate over for loops.

for i in range().

print(i)

The range() function accompanies two sets of parameters.

  • range(stop)
    • stop. It is the no. of integers to generate and starts from zero. eg. range() == [, , ].
  • range([start], stop[, step])
    • Start. It is the starting no. of the sequence.
    • Stop. It specifies the upper limit of the sequence.
    • Step. It is the incrementing factor for generating the sequence.
  • Points to note.
    • Only integer arguments are allowed.
    • Parameters can be positive or negative.
    • The range() function in Python starts from the zeroth index.

What are the optional statements possible inside a try-except block in Python?

There are two optional clauses you can use in the try-except block.

  • The “else” clause
    • It is useful if you want to run a piece of code when the try block doesn’t create an exception.
  • The “finally” clause
    • It is useful when you want to execute some steps which run, irrespective of whether there occurs an exception or not.

What is a string in Python?

A string in Python is a sequence of alpha-numeric characters. They are immutable objects. It means that they don’t allow modification once they get assigned a value. Python provides several methods, such as join(), replace(), or split() to alter strings. But none of these change the original object.

What is slicing in Python?

Slicing is a string operation for extracting a part of the string, or some part of a list. In Python, a string (say text) begins at index , and the nth character stores at position text[n-]. Python can also perform reverse indexing, i.e., in the backward direction, with the help of negative numbers. In Python, the slice() is also a constructor function which generates a slice object. The result is a set of indices mentioned by range(start, stop, step). The slice() method allows three parameters. . start – starting number for the slicing to begin. . stop – the number which indicates the end of slicing. . step – the value to increment after each index (default = ).

What is %s in Python?

Python has support for formatting any value into a string. It may contain quite complex expressions.

One of the common usages is to push values into a string with the %s format specifier. The formatting operation in Python has the comparable syntax as the C function printf() has.

Is a string immutable or mutable in Python?

Python strings are indeed immutable.

Let’s take an example. We have an “str” variable holding a string value. We can’t mutate the container, i.e., the string, but can modify what it contains that means the value of the variable.

What is the index in Python?

An index is an integer data type which denotes a position within an ordered list or a string.

In Python, strings are also lists of characters. We can access them using the index which begins from zero and goes to the length minus one.

For example, in the string “Program,” the indexing happens like this.

Program

What is Docstring in Python?

A docstring is a unique text that happens to be the first statement in the following Python constructs.

Module, Function, Class, or Method definition.

A docstring gets added to the __doc__ attribute of the string object.

Now, read some of the Python interview questions on functions.

What is a function in Python programming?

A function is an object which represents a block of code and is a reusable entity. It brings modularity to a program and a higher degree of code reusability.

Python has given us many built-in functions such as print() and provides the ability to create user-defined functions.

How many basic types of functions are available in Python?

Python gives us two basic types of functions.

. Built-in, and

. User-defined.

The built-in functions happen to be part of the Python language. Some of these are print(), dir(), len(), and abs() etc.

How do we write a function in Python?

We can create a Python function in the following manner.

Step-. to begin the function, start writing with the keyword def and then mention the function name.

Step-. We can now pass the arguments and enclose them using the parentheses. A colon, in the end, marks the end of the function header.

Step-. After pressing an enter, we can add the desired Python statements for execution.

What is a function call or a callable object in Python?

A function in Python gets treated as a callable object. It can allow some arguments and also return a value or multiple values in the form of a tuple. Apart from the function, Python has other constructs, such as classes or the class instances which fits in the same category.

What is the return keyword used for in Python?

The purpose of a function is to receive the inputs and return some output.

The return is a Python statement which we can use in a function for sending a value back to its caller.

What is “Call by Value” in Python?

In call-by-value, the argument whether an expression or a value gets bound to the respective variable in the function.

Python will treat that variable as local in the function-level scope. Any changes made to that variable will remain local and will not reflect outside the function.

What is “Call by Reference” in Python?

We use both “call-by-reference” and “pass-by-reference” interchangeably. When we pass an argument by reference, then it is available as an implicit reference to the function, rather than a simple copy. In such a case, any modification to the argument will also be visible to the caller.

This scheme also has the advantage of bringing more time and space efficiency because it leaves the need for creating local copies.

On the contrary, the disadvantage could be that a variable can get changed accidentally during a function call. Hence, the programmers need to handle in the code to avoid such uncertainty.

What is the return value of the trunc() function?

The Python trunc() function performs a mathematical operation to remove the decimal values from a particular expression and provides an integer value as its output.

Is it mandatory for a Python function to return a value?

It is not at all necessary for a function to return any value. However, if needed, we can use None as a return value.

What does the continue do in Python?

The continue is a jump statement in Python which moves the control to execute the next iteration in a loop leaving all the remaining instructions in the block unexecuted.

The continue statement is applicable for both the “while” and “for” loops.

What is the purpose of id() function in Python?

The id() is one of the built-in functions in Python.

Signature. id(object)

It accepts one parameter and returns a unique identifier associated with the input object.

What does the *args do in Python?

We use *args as a parameter in the function header. It gives us the ability to pass N (variable) number of arguments.

Please note that this type of argument syntax doesn’t allow passing a named argument to the function.

Example of using the *args.

# Python code to demonstrate

# *args for dynamic arguments

def fn(*argList).

for argx in argList.

print (argx)

fn(‘I’, ‘am’, ‘Learning’, ‘Python’)

The output.

I

am

Learning

Python

What is PEP ?

PEP is defined as a document that helps us to provide the guidelines on how to write the Python code. It was written by Guido van Rossum, Barry Warsaw and Nick Coghlan in .

It stands for Python Enhancement Proposal, and its major task is to improve the readability and consistency of Python code.

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.

E.g..

“Aman”, ”.

Numeric Literals

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

  1. # Integer literal
  2. a =
  3. #Float Literal
  4. b = .
  5. #Complex Literal
  6. x = .j

Boolean Literals

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

  1. # Boolean literal
  2. isboolean = True

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 two types of functions.

  • Built-In Functions. copy(), len(), count() are the some built-in functions.
  • User-defined Functions. Functions which are defined by a user known as user-defined functions.

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

  1. def function_name(parameters list).
  2.     #— statements—
  3.     return a_value

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(iterator, iterator, iterator …)

Parameters

iterator, iterator, iterator. These are iterator objects that are joined together.

Return

It returns an iterator from two or more iterators.

What does the **kwargs do in Python?

We can also use the **kwargs syntax in a Python function declaration. It let us pass N (variable) number of arguments which can be named or keyworded.

Example of using the **kwargs.

# Python code to demonstrate

# **kwargs for dynamic + named arguments

def fn(**kwargs).

for emp, age in kwargs.items().

print (“%s’s age is %s.” %(emp, age))

fn(John=, Kalley=, Tom=)

The output.

John’s age is .

Kalley’s age is .

Tom’s age is .

Does Python have a Main() method?

The main() is the entry point function which happens to be called first in most programming languages.

Since Python is interpreter-based, so it sequentially executes the lines of the code one-by-one.

Python also does have a Main() method. But it gets executed whenever we run our Python script either by directly clicking it or starts it from the command line.

We can also override the Python default main() function using the Python if statement. Please see the below code.

print(“Welcome”)

print(“__name__ contains. “, __name__)

def main().

print(“Testing the main function”)

if __name__ == ‘__main__’.

main()

The output.

Welcome

__name__ contains. __main__

Testing the main function

What does the __ Name __ do in Python?

The __name__ is a unique variable. Since Python doesn’t expose the main() function, so when its interpreter gets to run the script, it first executes the code which is at level indentation.

To see whether the main() gets called, we can use the __name__ variable in an if clause compares with the value “__main__.”

What is the purpose of “end” in Python?

Python’s print() function always prints a newline in the end. The print() function accepts an optional parameter known as the ‘end.’ Its value is ‘\n’ by default. We can change the end character in a print statement with the value of our choice using this parameter.

# Example. Print a instead of the new line in the end.

print(“Let’s learn” , end = ‘ ‘)

print(“Python”)

 

# Printing a dot in the end.

print(“Learn to code from techbeamers” , end = ‘.’)

print(“com”, end = ‘ ‘)

The output is.

Let’s learn Python

Learn to code from techbeamers.com

When should you use the “break” in Python?

Python provides a break statement to exit from a loop. Whenever the break hits in the code, the control of the program immediately exits from the body of the loop.

The break statement in a nested loop causes the control to exit from the inner iterative block.

What is the difference between pass and continue in Python?

The continue statement makes the loop to resume from the next iteration.

On the contrary, the pass statement instructs to do nothing, and the remainder of the code executes as usual.

What does the len() function do in Python?

In Python, the len() is a primary string function. It determines the length of an input string.

>>> some_string = ‘techbeamers’

>>> len(some_string)

What does the chr() function do in Python?

The chr() function got re-added in Python .. In version ., it got removed.

It returns the string denoting a character whose Unicode code point is an integer.

For example, the chr() returns the string ‘z’ whereas the chr() returns the string ‘Ҽ’.

What does the ord() function do in Python?

The ord(char) in Python takes a string of size one and returns an integer denoting the Unicode code format of the character in case of a Unicode type object, or the value of the byte if the argument is of -bit string type.

>>> ord(“z”)

What is Rstrip() in Python?

Python provides the rstrip() method which duplicates the string but leaves out the whitespace characters from the end.

The rstrip() escapes the characters from the right end based on the argument value, i.e., a string mentioning the group of characters to get excluded.

The signature of the rstrip() is.

str.rstrip([char sequence/pre>

#Example

test_str = ‘Programming ‘

# The trailing whitespaces are excluded

print(test_str.rstrip())

What is whitespace in Python?

Whitespace represents the characters that we use for spacing and separation.

They possess an “empty” representation. In Python, it could be a tab or space.

What is isalpha() in Python?

Python provides this built-in isalpha() function for the string handling purpose.

It returns True if all characters in the string are of alphabet type, else it returns False.

How do you use the split() function in Python?

Python’s split() function works on strings to cut a large piece into smaller chunks, or sub-strings. We can specify a separator to start splitting, or it uses the space as one by default.

#Example

str = ‘pdf csv json’

print(str.split(” “))

print(str.split())

The output.

[‘pdf’, ‘csv’, ‘json’]

[‘pdf’, ‘csv’, ‘json’]

What does the join method do in Python?

Python provides the join() method which works on strings, lists, and tuples. It combines them and returns a united value.

What does the Title() method do in Python?

Python provides the title() method to convert the first letter in each word to capital format while the rest turns to Lowercase.

#Example

str = ‘lEaRn pYtHoN’

print(str.title())

The output.

Learn Python

Now, check out some general purpose Python interview questions.

What makes the CPython different from Python?

CPython has its core developed in C. The prefix ‘C’ represents this fact. It runs an interpreter loop used for translating the Python-ish code to C language.

Which package is the fastest form of Python?

PyPy provides maximum compatibility while utilizing CPython implementation for improving its performance.

The tests confirmed that PyPy is nearly five times faster than the CPython. It currently supports Python ..

What is GIL in Python language?

Python supports GIL (the global interpreter lock) which is a mutex used to secure access to Python objects, synchronizing multiple threads from running the Python bytecodes at the same time.

How is Python thread safe?

Python ensures safe access to threads. It uses the GIL mutex to set synchronization. If a thread loses the GIL lock at any time, then you have to make the code thread-safe.

For example, many of the Python operations execute as atomic such as calling the sort() method on a list.

How does Python manage the memory?

Python implements a heap manager internally which holds all of its objects and data structures.

This heap manager does the allocation/de-allocation of heap space for objects.

What is a tuple in Python?

A tuple is a collection type data structure in Python which is immutable.

They are similar to sequences, just like the lists. However, There are some differences between a tuple and list; the former doesn’t allow modifications whereas the list does.

Also, the tuples use parentheses for enclosing, but the lists have square brackets in their syntax.

What is a dictionary in Python programming?

A dictionary is a data structure known as an associative array in Python which stores a collection of objects.

The collection is a set of keys having a single associated value. We can call it a hash, a map, or a hashmap as it gets called in other programming languages.

What is the set object in Python?

Sets are unordered collection objects in Python. They store unique and immutable objects. Python has its implementation derived from mathematics.

What is the use of the dictionary in Python?

A dictionary has a group of objects (the keys) map to another group of objects (the values). A Python dictionary represents a mapping of unique Keys to Values.

They are mutable and hence will not change. The values associated with the keys can be of any Python types.

Is Python list a linked list?

A Python list is a variable-length array which is different from C-style linked lists.

Internally, it has a contiguous array for referencing to other objects and stores a pointer to the array variable and its length in the list head structure.

Here are some Python interview questions on classes and objects.

What is Class in Python?

Python supports object-oriented programming and provides almost all OOP features to use in programs.

A Python class is a blueprint for creating the objects. It defines member variables and gets their behavior associated with them.

We can make it by using the keyword “class.” An object gets created from the constructor. This object represents the instance of the class.

In Python, we generate classes and instances in the following way.

>>>class Human. # Create the class

… pass

>>>man = Human() # Create the instance

>>>print(man)

<__main__.Human object at xE>

What are Attributes and Methods in a Python class?

A class is useless if it has not defined any functionality. We can do so by adding attributes. They work as containers for data and functions. We can add an attribute directly specifying inside the class body.

>>> class Human.

… profession = “programmer” # specify the attribute ‘profession’ of the class

>>> man = Human()

>>> print(man.profession)

programmer

After we added the attributes, we can go on to define the functions. Generally, we call them methods. In the method signature, we always have to provide the first argument with a self-keyword.

>>> class Human.

profession = “programmer”

def set_profession(self, new_profession).

self.profession = new_profession

>>> man = Human()

>>> man.set_profession(“Manager”)

>>> print(man.profession)

Manager

How to assign values for the Class attributes at runtime?

We can specify the values for the attributes at runtime. We need to add an init method and pass input to object constructor. See the following example demonstrating this.

>>> class Human.

def __init__(self, profession).

self.profession = profession

def set_profession(self, new_profession).

self.profession = new_profession

 

>>> man = Human(“Manager”)

>>> print(man.profession)

Manager

What is Inheritance in Python programming?

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

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

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

class PC. # Base class

processor = “Xeon” # Common attribute

def set_processor(self, new_processor).

processor = new_processor

 

class Desktop(PC). # Derived class

os = “Mac OS High Sierra” # Personalized attribute

ram = ” GB”

 

class Laptop(PC). # Derived class

os = “Windows Pro ” # Personalized attribute

ram = ” GB”

 

desk = Desktop()

print(desk.processor, desk.os, desk.ram)

 

lap = Laptop()

print(lap.processor, lap.os, lap.ram)

The output.

Xeon Mac OS High Sierra GB

Xeon Windows Pro GB

What is Composition in Python?

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

See the below diagram.

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

class PC. # Base class

processor = “Xeon” # Common attribute

def __init__(self, processor, ram).

self.processor = processor

self.ram = ram

 

def set_processor(self, new_processor).

processor = new_processor

 

def get_PC(self).

return “%s cpu & %s ram” % (self.processor, self.ram)

 

class Tablet().

make = “Intel”

def __init__(self, processor, ram, make).

self.PC = PC(processor, ram) # Composition

self.make = make

 

def get_Tablet(self).

return “Tablet with %s CPU & %s ram by %s” % (self.PC.processor, self.PC.ram, self.make)

 

if __name__ == “__main__”.

tab = Tablet(“i”, ” GB”, “Intel”)

print(tab.get_Tablet())

The output is.

Tablet with i CPU & GB ram by Intel

What are Errors and Exceptions in Python programs?

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

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

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

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

try.

print(“Executing code in the try block”)

print(exception)

except.

print(“Entering in the except block”)

finally.

print(“Reached to the final block”)

The output is.

Executing code in the try block

Entering in the except block

Reached to the final block

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

We can raise an exception based on some condition.

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

# Example – Raise an exception

while True.

try.

value = int(input(“Enter an odd number- “))

if value% == .

raise ValueError(“Exited due to invalid input!!!”)

else.

print(“Value entered is . %s” % value)

except ValueError as ex.

print(ex)

break

The output is.

Enter an odd number-

Exited due to invalid input!!!

Enter an odd number-

Value entered is .

Enter an odd number-

What are Python Iterators?

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

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

What is the difference between an Iterator and Iterable?

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

Here are some advanced-level Python interview questions.

What are Python Generators?

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

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

# Simple Python function

def fn().

return “Simple Python function.”

 

# Python Generator function

def generate().

yield “Python Generator function.”

 

print(next(generate()))

The output is.

Python Generator function.

What are Closures in Python?

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

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

def multiply_number(num).

def product(number).

‘product() here is a closure’

return num * number

return product

 

num_ = multiply_number()

print(num_())

print(num_())

 

num_ = multiply_number()

print(num_())

The output is.

What are Decorators in Python?

Python decorator gives us the ability to add new behavior to the given objects dynamically. In the example below, we’ve written a simple example to display a message pre and post the execution of a function.

def decorator_sample(func).

def decorator_hook(*args, **kwargs).

print(“Before the function call”)

result = func(*args, **kwargs)

print(“After the function call”)

return result

return decorator_hook

 

@decorator_sample

def product(x, y).

“Function to multiply two numbers.”

return x * y

 

print(product(, ))

The output is.

Before the function call

After the function call

How do you create a dictionary in Python?

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

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

>>> site_stats = {‘site’. ‘tecbeamers.com’, ‘traffic’. , “type”. “organic”}

>>> type(site_stats)

<class ‘dict’>

>>> print(site_stats)

{‘type’. ‘organic’, ‘site’. ‘tecbeamers.com’, ‘traffic’. }

How do you read from a dictionary in Python?

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

>>> site_stats = {‘site’. ‘tecbeamers.com’, ‘traffic’. , “type”. “organic”}

>>> print(site_stats[“traffic”])

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

>>> site_stats = {‘site’. ‘tecbeamers.com’, ‘traffic’. , “type”. “organic”}

>>> print(site_stats.get(‘site’))

tecbeamers.com

How do you traverse through a dictionary object in Python?

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

>>> site_stats = {‘site’. ‘tecbeamers.com’, ‘traffic’. , “type”. “organic”}

>>> for k, v in site_stats.items().

print(“The key is. %s” % k)

print(“The value is. %s” % v)

print(“++++++++++++++++++++++++”)

The output is.

The key is. type

The value is. organic

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

The key is. site

The value is. tecbeamers.com

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

The key is. traffic

The value is.

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

How do you add elements to a dictionary in Python?

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

>>> # Setup a blank dictionary

>>> site_stats = {}

>>> site_stats[‘site’] = ‘google.com’

>>> site_stats[‘traffic’] =

>>> site_stats[‘type’] = ‘Referral’

>>> print(site_stats)

{‘type’. ‘Referral’, ‘site’. ‘google.com’, ‘traffic’. }

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

>>> site_stats[‘site’] = ‘google.co.in’

>>> print(site_stats)

{‘site’. ‘google.co.in’}

>>> site_stats_new = {‘traffic’. , “type”. “social media”}

>>> site_stats.update(site_stats_new)

>>> print(site_stats)

{‘type’. ‘social media’, ‘site’. ‘google.co.in’, ‘traffic’. }

 

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

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

>>> site_stats = {‘site’. ‘tecbeamers.com’, ‘traffic’. , “type”. “organic”}

>>> ‘site’ in site_stats

True

>>> ‘traffic’ in site_stats

True

>>> “type” in site_stats

True

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

What is the syntax for List comprehension in Python?

The signature for the list comprehension is as follows.

[ expression(var) for var in iterable ]

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

>>> alist = [var for var in range(, )]

>>> print(alist)

What is the syntax for Dictionary comprehension in Python?

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

{ aKey, itsValue for aKey in iterable }

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

>>> adict = {var.var** for var in range(, )}

>>> print(adict)

What is the syntax for Generator expression in Python?

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

( expression(var) for var in iterable )

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

>>> (var for var in range(, ))

at x>

>>> list((var for var in range(, )))

Now, see more Python interview questions for practice.

How do you write a conditional expression in Python?

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

>>> no_of_days =

>>> is_leap_year = “Yes” if no_of_days == else “No”

>>> print(is_leap_year)

Yes

What do you know about the Python enumerate?

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

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

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

enumerate(iterable, to_begin=)

Arguments.

iterable. array type object which enables iteration

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

# Example – enumerate function

alist = [“apple”,”mango”, “orange”]

astr = “banana”

# Let’s set the enumerate objects

list_obj = enumerate(alist)

str_obj = enumerate(astr)

print(“list_obj type.”, type(list_obj))

print(“str_obj type.”, type(str_obj))

 

print(list(enumerate(alist)) )

# Move the starting index to two from zero

print(list(enumerate(astr, )))

The output is.

list_obj type. <class ‘enumerate’>

str_obj type. <class ‘enumerate’>

[(, ‘apple’), (, ‘mango’), (, ‘orange’)]

[(, ‘b’), (, ‘a’), (, ‘n’), (, ‘a’), (, ‘n’), (, ‘a’)]

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

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

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

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

Signature. globals()

 

Arguments. None

# Example. globals() function

x =

def fn().

y =

z = y + x

# Calling the globals() method

z = globals()[‘x’] = z

return z

# Test Code

ret = fn()

print(ret)

The output is.

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

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

Signature.

zip(*iterators)

Arguments.

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

Returns.

A single iterator object with combined mapped values

# Example. zip() function

emp = [ “tom”, “john”, “jerry”, “jake” ]

age = [ , , , ]

dept = [ ‘HR’, ‘Accounts’, ‘R&D’, ‘IT’ ]

# call zip() to map values

out = zip(emp, age, dept)

# convert all values for printing them as set

out = set(out)

# Displaying the final values

print (“The output of zip() is . “,end=””)

print (out)

The output is.

The output of zip() is . {(‘jerry’, , ‘R&D’), (‘jake’, , ‘IT’), (‘john’, , ‘Accounts’), (‘tom’, , ‘HR’)}

What are Class or Static Variables in Python programming?

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

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

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

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

# Example

class Test.

aclass = ‘programming’ # A class variable

def __init__(self, ainst).

self.ainst = ainst # An instance variable

# Objects of CSStudent class

test = Test()

test = Test()

print(test.aclass)

print(test.aclass)

print(test.ainst)

print(test.ainst)

 

# A class variable is also accessible using the class name

print(Test.aclass)

The output is.

programming

programming

 

 

programming

How does the ternary operator work in Python?

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

The syntax would look like the one given below.

[onTrue] if [Condition] else [onFalse]

x, y = ,

smaller = x if x < y else y

print(smaller)

What does the “self” keyword do?

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

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

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

There are two ways to copy objects in Python.

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

What is the purpose of docstrings in Python?

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

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

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

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

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

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

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

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

What is the command to debug a Python program?

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

$ python -m pdb python-script.py

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

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

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

import sys

 

def trace_calls(frame, event, arg).

# The ‘call’ event occurs before a function gets executed.

if event != ‘call’.

return

# Next, inspect the frame data and print information.

print ‘Function name=%s, line num=%s’ % (frame.f_code.co_name, frame.f_lineno)

return

 

def demo().

print ‘in demo()’

 

def demo().

print ‘in demo()’

demo()

 

sys.settrace(trace_calls)

demo()

Why and when do you use generators in Python?

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

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

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

What does the yield keyword do in Python?

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

See the example below.

def testgen(index).

weekdays = [‘sun’,’mon’,’tue’,’wed’,’thu’,’fri’,’sat’]

yield weekdays[index]

yield weekdays[index+]

 

day = testgen()

print next(day), next(day)

 

#output. sun mon

How to convert a list into other data types?

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

Turn a list into a string.

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

weekdays = [‘sun’,’mon’,’tue’,’wed’,’thu’,’fri’,’sat’]

listAsString = ‘ ‘.join(weekdays)

print(listAsString)

 

#output. sun mon tue wed thu fri sat

Turn a list into a tuple.

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

This function takes the list as its argument.

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

weekdays = [‘sun’,’mon’,’tue’,’wed’,’thu’,’fri’,’sat’]

listAsTuple = tuple(weekdays)

print(listAsTuple)

 

#output. (‘sun’, ‘mon’, ‘tue’, ‘wed’, ‘thu’, ‘fri’, ‘sat’)

Turn a list into a set.

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

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

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

weekdays = [‘sun’,’mon’,’tue’,’wed’,’thu’,’fri’,’sat’,’sun’,’tue’]

listAsSet = set(weekdays)

print(listAsSet)

 

#output. set([‘wed’, ‘sun’, ‘thu’, ‘tue’, ‘mon’, ‘fri’, ‘sat’])

Turn a list into a dictionary.

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

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

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

weekdays = [‘sun’,’mon’,’tue’,’wed’,’thu’,’fri’]

listAsDict = dict(zip(weekdays[..], weekdays[..]))

print(listAsDict)

#output. {‘sun’. ‘mon’, ‘thu’. ‘fri’, ‘tue’. ‘wed’}

So, this brings us to the end of the Python Interview Questions blog.This Tecklearn ‘Top Python Interview Questions and Answers’ helps you with commonly asked questions if you are looking out for a job in Programming Domain. If you wish to learn Python and build a career in Programming domain, then check out our interactive Python with Data Science Training, that comes with 24*7 support to guide you throughout your learning period.

https://www.tecklearn.com/course/python-with-data-science/

Python with Data Science Training

About the Course

Python with Data Science training lets you master the concepts of the widely used and powerful programming language, Python. This Python Course will also help you master important Python programming concepts such as data operations, file operations, object-oriented programming and various Python libraries such as Pandas, NumPy, Matplotlib which are essential for Data Science. You will work on real-world projects in the domain of Python and apply it for various domains of Big Data, Data Science and Machine Learning.

Why Should you take Python with Data Science Training?

  • Python is the preferred language for new technologies such as Data Science and Machine Learning.
  • Average salary of Python Certified Developer is $123,656 per annum – Indeed.com
  • Python is by far the most popular language for data science. Python held 65.6% of the data science market.

What you will Learn in this Course?

Introduction to Python

  • Define Python
  • Understand the need for Programming
  • Know why to choose Python over other languages
  • Setup Python environment
  • Understand Various Python concepts – Variables, Data Types Operators, Conditional Statements and Loops
  • Illustrate String formatting
  • Understand Command Line Parameters and Flow control

Python Environment Setup and Essentials

  • Python installation
  • Windows, Mac & Linux distribution for Anaconda Python
  • Deploying Python IDE
  • Basic Python commands, data types, variables, keywords and more

Python language Basic Constructs

  • Looping in Python
  • Data Structures: List, Tuple, Dictionary, Set
  • First Python program
  • Write a Python Function (with and without parameters)
  • Create a member function and a variable
  • Tuple
  • Dictionary
  • Set and Frozen Set
  • Lambda function

OOP (Object Oriented Programming) in Python

  • Object-Oriented Concepts

Working with Modules, Handling Exceptions and File Handling

  • Standard Libraries
  • Modules Used in Python (OS, Sys, Date and Time etc.)
  • The Import statements
  • Module search path
  • Package installation ways
  • Errors and Exception Handling
  • Handling multiple exceptions

Introduction to NumPy

  • Introduction to arrays and matrices
  • Indexing of array, datatypes, broadcasting of array math
  • Standard deviation, Conditional probability
  • Correlation and covariance
  • NumPy Exercise Solution

Introduction to Pandas

  • Pandas for data analysis and machine learning
  • Pandas for data analysis and machine learning Continued
  • Time series analysis
  • Linear regression
  • Logistic Regression
  • ROC Curve
  • Neural Network Implementation
  • K Means Clustering Method

Data Visualisation

  • Matplotlib library
  • Grids, axes, plots
  • Markers, colours, fonts and styling
  • Types of plots – bar graphs, pie charts, histograms
  • Contour plots

Data Manipulation

  • Perform function manipulations on Data objects
  • Perform Concatenation, Merging and Joining on DataFrames
  • Iterate through DataFrames
  • Explore Datasets and extract insights from it

Scikit-Learn for Natural Language Processing

  • What is natural language processing, working with NLP on text data
  • Scikit-Learn for Natural Language Processing
  • The Scikit-Learn machine learning algorithms
  • Sentimental Analysis – Twitter

Introduction to Python for Hadoop

  • Deploying Python coding for MapReduce jobs on Hadoop framework.
  • Python for Apache Spark coding
  • Deploying Spark code with Python
  • Machine learning library of Spark MLlib
  • Deploying Spark MLlib for Classification, Clustering and Regression

Got a question for us? Please mention it in the comments section and we will get back to you.

 

 

 

0 responses on "Top Python Interview Questions and Answers"

Leave a Message

Your email address will not be published. Required fields are marked *