Python Interview Question set 1/Python Interview Questions and Answers for Freshers & Experienced

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

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

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

What do you understand by Tkinter?

Tkinter is a built-in Python module that is used to create GUI applications. It is Python’s standard toolkit for GUI development. Tkinter comes with Python, so there is no separate installation needed. You can start using it by importing it in your script.

Do we need to declare variables with data types in Python?

No. Python is a dynamically typed language, I.E., Python Interpreter automatically identifies the data type of a variable based on the type of value assigned to the variable.

What type of language is python? Programming or scripting?

Generally, Python is an all purpose Programming Language ,in addition to that Python is also Capable to perform scripting.

Is indentation required in Python?

Indentation in Python is compulsory and is part of its syntax.

All programming languages have some way of defining the scope and extent of the block of codes. In Python, it is indentation. Indentation provides better readability to the code, which is probably why Python has made it compulsory.

What are Python packages?

A Python package refers to the collection of different sub-packages and modules based on the similarities of the function.

Is python case sensitive?

Yes,Python is a case sensitive language.This means that Function and function both are different in python alike SQL and Pascal.

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

Python supports the below-mentioned built-in data types:

Immutable data types:
1.Number
2.String
3.Tuple
Mutable data types:
1.List
2.Dictionary
3.set

What is, not and in operators?

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

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

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

Define Python Iterators.

Group of elements, containers or objects that can be traversed.

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.

What is the difference between Xrange and range?

Xrange returns the xrange object while range returns the list, and uses the same memory and no
matter what the range size is.

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

You can access a module written in Python from C by following method,
Module = =PyImport_ImportModule("<modulename>");

How can you generate random numbers in Python?

To generate random numbers in Python, you need to import command as

import random

random.random()

This returns a random floating point number in the range [0,1)

Mention what is Flask-WTF and what are their features?

Flask-WTF offers simple integration with WTForms. Features include for Flask WTF are
• Integration with wtforms
• Secure form with csrf token
• Global csrf protection
• Internationalization integration
• Recaptcha supporting
• File upload that works with Flask Uploads

Five benefits of using Python?

• Python comprises of a huge standard library for most Internet platforms like Email, HTML,
etc.
• Python does not require explicit memory management as the interpreter itself allocates the
memory to new variables and free them automatically
• Provide easy readability due to use of square brackets
• Easy-to-learn for beginners
• Having the built-in data types saves programming time and effort from declaring variables

Explain what is Dogpile effect? How can you prevent this effect?

Dogpile effect is referred to the event when cache expires, and websites are hit by the multiple
requests made by the client at the same time. This effect can be prevented by using semaphore
lock. In this system when value expires, first process acquires the lock and starts generating new
value.

Explain how you can access sessions in Flask?

A session basically allows you to remember information from one request to another. In a flask, it
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.

Explain what is the common way for the Flask script to work?

The common way for the flask script to work is
• Either it should be the import path for your application
• Or the path to a Python file

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

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 1 arguments, then many iterables are given.

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.

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

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

How do you delete a file in Python?

Delete a file in Python using the command os.remove (filename) or os.unlink(filename).

How to check Python Version in CMD?

To check the Python Version in CMD, press CMD + Space. This opens Spotlight. Here, type “terminal” and press enter. To execute the command, type python –version or python -V and press enter. This will return the python version in the next line below the command.

Write a sorting algorithm for a numerical dataset in Python.

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

1.list = ["1", "4", "0", "6", "9"]
2.list = [int(i) for i in list]
3.list.sort()
4.print (list)

How many ways can be applied for applying reverse string?

There are five ways to applied for applying reverse string following.

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

Why do we need a break in Python?

We need a break in Python because break helps in controlling the Python loop by breaking the current loop from execution and transfer the control to the next block.

Can we reverse a list in Python?

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

How do you get a list of all the keys in a dictionary?

we can get a list of keys is by using: dict.keys()
This method returns all the available keys in the dictionary. dict = {1:a, 2:b, 3:c} dict.keys()
o/p: [1, 2, 3]

What is a classifier?

A classifier is used to predict the class of any data point. Classifiers are special hypotheses that are used to assign class labels to any particular data points.A classifier often uses training data to understand the relation between input variables and the class. Classification is a method used in supervised learning in Machine Learning.

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 split used for?

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

Example:

1
2
a="edureka python"
print(a.split())
Output: [‘edureka’, ‘python’]

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 – 8 and PEP – 20.

What are the supported standard data types in Python?

The supported standard data types in Python include the following.

List.
Number.
String.
Tuples.
Dictionary

Why do we use Pythonstartup environment variable?

It consists of the path in which the initialization file carrying Python source code can be executed to start the interpreter.

Can we preset Pythonpath?

Yes, we can preset Pythonpath as a Python installer.

How can you pick a random item from a range?

randrange ([start,] stop [,step]) − returns a randomly selected element from range(start, stop, step).

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.
Example:

str = "Rahul"
str2 = "ab"
# Calling function
str2 = str.join(str2)
# Displaying result
print(str2)
Output:

aRahulb

What are Python packages?

Python packages are namespaces containing multiple modules.Modules that are related to each other are mainly put in the same package. When a module from an external package is required in a program, that package can be imported and its modules can be put to use

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.

example:

The following example contains some keys. Class, Roll no. & Result. Their corresponding values are Intermediate, 13B and Pass respectively.

1
dict={'Class':'Intermediate','Roll no':'13B','Result':'Pass'}
1
print dict[Class]
Intermediate
1
print dict[ Roll no ]
13B
1
print dict[Result]
Pass

How will you convert a string to all lowercase?

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

Example:

1
2
stg='SARA'
print(stg.lower())
Output: sara

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.

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 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 0, stop is number of items, step is 1.
 Slicing can be done on strings, arrays, lists, and tuples.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(numbers[1 : : 2]) #output : [2, 4, 6, 8, 10]

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 3
# IndentationError: expected an indented block

What are Literals in Python and explain about different Literals?

Literals in Python refer to the data that is given in a variable or constant. Python has various kinds of literals including:
1. String Literals: It is a sequence of characters enclosed in codes. There can be single, double and triple strings based on the number of quotes used. Character literals are single characters surrounded by single or double-quotes.
2. Numeric Literals: These are unchangeable kind and belong to three different types – integer, float and complex.
3. Boolean Literals: They can have either of the two values- True or False which represents ‘1’ and ‘0’ respectively.
4. Special Literals: Special literals are sued to classify fields that are not created. It is represented by the value ‘none’.

What is docstring in Python?

 Documentation string or docstring is a multiline string used to document a specific code segment.
 The doc string line should begin with a capital letter and end with a period.
 The first line should be a short description.
 The docstring should describe what the function or method does.

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 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:
1
2 a = lambda x,y : x+y
print(a(4, 8))
Output: 12

What is __init__?

__init__ is a contructor method in Python and is automatically called to allocate memory when a new object is created. All classes have a __init__ method associated with them. It helps in distinguishing methods and attributes of a class from local variables.
# class definition
class Student:
def __init__(self, fname, lname, age, section):
self.firstname = fname
self.lastname = lname
self.age = age
self.section = section

# creating a new object
stu1 = Student("Shiv", "Rohan", 22, "A2")

What is self in Python?

Self is a keyword in Python used to define 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.

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_1 = [1, 2, [3, 5], 4]

## shallow copy

list_2 = copy(list_1)
list_2[3] = 7
list_2[2].append(6)

list_2 # output => [1, 2, [3, 5, 6], 7]
list_1 # output => [1, 2, [3, 5, 6], 4]

## deep copy

list_3 = deepcopy(list_1)
list_3[3] = 8
list_3[2].append(7)

list_3 # output => [1, 2, [3, 5, 6, 7], 8]
list_1 # output => [1, 2, [3, 5, 6], 4]

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 ['shiv', 6, 0.19], while tuples are represented with parantheses ('rohan', 5, 0.97).
But what is the real difference between the two? The key difference between the two is that while lists are mutable, tuples on the other hand are immutable objects. This means that lists can be modified, appended or sliced on-the-go but tuples remain constant and cannot be modified in any manner. You can run the following example on Python IDLE to confirm the difference:
my_tuple = ('shiv', 6, 5, 0.97)
my_list = ['shiv', 6, 5, 0.97]

print(my_tuple[0]) # output => 'shiv'
print(my_list[0]) # output => 'shiv'

my_tuple[0] = 'rohan' # modifying tuple => throws an error
my_list[0] = 'rohan' # modifying list => list modified

print(my_tuple[0]) # output => 'shiv'
print(my_list[0]) # output => 'rohan'

What is pep 8?

Python provides a coding style known as PEP 8. PEP refers to Python Enhancement Proposals and is one of the most readable and eye-pleasing coding styles.It is a set of rules that specify how to format Python code for maximum readability.

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.

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.

What is namespace in Python?

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

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.

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. 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 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 website and application with the right tools. 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

Search
R4R Team
R4R provides Python Freshers questions and answers (Python Interview Questions and Answers) .The questions on R4R.in website is done by expert team! Mock Tests and Practice Papers for prepare yourself.. Mock Tests, Practice Papers,Python Interview Question set 1,Python Freshers & Experienced Interview Questions and Answers,Python Objetive choice questions and answers,Python Multiple choice questions and answers,Python objective, Python questions , Python answers,Python MCQs questions and answers Java, C ,C++, ASP, ASP.net C# ,Struts ,Questions & Answer, Struts2, Ajax, Hibernate, Swing ,JSP , Servlet, J2EE ,Core Java ,Stping, VC++, HTML, DHTML, JAVASCRIPT, VB ,CSS, interview ,questions, and answers, for,experienced, and fresher R4r provides Python,General knowledge(GK),Computer,PHP,SQL,Java,JSP,Android,CSS,Hibernate,Servlets,Spring etc Interview tips for Freshers and Experienced for Python fresher interview questions ,Python Experienced interview questions,Python fresher interview questions and answers ,Python Experienced interview questions and answers,tricky Python queries for interview pdf,complex Python for practice with answers,Python for practice with answers You can search job and get offer latters by studing r4r.in .learn in easy ways .