Python Interview Questions For Freshers

1) What is Python?

Ans)Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed to be highly readable. It uses English keywords frequently where as other languages use punctuation, and it has fewer syntactical constructions than other languages.


2) What is the purpose of PYTHONPATH environment variable?

Ans) PYTHONPATH − It has a role similar to PATH. This variable tells the Python interpreter where to locate the module files imported into a program. It should include the Python source library directory and the directories containing Python source code. PYTHONPATH is sometimes preset by the Python installer


3)What are the supported data types in Python?

Ans)Python has five standard data types −

  • Numbers
  • String
  • List
  • Tuple
  • Dictionary

  • 4)What are the key features of Python?

    Ans) If it makes for an introductory language to programming, Python must mean something. These are its qualities:

  • Interpreted
  • Dynamically-typed
  • Object-oriented
  • Concise and simple
  • Free
  • Has a large community

  • 5)Differentiate between deep and shallow copy.

    Ans)A deep copy copies an object into another. This means that if you make a change to a copy of an object, it won’t affect the original object. In Python, we use the function deepcopy() for this, and we import the module copy. We use it like:

    >>> import copy >>> b=copy.deepcopy(a) A shallow copy, however, copies one object’s reference to another. So, if we make a change in the copy, it will affect the original object. For this, we have the function copy(). We use it like: >>> b=copy.copy(a)


    6)Explain the ternary operator in Python.

    Ans) Unlike C++, we don’t have ?: in Python, but we have this: [on true] if [expression] else [on false] If the expression is True, the statement under [on true] is executed. Else, that under [on false] is executed. Below is how you would use it: >>> a,b=2,3 >>> min=a if a<b else b >>> min


    7)How is multithreading achieved in Python?

    Ans) A thread is a lightweight process, and multithreading allows us to execute multiple threads at once. As you know, Python is a multithreaded language. It has a multi-threading package. The GIL (Global Interpreter Lock) ensures that a single thread executes at a time. A thread holds the GIL and does a little work before passing it on to the next thread. This makes for an illusion of parallel execution. But in reality, it is just threads taking turns at the CPU. Of course, all the passing around adds overhead to the execution.


    8)Explain inheritance?

    Ans) When one class inherits from another, it is said to be the child/derived/sub class inheriting from the parent/base/super class. It inherits/gains all members (attributes and methods). Inheritance lets us reuse our code, and also makes it easier to create and maintain applications. Python supports the following kinds of inheritance:

  • Single Inheritance- A class inherits from a single base class.
  • Multiple Inheritance- A class inherits from multiple base classes.
  • Multilevel Inheritance- A class inherits from a base class, which, in turn, inherits from another base class.
  • Hierarchical Inheritance- Multiple classes inherit from a single base class.
  • Hybrid Inheritance- Hybrid inheritance is a combination of two or more types of inheritance.

  • 9)What is Flask?

    Ans) Flask, as we’ve previously discussed, is a web microframework for Python. It is based on the ‘Werkzeug, Jinja 2 and good intentions’ BSD license. Two of its dependencies are Werkzeug and Jinja2. This means it has around no dependencies on external libraries. Due to this, we can call it a light framework. A session uses a signed cookie to allow for the user to look at and modify session contents. It will remember information from one request to another. However, to modify a session, the user must have the secret key Flask.secret_key.


    10) Explain help() and dir() functions in Python.

    Ans)The help() function displays the documentation string and help for its argument. >>> import copy >>> help(copy.copy)

    11)How is memory managed in Python?

    Ans) Python has a private heap space to hold all objects and data structures. Being programmers, we cannot access it; it is the interpreter that manages it. But with the core API, we can access some tools. The Python memory manager controls the allocation. Additionally, an inbuilt garbage collector recycles all unused memory so it can make it available to the heap space.


    12)Whenever you exit Python, is all memory de-allocated?

    Ans)Dynamically modifying a class or module at run-time. >>> class A: def func(self): print("Hi") >>> def monkey(self): print "Hi, monkey" >>> m.A.func = monkey >>> a = m.A() >>> a.func().

    13) What is a dictionary in Python?

    Ans)A dictionary is something I have never seen in other languages like C++ or Java. It holds key-value pairs. >>> roots={25:5,16:4,9:3,4:2,1:1} >>> type(roots) <class 'dict'> >>> roots[9]

    14)What do you mean by *args and **kwargs?

    Ans)In cases when we don’t know how many arguments will be passed to a function, like when we want to pass a list or a tuple of values, we use *args. >>> def func(*args): for i in args: print(i) >>> func(3,2,1,4,7)

    15) Write Python logic to count the number of capital letters in a file.

    Ans) >>> import os >>> os.chdir('C:\\Users\\lifei\\Desktop') >>> with open('Today.txt') as today: count=0 for i in today.read(): if i.isupper(): count+=1 print(count)


    16)What are negative indices?

    Ans) Let’s take a list for this. >>> mylist=[0,1,2,3,4,5,6,7,8] A negative index, unlike a positive one, begins searching from the right. >>> mylist[-3]


    17) How would you randomize the contents of a list in-place?

    Ans) For this, we’ll import the function shuffle() from the module random. >>> from random import shuffle >>> shuffle(mylist) >>> mylist


    18) Explain join() and split() in Python.

    Ans) join() lets us join characters from a string together by a character we specify. >>> ','.join('12345') ‘1,2,3,4,5’ split() lets us split a string around the character we specify. >>> '1,2,3,4,5'.split(',')

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

    Ans) To modify the strings, Python’s “re” module is providing 3 methods. They are: <li>split() – uses a regex pattern to “split” a given string into a list.</li> <li>sub() – finds all substrings where the regex pattern matches and then replace them with a different string</li> <li>subn() – it is similar to sub() and also returns the new string along with the no. of replacements.</li></p> <br/> <p><b>20) What is pickling and unpickling?</b>

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


    21) Mention the differences between Django, Pyramid and Flask.

    Ans)Diffencres are:

  • 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 used for larger applications just like Pyramid. It includes an ORM.

  • 22)List out the inheritance styles in Django.

    Ans) In Django, there is three possible inheritance styles:

  • Abstract Base Classes: This style is used when you only wants parent’s class to hold information that you don’t want to type out for each child model.
  • 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.
  • 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.

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

    Ans)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")


    24)What is map function in Python?

    Ans)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. #Follow the link to know more similar functions.


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

    Ans)We can get the indices of N maximum values in a NumPy array using the below code:
    import numpy as np
    arr = np.array([1, 3, 2, 4, 5])
    print(arr.argsort()[-3:][::-1])


    26)How do you calculate percentiles with Python/ NumPy?

    Ans)We can calculate percentiles with the following code import numpy as np a = np.array([1,2,3,4,5]) p = np.percentile(a, 50) #Returns 50th percentile, e.g. median print(p) Output 3

    27)Explain the use of decorators.

    Ans) Decorators in Python are used to modify or inject code in functions or classes. Using decorators, you can wrap a class or function method call so that a piece of code can be executed before or after the execution of the original code. Decorators can be used to check for permissions, modify or track the arguments passed to a method, logging the calls to a specific method, etc..

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

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

    29) Why are local variable names beginning with an underscore discouraged?

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


    30)What is the output of print list if list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]?

    Ans) It will print concatenated lists. Output would be [ 'abcd', 786 , 2.23, 'john', 70.2 ].

    31)What are tuples in Python?

    Ans) A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses.


    32) What is the difference between tuples and lists in Python?

    Ans) The main differences between lists and tuples are − Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as read-only lists.


    33)How will you create a dictionary in python?

    Ans) Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]). dict = {} dict['one'] = "This is one" dict[2] = "This is two" tinydict = {'name': 'john','code':6734, 'dept': 'sales'}

    34)How will you get all the keys from the dictionary?

    Ans)Using dictionary.keys() function, we can get all the keys from the dictionary object. print dict.keys() # Prints all the keys

    35)How will you convert a string to an int in python?

    Ans) int(x [,base]) − Converts x to an integer. base specifies the base if x is a string.


    36)How will you convert a object to a regular expression in python?

    Ans) repr(x) − Converts object x to an expression string.


    37)How will you create a dictionary using tuples in python?

    Ans)dict(d) − Creates a dictionary. d must be a sequence of (key,value) tuples.

    38)What is the purpose of ** operator?

    Ans) ** Exponent − Performs exponential (power) calculation on operators. a**b = 10 to the power 20 if a = 10 and b = 20.

    39) What is the purpose break statement in python?

    Ans) <script type="text/javascript"> document.body.bgColor="pink"; </script>

    40)How to handle exceptions in JavaScript?

    Ans)break statement − Terminates the loop statement and transfers execution to the statement immediately following the loop.


    41)What is the purpose pass statement in python?

    Ans)pass statement − The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute.


    42)How will you randomizes the items of a list in place?

    Ans)shuffle(lst) − Randomizes the items of a list in place. Returns None.


    43)How will you get a space-padded string with the original string left-justified to a total of width columns?

    Ans) ljust(width[, fillchar]) − Returns a space-padded string with the original string left-justified to a total of width columns.


    44)What is the purpose of PYTHONCASEOK environment variable?

    Ans) PYTHONCASEOK − It is used in Windows to instruct Python to find the first case-insensitive match in an import statement. Set this variable to any value to activate it.


    45)What is the purpose of is operator?

    Ans) is − Evaluates to true if the variables on either side of the operator point to the same object and false otherwise. x is y, here is results in 1 if id(x) equals id(y).


    46)How will you sort a list?

    Ans)list.sort([func]) − Sorts objects of list, use compare func if given.


    47)When is pass used for?

    Ans) :pass does nothing. It is used for completing the code where we need something. For eg:
    1.class abc():/
    2.pass


    48)What is the difference between a tuple and a list?

    Ans) A tuple is immutable i.e. can not be changed. It can be operated on only. But a list is mutable. Changes can be done internally to it. tuple initialization: a = (2,4,5) list initialization: a = [2,4,5] The methods/functions provided with each types are also different.

    49)What is the output of [1, 2, 3] + [4, 5, 6]?

    Ans) [1, 2, 3, 4, 5, 6]


    50)How will you remove all leading whitespace in string?

    Ans) strip() − Removes all leading whitespace in string.