Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Python Interview Questions


A list of top frequently asked Python interview questions and answers are given below.

1) What is Python?

Python is a high level object-oriented programming language with objects, modules, threads, exceptions and automatic memory management. It is a simple yet powerful programming language. It can run equally on different platforms such as Windows, Linux, UNIX, Macintosh etc. Thus, Python is a portable language.

2) What are the advantages of Python?

Following are the main advantages of using Python.
  • Free and open source
  • Portable
  • Extensible
  • Object oriented
  • Built-in data structure

3)What is PEP 8?

PEP 8 is a coding convention which specifies a set of guidelines, about how to write your Python code more readable.

4) What do you mean by Python literals?

Python literals can be defined as data which are given in a variable or constant. There are 5 types of literals in Python:
  • String Literals
  • Numeric Literals
  • Boolean Literals
  • Special Literals
  • Literal Collections
For more information:Click here

5) Explain Python functions.

A Function is a section of program or a block of code that is written once and can be executed whenever required in the program.
There are two types of functions:
  • Built-In Functions
  • User-defined Functions
For more information: Click here

6) What is Python zip() function?

The Python zip() function is used to transform multiple lists i.e. list1, list2, list3 etc. into a single list of tuples by taking the corresponding elements of the lists that are passed as parameters.
See this example:
  1. list1 = ['A',  
  2. 'B','C'] and list2 = [10,20,30].  
  3. zip(list1, list2) # results in a list of tuples say [('A',10),('B',20),('C',30)]  

Note: If the given lists are of different lengths, zip stops generating tuples when the first list ends.


7) What is Python's parameter passing mechanism?

There are two parameter 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.
The pass by value is that whenever we pass the arguments to functions that are of type say numbers, strings, tuples. This is because of the immutable nature of them.

8) How to overload constructors or methods in Python?

Python's constructor: _init__ () is a first method of a class. Whenever we try to instantiate a object __init__() is automatically invoked by python to initialize members of an object.

9) What is Web scraping? How would you achieve web scraping in Python?

Web Scrapping is a method of extracting the large amounts of information which is available on the web sites and saving it onto the local machine or onto the database tables.
In Python, following are some modules for web scraping:
  • Urllib2
  • Scrappy
  • Pyquery
  • BeautifulSoap etc.

10) Which are the file related libraries/modules in Python?

Python provides libraries/modules with functions that facilitate you to manipulate text files and binary files on file system. By using these libraries, you can create files, update their contents, copy, and delete files.
These libraries are: os, os.path, and shutil.
os and os.path: os and os.path libraries include functions for accessing the filesystem.
shutil: shutil library is used to copy and delete the files.

11) Which are the different file processing modes supported by Python?

Python provides three modes to open files:
  • Read-only mode
  • Write-only mode
  • Read-Write mode

12) What is operator in Python?

An operator is a particular symbol which is used on some values and produces an output as result.
For example:
3 + 2 = 5
Here, "+" and "=" are operators.

13) Which are the different types of operators in Python?

Following is a list of operators in Python:
  • Arithmetic Operators.
  • Relational Operators.
  • Assignment Operators.
  • Logical Operators.
  • Membership Operators.
  • Identity Operators.
  • Bitwise Operators.
For more information: Click here

14) What is used to create Unicode string in Python?

You should use "Unicode" before the string. For example: Unicode (text).

15) Explain how Python is interpreted?

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

16) How memory is managed in Python?

Memory is managed in Python in following way:
  • Memory is managed in Python by private heap space. All Python objects and data structures are located in a private heap. The programmer does not have an access to this private heap and interpreter takes care of this Python private heap.
  • Python memory manager is responsible for allocating Python heap space for Python objects.
  • Python also have an inbuilt garbage collector, which recycle all the unused memory and frees the memory and makes it available to the heap space.

17) What is Python decorator?

A Python decorator is a specific change made within Python syntax to alter functions easily.

18) What are the rules for 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 you need to explicitly declare it as 'global'.

19) What is namespace in Python?

In Python, every name has a place where it lives and can be hooked for. This is known as namespace. It is like a box where a variable name is mapped to the object placed. Whenever the variable is searched out, this box will be searched, to get corresponding object.

20) What are iterators in Python?

In Python, iterators are used to iterate a group of elements, containers like list.

21) What is generator in Python?

In Python, generator is a way that specifies how to implement iterators. It is a normal function except that it yields expression in the function.

22) What is slicing in Python?

Slicing is a mechanism used to select a range of items from sequence type like list, tuple, string etc.

23) What is 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 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  

24) What is Pass in Python?

Pass specifies a Python statement without operations. It is a place holder in a compound statement, where there should be a blank left and nothing has to be written there.

25) Explain docstring in Python?

A Python documentation string is called docstring. It is used for documenting Python functions, modules and classes.

26) What is negative index in Python?

Python sequences are indexed 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.

27) What is pickling and unpickling in Python?

Pickling is a process in which a pickle module accepts any Python object, converts it into a string representation and dumps it into a file by using dump() function.
Unpickling is a process of retrieving original Python object from the stored string representation for use.

Pickle is a standard module which serializes and de-serializes a Python object structure.


28) Which programming language is good between Java and Python?

Java and Python both are very famous object-oriented programming languages. Let's compare both on some criteria given below:
CriteriaJavaPython
Ease of useGoodVery Good
Coding SpeedAverageExcellent
Data typesStatic typeDynamic type
Data Science and Machine learning applicationAverageVery Good

29) 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 you to see the help related to modules, keywords, attributes, etc.
Dir() function: The dir() function is used to display the defined symbols.

30) What is the difference between help() and dir() function in Python?

The help() function is used to see the help related to modules, keywords, attributes, etc. whereas dir() function is used to display the defined symbols.

31) How can you make forms in Python?

You have to import cgi module to access form fields using FieldStorage class.
Attributes of class FieldStorage for 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 can be 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.
Example
  1. import cgi  
  2. form = cgi.FieldStorage()  
  3. if not (form.has_key("name") and form.has_key("age")):  
  4. print "H1>Name & Age not EnteredH1>"  
  5. print "Fill the Name & Age accurately."  
  6. return  
  7. print "p>name:", form["name"].value  
  8. print "p>Age:", form["age"].value  

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

Python 2.x is an older version of Python. It is a legacy now. Python 3.x is newer. It is the present and future of this language.
The most visible difference between them is in print statement. In Python 2 it is print "Hello" and in Python 3, it is print ("Hello").

33) How can you organize your code to make it easier to change the base class?

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
  1. BaseAlias = real base class>  
  2. class Derived(BaseAlias):  
  3. def meth(self):  
  4. BaseAlias.meth(self)  

34) Which command is used to exit help window or help command prompt?

"quit" command is used to exit help window or help command prompt.

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

36) 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:


This post first appeared on GNIITSolution, please read the originial post: here

Share the post

Python Interview Questions

×

Subscribe to Gniitsolution

Get updates delivered right to your inbox!

Thank you for your subscription

×