Python Interview Questions | Eklavya Online

Python Interview Questions

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

PEP 8 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 2001.

It stands for Python Enhancement Proposal, and its major task is to improve the readability and consistency of Python code.

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.

>>> dict = {‘Country’: ‘India’, ‘Hero’: ‘Modi’, ‘Cartoon’: ‘Rahul’}
>>>print dict[Country]
India
>>>print dict[Hero]
Modi
>>>print dict[Cartoon]
Rahul

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

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.

string = ” javatpoint “
string2 = ” javatpoint “
string3 = ” javatpoint”
print(string)
print(string2)
print(string3)
print(“After stripping all have placed in a sequence:”)
print(string.strip())

print(string2.strip())
print(string3.strip())
javatpoint
javatpoint
javatpoint

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.

import cgi
form = cgi.FieldStorage()
if not (form.has_key(“name”) and form.has_key(“age”)):
print ”Name & Age not Entered”
print “Fill the Name & Age accurately.”
return
print ”

name:”, form[“name”].value
print ”

Age:”, form[“age”].value

Memory is managed in Python by the following way:

  • The Python memory is managed by a Python private heap space. All the objects and data structures are located in a private heap. The programmer does not have permission to access this private heap.
  • We can easily allocate heap space for Python objects by the Python memory manager. The core API gives access of some tools to the programmer for coding purpose.
  • Python also has an inbuilt garbage collector, which recycle all the unused memory and frees the memory for the heap space.

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.

Decorator example
def decoratorfun():
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.

The output will be [‘!!Welcome!! ‘, ‘!!Welcome!!’]

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.

def function_name(parameters list):
#— statements—
return a_value

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.

# For Example
class Student:
pass # Passing class
class Student:
def info():
pass # Passing function

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.

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.

str = “Rohan”
str2 = “ab”
# Calling function
str2 = str.join(str2)
# Displaying result
print(str2)
Output:

aRohanb

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

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

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

The xrange() method has removed from Python 3 version. A new keyword as is introduced in Error handling.

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

It is a general-purpose computer programming language. It is a high-level, object-oriented language which can run equally on different platforms such as Windows, Linux, UNIX, and Macintosh. 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.

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.

In the list, an element present at the 2nd index from the right is 3. So, the output will be 3.

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

zip(iterator1, iterator2, iterator3 …)
Parameters

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

Return

It returns an iterator from two or more iterators.

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

# One-line docstrings
def hello():
“””A function to greet.”””
return “hello”

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.

import random

list = [12,25,15,65,58,14,5,];
print(list)
random.shuffle(list)
print (“Reshuffled list : \n”, list)
[12, 25, 15, 65, 58, 14, 5]
Reshuffled list :
[58, 15, 5, 65, 12, 14, 25]

You have to define an alias for the base class, assign the real base class to it before your class definition, and use the alias throughout your class. You can also use this method if you want to decide dynamically (e.g., depending on availability of resources) which base class to use.

Example

BaseAlias = <real base class>
class Derived(BaseAlias):
def meth(self):
BaseAlias.meth(self)

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.

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

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

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

Python sequences are accessible using an index in positive and negative numbers. For example, 0 is the first positive index, 1 is the second positive index and so on. For negative indexes -1 is the last negative index, -2 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.

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.

import smtplib
# Calling SMTP
s = smtplib.SMTP(‘smtp.gmail.com’, 587)
# TLS for network security
s.starttls()
# User email Authentication
s.login(“sender_email_id”, “sender_email_id_password”)
# message to be sent
message = “Message_you_need_to_send”
# sending the mail
s.sendmail(“sender_email_id”, “receiver_email_id”, message)
It will send an email to the receiver after authenticating sender username and password.

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.

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.

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.

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

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

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.

class student:
def __init__(self,name):
self.name = name
def __init__(self, name, email):
self.name = name
self.email = email

# This line will generate an error
#st = student(“rahul”)

# This line will call the second constructor
st = student(“rahul”, “rahul@gmail.com”)
print(st.name)
Output:
rahul

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.

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.

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

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

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

For i,v in enumerate([‘Python’,’Java’,’C++’]):
print(i,v)
0 Python
1 Java
2 C++
# enumerate using an index sequence
for count, item in enumerate([‘Python’,’Java’,’C++’], 10):

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

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

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

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.

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.

string = “IT IS IN LOWERCASE.”
print(string.swapcase())

string = “it is in uppercase.”
print(string.swapcase())
it is in lowercase.
IT IS IN UPPERCASE.

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.

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