Python Interview Questions (Part 2)

Why was the language called as Python?

Python actually got its name from a BBC comedy series from the seventies Monty Python's Flying Circus . The designer needed a name that was short, unique, and slightly mysterious. Since he was a fan of the show he thought this name was great, so he decided to call the language Python.

Name few Python Web Frameworks for developing web applications?

There are various web frameworks provided by Python. Some popular frameworks are :

  1. Django
  2. TurboGears
  3. Web2py
  4. Flask
  5. Pyramid
  6. Cubic Web

What is PEP 8?

Pep8 is a coding standard and Style Guide for readability and long-term maintainability. It was designed to help python developers write more readable code. It's not a requirement for your code to work, just a good coding practice you should follow.

What IDE to use for Python?

There are various IDE for Python development. Some popular IDEs are :

  1. Pycharm IDE
  2. Pydev IDE
  3. Wing IDE
  4. Eric Python IDE
  5. Vim IDE
  6. IPython Notebook
Also, Visual Studio has an extension for Python:

What are all the operating system that Python can run on?

Python is a platform independent language, it works for all Operating Systems like, Windows, Unix, Linus, MacOS etc.

Is python a case sensitive language?

Yes, Python a case sensitive language

Case sensitive means that x is different from X. The variable of John is different from the variable of john.

What is the purpose of PYTHONPATH environment variable?

Setting the PYTHONPATH environment variable is an easy way to make Python modules available for import from any directory. When you import modules in python, python searches for the module in the directories in PYTHONPATH, in addition to some other directories.

Docstrings vs Comments

Documentation is important to understand what the code does. Docstrings are for people who are going to be using your code without needing or wanting to know how it works. Docstrings can be turned into actual documentation. While, comments are meant to give specific information on blocks or lines, #TODO is used to remind you what you want to do in future, definition of variables and so on.

What's wrong with import all?

Importing * from a module, you will import all the functions and classes in your own namespace, which may clash with the functions you define yourself. Also you don't know exactly what is imported and can't find place from what module certain thing was imported easily (readability).

How is print statement represented in Python 3 (v/s Python2)?

In Python 2.x print is actually a special statement, while in Python 3.x the print statement has been replaced with a print() function. It means that we have to wrap the object that we want to print in parentheses. Python 2 doesn't have a problem with additional parentheses, but in contrast, Python 3 would raise a Syntax Error if we called the print function without the parentheses.

How can I read inputs as integers/float?

The input()method in Python return strings. Convert the result to integer explicitly with int()/float().

x = int(input("Enter a number: ")) y = float(input("Enter a number: "))

What are the supported data types in Python?

Python's data types are built in the core of the language. Sticking to the hierarchy scheme used in the official Python documentation these are numeric types, sequences, sets and mappings.

Numeric types: int, long, float, complex.

Sequences: String, bytes, byte array, list, tuple.

Sets: set, frozen set.

Mappings: dict.

What are Python decorators?

A decorator is a function that takes another function and extends the behaviour of the latter function without explicitly modifying it. This supports more readable applications of the DecoratorPattern but also other uses as well.

Is there a statement in Python?

No. There is no switch or case in Python.

How can we get home directory using '~' in Python?

On Unix and Windows, return the argument with an initial component of ~ or ~user replaced by that user's home directory.

import os home = str(os.path.expanduser('~')) print(home)


import os home = str(os.path.expanduser('~user')) print(home)

What is the purpose of the "//" operator in python?

"//" is for flooring division


How do I test one variable against multiple values?

The "in" operator you can use in this case.

x=2 if x in (1,2,3,4,5): print("found") else: print("Not found")

Above statement validate... x=1 or x=2 or x=3 or x=4 or x=5.

How to call an external command in Python

The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. The method run the command described by args. Wait for command to complete, then return the returncode attribute. Windows example
from subprocess import call call(["dir"])
Unix example
from subprocess import call call(["ls", "-l"])

Meaning of a single and double underscore before an object name?

  1. _abc: weak "internal use" indicator. E.g. from X import * does not import objects whose name starts with single underscore.
  2. __abc: the interpreter replaces this name with _classname__abc as a way to ensure that the name will not overlap with a similar name in another class.

Python read a single character from the user?

while True: userInput = input('>>') if len(userInput) == 1: break print ("You should enter only one character")

Use of double quotes and single quote in Python

Python does not have that restriction of single quotes for chars and double quotes for strings.

Both are equal and what you use is entirely your preference.

print('Single Quotes') print("Double Quotes")

What's the difference between raw_input() and input() in python?

  1. In Python 2, raw_input() takes exactly what the user typed and passes it back as a string.
  2. In Python 3, raw_input() was renamed to input() so now input() returns the exact string and Old input() was removed.

What is the difference between Xrange and range?

In python 2.x range() returns a list and xrange() returns an xrange object, which is kind of like an iterator and generates the numbers on demand. In Python 3, there is no xrange() , but the range() function behaves like xrange in Python 2. If you want to write code that will run on both Python 2 and Python 3, you should use range().
for x in range(5): print(x)
0 1 2 3 4

How to exit python script in command prompt?

To leave the interactive shell and go back to the console (the system shell), press Ctrl-Z and then Enter on Windows, or Ctrl-D on OS X or Linux. Alternatively, you could also run the python command exit()!

What is negative index in Python?

In python we can Both positive and negative index . Negative index is used in python to index starting from the last element of the list, tuple or any other container class which supports indexing.

-1 refers to the last index, -2 refers to the second last index and so on.

lst = [1,2,3,4,5] print(lst[-1]) print(lst[-2]) print(lst[-5])
5 4 1

Is Python object oriented?

Yes. Python is an object-oriented language , in which the program is built around objects which combine data and functionality. Python classes provide all the standard features of Object Oriented Programming. It is a mixture of the class mechanisms found in C++ and Modula-3.

Why is Python not fully object-oriented?

Python is an object-oriented language but not pure. Python doesn't support strong encapsulation , which is only one of many features associated with the term "object-oriented".

What is a Class? How do you create it in Python?

Python Object is simply a collection of data (variables) and methods (functions) that act on those data. And, class is a blueprint for the object.

Here is a simple class definition.

class MyClass: MyVar = 0

How to convert strings into integers in Python?

Python int() method is the standard built-in function to convert a string into an integer value. You call it with a string containing a number as the argument, and it returns the number converted to an actual integer.
print (int("100") + 1) Return 101

What is the output of print str * 2 if str = 'Hello World!'?

It will print 'Hello World!' two times.

str = "Hello World!" print(str*2) Return "Hello World!Hello World!"

How to capitalize the first letter of each word in a string (Python)?

The .title() method of a string (either ASCII or Unicode is fine) will capitalize the first letter of each word in a string.

str = "python hello world" print(str.title()) Return "Python Hello World"

How to check the string consists of alphanumeric characters ?

The method isalnum() checks whether the string consists of alphanumeric characters.
print ('123abc'.isalnum()) Return True print ('123#$%abc'.isalnum()) Return False

How will you check in a string that all characters are digits?

Python str.isdigit() method return true if all characters in the string are digits and there is at least one character, false otherwise.
print ("12345".isdigit()) return True print ("12345abc".isdigit()) return False

How will you remove all leading and trailing whitespace in string?

You can use the strip() to trim whitespace in Python.
str = " hello World! " print(str.strip()) Return "hello World!"