Top 81 Python Interview Questions and Answers

Here, you will come across some of the most frequently asked questions in Python job interviews which will help you in your interview preparation.

Let's have a look at some of the most popular and significant Python questions and answers:

Interview Questions




Most Essential And Frequently Asked Interview
Questions And Answer

Python

Q.1. How to define an empty class in python

Ans.:

Python | Create an empty class

In python, it required adding a pass statement to define an empty class. The pass is a special statement in python that does nothing. It just works as a dummy statement.

View Detials

Q.2. Print prime number between 1 to 100 in python

Ans.:

Python | Print prime no between 1 to 100

This is an example of how to print all prime numbers between 1 and 100 using for loop.

A prime number is a natural number greater than 1 which has no other factors except 1 and the number itself.
The first few prime numbers are {2, 3, 5, 7, ….}

n = 100
total = 0
for i in range(2, n):
    flag = True
    for j in range(2,i):
        if i%j == 0:
            flag = False 
            break

    if(flag == True):
        total +=1
        print(i)

print(f'total no of prime between 1 to {n} is {total}')
View Detials

Q.3. Print Triangle pyramid pattern in python
    *
   ***
  *****
*********

 

Ans.:

Python | Print  Triangle pyramid pattern

This is an example of how to print the Triangle pyramid pattern. It takes an input number from the user to print the number of rows for the pattern. 

n = int(input('enter no:'))

for i in range(n):
	print(" "*(n-i-1) + '*'*(2*i+1))
View Detials

Q.4. Ternary Operator in Python

Ans.:

Python | Ternary Operator

python uses an if-else conditional statement in a single line to represent the Ternary Operator.

[true] if [expression] else [false]
View Detials

Q.5. Program to check palindrome in python

Ans.:

Python | Check whether the given value is palindrome or not

This is an example of how to check whether the given value is palindrome or not. It takes input from the user to check palindrome.

A string is said to be palindrome if the string and reverse of the string will be the same.

value1 = input('Enter value to check palindrome: ')

# reverse of value1
value2 = value1[::-1]

# check value and its reverses(value2) is same
if value1==value2:
    print(f'{value1} is palindrome')
else:
    print(f'{value1} is not palindrome')
View Detials

Q.6. Python program for bubble sort

Ans.:

Python | Bubble sort program

Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are not in the right order.

This is an example for bubble sort in python

# unordered list
l = [5,6,8,5,4,1,9,3,7]

# bubble sort approch for sorting
for i in range(len(l)-1,0,-1):
    for j in range(i):
        if l[j] > l[j+1]:
            l[j],l[j+1] = l[j+1],l[j]

print(l)
View Detials

Q.7. Program to check prime number in python

Ans.:

Python | Check whether the given number is a prime number or not

This is an example of how to check whether the given number is a prime number or not. It takes an input number from the user to check the prime number

n = int(input('enter no.:'))
flag = True

if n > 2:
    for i in range(2, n):
        if n%i == 0:
            flag = False
            break

    if flag == True:
        print(f'{n} is a prime number')
    else:
        print(f'{n} is not a prime number')
else:
    print('number must be > 2')
View Detials

Q.8. Factorial program in python

Ans.:

Python | Program to find factorial of a number

This is an example of how to find the factorial of a number in python.

The factorial of a number is a product of all the positive integers less than or equal to that number.
For example, the factorial of 5 is  5x4x3x2x1 = 120

Factorial is not defined for negative integers, and the factorial of zero is one, 0! = 1.

Check here for factorial recursive way

n = int(input('Enter no.:'))
fact = 1
for i in range(1,n+1):
    fact *= i
print(fact)
View Detials

Q.9. Fibonacci series in python

Ans.:

Python | Fibonacci series

This is an example of how to print the Fibonacci series. It takes an input number from the user to print the Fibonacci series.

The Fibonacci series is a sequence of numbers where each number in the sequence is the addition to the previous two consecutive numbers.

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ……..

The first two terms are 0 and 1. The rest of the terms are obtained by adding the previous two consecutive numbers. This means the nth term is the sum of (n-1)th and (n-2)th term.

n = int(input('enter no:'))
a,b = 0,1
if n>1:
	print(a,b,end=' ')
	for i in range(2,n):
		a,b = b,a+b
		print(b, end=' ')
View Detials

Q.10. What is the iterator in python?

Ans.:

Python | Iterator | (__iter__ and __next__)

Iterators are objects that can be iterated upon. The iterator protocol for Python declares that we must make use of two functions to build an iterator- iter() and next().

View Detials

Q.11. What is zip() function in Python?

Ans.:

Python | zip() Function

Python zip() function returns a zip object, which maps a similar index of multiple containers. It takes an iterable, converts it into an iterator, and aggregates the elements based on the iterable passed. It returns an iterator of tuples. e.g: zip(iterator1, iterator2, iterator3 ...)  

View Detials

Q.12. What is monkey patching in Python?

Ans.:

Python | Monkey Patching

In Python, the term monkey patch only refers to dynamic modifications of a class or module at run-time.
 

# m.py
class A:
    def func(self):
        print("Hi")



import m
def monkey(self):
    print "Hi, monkey"

m.A.func = monkey
a = m.A()
a.func()    #Hi, monkey

 

Q.13. How do yo handle exception in python?

Ans.:

Python | Exception Handling

Python has many built-in exceptions that are raised when your program encounters an error.

Try and Except Statement – Catching Exceptions:

Try and except statements are used to catch and handle exceptions in Python. Statements that can raise exceptions are kept inside the try clause and the statements that handle the exception are written inside except clause.

a = [1, 2, 3]
try:
    print ("Second element = %d" %(a[1]))
    # Throws error since there are only 3 elements in array
    print ("Fourth element = %d" %(a[3]))
except:
    print ("An error occurred")
View Detials

Q.14. What is pickling and unpickling?

Ans.:

Python | Pickling, and Unpickling

The pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using the dump function, this process is called pickling. While the process of retrieving original Python objects from the stored string representation is called unpickling.

Q.15. What is swapcase() function in the Python?

Ans.:

Python | swapcase() Function

It is a string's function that converts all uppercase characters into lowercase and vice versa. It automatically ignores all the non-alphabetic characters.
 

string = "IT IS IN LOWERCASE."  

print(string.swapcase())  

 

Q.16. What is the usage of enumerate() function in Python?

Ans.:

Python | enumerate() Function

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

lst = ["A","B","C"] 
 
print (list(enumerate(lst)))

#[(0, 'A'), (1, 'B'), (2, 'C')]

 

Q.17. What is lambda in Python?

Ans.:

Python | Lambda function

A lambda function is a small anonymous function. This function can have any number of parameters but, can have just one statement.
 

View Detials

Q.18. What does an x = y or z assignment do in Python?
x = a or b

 

Ans.:

If bool(a) returns False, then x is assigned the value of b.

Q.19. How to send an email in Python Language?

Ans.:

Python | Send an email

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.
 

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_sender_need_to_send" 
   
# Sending the mail    
s.sendmail("sender@email_id ", "receiver@email_id", message) 

 

Q.20. Explain context manager. Can you write your own context manager example?

Ans.:

Python | context manager

Context managers allow you to allocate and release resources precisely when you want to. The most widely used example of context managers is the with() statement. 

with open('some_file', 'w') as opened_file:
    opened_file.write('Hola!')
View Detials

Q.21. What is slicing in Python?

Ans.:

Python | Slicing 

As the name suggests, ‘slicing’ is taking parts of sequences like lists, tuples, and strings.

Syntax for slicing is [start : stop : step]

  • The start is the starting index from where to slice a list or tuple
  • The stop is the ending index.
  • The step is the number of steps to jump.
  • The default value for start is 0, stop is the number of items, and step is 1.
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

print(numbers[1 : : 2])  

#output : [2, 4, 6, 8, 10]

 

Q.22. What are lists and tuples? What is the key difference between the two?

Ans.:

Python | lists, and tuples

Lists and Tuples both are sequence data types that can store a collection of objects in Python. They are both heterogeneous data types means that you can store any kind of data type

The key difference between the tuples and lists is that the tuples are immutable objects while the lists are mutable. This means that lists can be modified, appended, or sliced on the go but tuples remain constant and cannot be modified in any manner.

View Detials

Q.23. What is docstring in Python?

Ans.:

Python | Docstring 

  • A documentation string or docstring is a multiline string used to document a specific code segment.
  • The docstring should describe what the function or method does.

 

Q.24. “in Python, Functions Are First-class Objects.” What Do You Infer from this?

Ans.:

It means that a function can be treated just like an object.

  • You can assign them to variables
  • and pass them as arguments to other functions.
  • You can even return them from another function. 
  • You can store them in data structures such as hash tables or lists

 

Q.25. What are the tools present to perform statics analysis?

Ans.:

The two static analysis tools used to find bugs in Python are Pychecker and Pylint. Pychecker detects bugs from the source code and warns about its style and complexity. While Pylint checks whether the module matches up to a coding standard.
 

Q.26. What are negative indexes and why are they used?

Ans.:

Negative indexes mean that you count from the right instead of the left. So, list[-1] refers to the last element, list[-2] is the second-last, and so on.

Q.27. What is a dynamically typed language?

Ans.:

Python is an interpreted language, that executes each statement line by line and thus type-checking is done on the fly, during execution. Hence, Python is a Dynamically Typed Language.

View Detials

Q.28. What is the use of vars(), dir() and help() functions?

Ans.:

Python | vars(), dir() and help() 

  • The vars() function returns the __dict__ attribute of an object.
  • The dir() function returns all properties and methods of the specified object, without the values.
  • The help() function is used to display the documentation string and also facilitates us to see the help related to modules, keywords, and attributes.
View Detials

Q.29. Explain how to delete a file in Python?

Ans.:

Python | Delete a file

Using command  os.remove(file_name)

View Detials

Q.30. Differentiate between new and override modifiers.

Ans.:

Python | New and Override Modifiers

The new modifier is used to instruct the compiler to use the new implementation and not the base class function. The Override modifier is useful for overriding a base class function inside the child class.

Q.31. What is the MRO in Python?

Ans.:

MRO stands for Method Resolution Order. Talking of multiple inheritances, whenever we search for an attribute in a class, Python first searches in the current class. If found, its search is satiated. If not, it moves to the parent class. It follows an approach that is left-to-right and depth-first.

View Detials

Q.32. What is PEP 8?

Ans.:

PEP stands for Python Enhancement Proposal. A PEP is an official design document that describes new features proposed for Python and documents aspects of Python, like design and style, for the community. PEP 8 exists to improve the readability of Python code.

Q.33. Explain the difference between @staticmethod and @classmethod?

Ans.:

Python | Difference between @staticmethod and @classmethod

staticmethod is a method that knows nothing about the class or the instance it was called on. It just gets the arguments that were passed, no implicit first argument. Its definition is immutable via inheritance.

class A:

    @staticmethod
    def func(arg1, arg2, ...): 
        ... 

classmethod, on the other hand, is a method that gets passed the class it was called on, or the class of the instance it was called on, as the first argument. Its definition follows Subclass, not Parent class, via inheritance.

class A:

    @classmethod
    def func(cls, arg1, arg2, ...): 
        ... 

 

 

Q.34. What is a map function in Python?

Ans.:

Python | map() Function

The map() function executes a specified function for each item in an iterable. The map() function in Python has two parameters, function and iterable. The map() function takes a function as an argument and then applies that function to all the elements of an iterable, passed to it as another argument. It returns an object list of results.

View Detials

Q.35. Does Python support interfaces like Java does?

Ans.:

No. However, Abstract Base Classes (ABCs) are a feature from the abc module that let us declare what methods subclasses should implement. Python supports this module since version 2.7.

Q.36. What is PYTHONPATH in Python?

Ans.:

Python | PYTHONPATH 

PYTHONPATH is an environment variable that 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.

 

Q.37. What is a generator in Python?

Ans.:

Python | Generator

Functions that return an iterable set of items are called generators. It is a normal function except that it yields expression in the function. It does not implements __itr__ and next() method and reduces other overheads as well.

View Detials

Q.38. What are global, protected and private attributes in Python?

Ans.:

Python | Global, Protected, and Private

Global, Protected, and Private access modifiers in Python. Python does not use these keywords to control access modifications instead single and double underscore  ‘_’ symbols are used to specify Protected and  Private to determine the access control. The variables that are defined in the global scope are Global

View Detials

Q.39. What is an Interpreted language?

Ans.:

Interpreted language

An Interpreted language executes its statements line by line. Languages such as Python, Javascript, R, PHP, and Ruby is a prime examples of Interpreted languages. Programs written in an interpreted language runs directly from the source code, with no intermediary compilation step.

Q.40. How can you generate random numbers?

Ans.:

Python | Generate random numbers

Python provides a module called random using which we can generate random numbers. e.g: print(random.random())

View Detials

Q.41. How to remove whitespaces from a string in Python?

Ans.:

Python | strip() Function | Remove whitespaces from a string 

To remove the whitespaces and trailing spaces from the string, Python provides a strip([str]) built-in function. This function returns a copy of the string after removing whitespaces if present. Otherwise returns the original string.
 

string = "  Python " 
 
print(string.strip())  

 

Q.42. Explain Global, Local and Nonlocal variables.

Ans.:

Python | Global, Local and Nonlocal variables

  • Global variables are public variables that are defined in the global scope.
  •  A variable declared inside the function's body or in the local scope is known as a local variable.
  • Nonlocal Variables are used in nested functions whose local scope is not defined. 
View Detials

Q.43. What is pass in Python?

Ans.:

Python | Pass Statement

The pass statement is used as a placeholder for future code. It 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.

 

def myfunction():
    pass

 

Q.44. What is break, continue and pass in Python?

Ans.:

Python | Break, Continue, and Pass

  • Break: The break statement terminates the loop immediately and the control flows to the statement after the body of the loop.
  • Continue: The continue statement skips the current iteration of the statement, and the control flows to the next iteration of the loop.
  • Pass: The pass keyword in Python is generally used to fill up empty blocks.
View Detials

Q.45. How do you debug code in python?

Ans.:

Using PDB we debug code in python. Some pdb commands include-

  • <b> — Add breakpoint
  • <c> — Resume execution
  • <s> — Debug step by step
  • <n> — Move to next line
  • <l> — List source code
  • <p> — Print an expression

latest python 3.7   we can use breakpoint() to debug code

Q.46. How is Multithreading achieved in Python?

Ans.:

Python has a multi-threading package, but commonly not considered good practice to use it as it will result in increased code execution time.

Python has a constructor called the Global Interpreter Lock (GIL). The GIL ensures that only one of your ‘threads’ can execute at one time. The process makes sure that a thread acquires the GIL, does a little work, then passes the GIL onto the next thread. This happens at a very Quick instance of time and that’s why to the human eye it seems like your threads are executing parallelly, but in reality, they are executing one by one by just taking turns using the same CPU core.

Q.47. What is the difference between append() and extend() methods?

Ans.:

Python | append() and extend() Function

Both append() and extend() methods are methods used to add elements at the end of a list.

  • append(element): append() method adds the given element at the end of the list.
  • extend(another-list): extend() method adds the elements of another list at the end of the list.

 

Q.48. What is the Dogpile effect?

Ans.:

Python | Dogpile effect

In case the cache expires, what happens when a client hits a website with multiple requests is what we call the dogpile effect. To avoid this, we can use a semaphore lock. When the value expires, the first process acquires the lock and then starts to generate the new value.

Q.49. Can you explain the filter(), map(), and reduce() functions?

Ans.:

Python | filter(), map(), and reduce() Functions

  • filter()  function accepts two arguments, a function and an iterable, where each element of the iterable is filtered through the function to test if the item is accepted or not.
    >>> set(filter(lambda x:x>4, range(7)))
    
    # {5, 6}
    
    

     

  • map() function calls the specified function for each item of an iterable and returns a list of result

    >>> set(map(lambda x:x**3, range(7)))
    
    # {0, 1, 64, 8, 216, 27, 125}

     

  • reduce() function reduces a sequence pair-wise, repeatedly until we arrive at a single value..
     

    >>> reduce(lambda x,y:y-x, [1,2,3,4,5])
    
    # 3
    

    Let’s understand this:

    2-1=1
    3-1=2
    4-2=2
    5-2=3

    Hence, 3.

 

Q.50. What is __init__ in python?

Ans.:

Python | __init__  constructor method

__init__ is a constructor method in Python and is automatically called to allocate memory when a new object/instance is created. All classes have a __init__ method associated with them.

View Detials

Q.51. What does *args and **kwargs mean?

Ans.:

Python | *args and **kwargs 

  • *args is a special syntax used in the function definition to pass variable-length arguments. e.g: myFun(*argv)
    def func(*args):
    	for i in args:
    		print(i)
    
    func(2,3,4)
    
    
    #Output
    2
    3
    4

     

  • **kwargs is a special syntax used in the function definition to pass variable-length keyworded arguments. e.g: myFun(**kwargs)
    def func(**kwargs):
    	for i in kwargs:
    		print(i, kwargs[i])
    
    func(a=1,b=2,c=3)
    
    
    #Output:
    a 1
    b 2
    c 7

The words args and kwargs are a convention, and we can use anything in their place.

 

 

Q.52. How will you check if a class is a child of another class?

Ans.:

Python |  issubclass()

This is done by using a method called issubclass() provided by python. The method tells us if any class is a child of another class by returning true or false accordingly.

View Detials

Q.53. What is yield in Python?

Ans.:

yield is a keyword beares the ability to turn any function into a generator.  Much like the standard return keyword, but returns a generator object. It is also true that one function may observe multiple yields.

def odds(n):
    odd=[i for i in range(n+1) if i%2!=0]
    for i in odd:
        yield i


for i in odds(8):
    print(i)

The output of the above code is

1
3
5
7

 

Q.54. Explain split() and join() method in Python?

Ans.:

Python | split() and join()

You can use split() method to split a string based on a delimiter to a list of strings. and join() method is used to join a list of strings based on a delimiter to give a single string.

View Detials

Q.55. What are accessors, mutators, and @property?

Ans.:

Python | accessors, mutators, and @property

What we call getters and setters in languages like Java, we term accessors and mutators in Python. In Java, if we have a user-defined class with the property ‘x’, we have methods like getX() and setX().

In Python, we have @property, which is syntactic sugar for property(). This lets us get and set variables without compromising on the conventions.

Q.56. Are access specifiers used in python?

Ans.:

Python | Access Specifiers

Python does not make use of access specifiers specifically like private, public, protected, etc. However, it does not derive this from any variables. It has the concept of imitating the behavior of variables by making use of a single (protected) or double underscore (private) as prefixed to the variable names. By default, the variables without prefixed underscores are public.
 

Q.57. Differentiate between deep and shallow copies.

Ans.:

Python | Deep and Shallow copies

  • Shallow copy does the task of creating new objects and storing references to original elements. This does not undergo recursion to create copies of nested objects. It just copies the reference details of nested objects.
  • Deep copy creates an independent and new copy of an object and even copies all the nested objects of the original element recursively.
     

Q.58. Whenever you exit Python, is all memory de-allocated?

Ans.:

The answer here is no. The modules with circular references to other objects, or to objects referenced from global namespaces, aren’t always freed on exiting Python.

Plus, it is impossible to de-allocate portions of memory reserved by the C library.

Q.59. What is the use of self in Python?

Ans.:

Python | Self

Self is used to represent the instance of the class. With this keyword, you can access the attributes and methods of the class in python. It binds the attributes with the given arguments.
 

View Detials

Q.60. What is main function in python? How do you invoke it?

Ans.:

Python | Main Function

In the world of programming languages, the main is considered as an entry point of execution for a program. But in python, it is known that the interpreter serially interprets the file line-by-line. This means that python does not provide main() function explicitly. But this doesn't mean that we cannot simulate the execution of main. This can be done by defining the user-defined main() function and by using the __name__  property of the python file. This __name__ variable is a special built-in variable that points to the name of the current module. This can be done as shown below:

def main():
    print("This is main function!")


if __name__=="__main__":
    main()

 

Q.61. What is the difference between / and // operator in Python?

Ans.:

Python |  / and // Operator

  • /: is a division operator and returns the Quotient value. e.g: 10/3  will return 3.33
  • // : is known as floor division operator and used to return only the value of quotient before a decimal. e.g: 10//3 will return 3

 

Q.62. List primitive and non primitive data types?

Ans.:
  • Primitive data types are Integers, Float, Strings, and Boolean.
  • Non-primitive data types are Array, List, Tuples, Dictionary, Sets, and Files.

 

 

Q.63. How is memory managed in Python?

Ans.:

Python | Memory manage

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.

Q.64. Why is finalize used?

Ans.:

Finalize method is used for freeing up the unmanaged resources and cleaning up before the garbage collection method is invoked. This helps in performing memory management tasks.

Q.65. Difference between module and package?. addon how do you create package in python?

Ans.:

Python | Module and Package

  • Module: The module is a simple Python file that contains collections of functions and global variables and with having a .py extension file. It is an executable file and to organize all the modules we have the concept called Package in Python.
  • Package: The package is a simple directory having collections of modules. This directory contains Python modules and also has a __init__.py file by which the interpreter interprets it as a Package. The package is simply a namespace. The package also contains sub-packages inside it.
     

To create a Python package of our own, we create a directory and create a file __init__.py in it. We leave it empty. Then, in that package, we create a module(s) with whatever code we want. 

Q.66. Program to count the number of capital letters in a file?

Ans.:

Python program to count the number of capital letters in a file.

with open(FILE_NAME) as my_file:
    count = 0
    text = my_file.read()
    for character in text:
        if character.isupper():
        count += 1
    print(count)

    

 

 

Q.67. Is it possible to call parent class without its instance creation in Python?

Ans.:

Yes, it is possible if the base class is instantiated by other child classes or if the base class is a static method.

Q.68. What are decorators?

Ans.:

Python | What are decorators

A decorator in Python is a function that modifies the behavior of an existing function or class without any modification to the original source code. 

A decorator takes another function as its argument and returns yet another function. They are represented @decorator_name in Python and are called in a bottom-up fashion.

# decorator function to convert to uppercase
def decor(func):
    def wrapper(s):
        s = s.upper()
        return(func(s))
    return inner

@decor
def check(s):
    print(s)


check('Hello Python')    # HELLO PYTHON

 

 

Q.69. List some of the most commonly used built-in modules in Python?

Ans.:

Python modules are the files having python code which can be functions, variables, or classes. These go by .py extension. The most commonly available built-in modules are:

  • os
  • math
  • sys
  • random
  • re
  • datetime
  • JSON

Q.70. Difference between new_style and old_style class?

Ans.:

Python | new_style and old_style

Old-style: With old-style classes, class and type are not quite the same things.  If obj is an instance of an old-style class, obj __class__ designates the class, but the type(obj) is always an instance.

>>> class Foo:
...     pass
>>> x = Foo()
>>> x.__class__
<class __main__.Foo at 0x000000000535CC48>
>>> type(x)
<type 'instance'>


New-Style: New-style classes unify the concepts of class and type. If obj is an instance of a new-style class, type(obj) is the same as obj. __class__:
 

>>> class Foo:
...     pass

>>> obj = Foo()
>>> obj.__class__
<class '__main__.Foo'>
>>> type(obj)
<class '__main__.Foo'>
>>> obj.__class__ is type(obj)
True

 


For more details click here

 

Q.71. What are unit tests in Python?

Ans.:

Python | What are unit tests

  • Unit test is a testing technique to check a single component of code and ensures that it performs as expected.
  • Unit tests are an important part of regression testing to ensure that the code still functions as expected after making changes to the code and helps ensure code stability. 
  • PyUnit and PyTest are some testing libraries in python

 

Q.72. List the common security issues that can be avoided by using Django?

Ans.:

A few common security issues that can be avoided by using Django are:

  • Clickjacking
  • Cross-site scripting and
  • SQL injection

Q.73. Write a code to match a string that has the letter ‘a’ followed by 4 to 6 'b’s.

Ans.:

We can use the python re module to match the string

import re

def check(txt):
    # regex pattern
    pattern = 'ab{4,8}'

    if re.search(pattern,  txt):
        print('Match found')
    else:
        print('Match not found')

check("abcbbbb")
# Match not found
       
check("aabbbbbc")
# Match found

check("abcbbabbbbbca")
# Match found

Q.74. Explain Inheritance in Python.

Ans.:

Python | Inheritance 

Inheritance is a process by which a class can inherit the methods and properties of another class. The concept of inheritance provides the idea of reusability.

The class from which we are inheriting is called a base class or superclass and the class that is inherited is called a derived class or subclass.

They are different types of inheritance supported by Python:

  1. Single Inheritance – A derived class acquires the members of a single superclass.
  2. Multi-level inheritance – A derived class is derived from another derived class. A derived class D1 is inherited by another derived class D2 and D2 is derived from a base class B1.
  3. Hierarchical inheritance – From one superclass you can inherit any number of subclasses
  4. Multiple inheritance – A derived class is inherited from more than one base class.

 

 

Q.75. What is the difference between .py and .pyc files?

Ans.:

The .py files are the python source code of a program. While the .pyc files contain the bytecode of the python files. We get bytecode after compilation of .py file (source code).

The .pyc files are not created for all the files that you run. it is created when the code is imported from some other source. The interpreter converts the source .py files to .pyc files if .pyc files are not already present. 

Having .pyc file saves the compilation time.

Q.76. What does [::-1] do?

Ans.:

[::-1] is used to inverse the order of a sequence.

>>> my_list = [1,2,3,5,6,7,8,9]

>>> my_list[::-1]
[9, 8, 7, 6, 5, 3, 2, 1]

 

 

Q.77. Write a code to add the values of same keys in two different dictionaries and return a new dictionary.

Ans.:

We can use the Counter method from the collections module

from collections import Counter

dict1 = {'a': 5, 'b': 3, 'c': 2}
dict2 = {'a': 2, 'b': 4, 'c': 3}

new_dict = Counter(dict1) + Counter(dict2)


print(new_dict)
# Print: Counter({'a': 7, 'b': 7, 'c': 5})


 

Q.78. Program to check all numbers are unique in a sequence.

Ans.:

You can do this by converting the list to a set using the set() method and comparing the length of this set with the length of the original list. If found equal, return True else False

# function to check unique numbers in the sequence
def check(lst):
 if len(lst) == len(set(lst)):
   return True
 else:
   return False;


print(lst([1,2,3,5]))     
# True

print(lst([1,2,2,3,3,3,5,5,7,8])) 
# False

 

 

Q.79. What is a namedtuple?

Ans.:

Python | namedtuple

A namedtuple will let us access a tuple’s elements using a name/label. We use the function namedtuple() for this, and import it from collections.

>>> from collections import namedtuple

#format
>>> result=namedtuple('result','Physics Chemistry Maths') 

#declaring the tuple
>>> Chris=result(Physics=86,Chemistry=92,Maths=80) 

>>> Chris.Chemistry
# 92

 

Q.80. What is the difference between Python array and Python list?

Ans.:

Difference between Python array and Python list

Array Lists
it is used to store only homogeneous data. The list is used to store heterogeneous data
it occupies less amount of memory as the array stores only similar types of data. List stores different types of data so it requires a large  amount of memory compared to the array
The length of an array is fixed as need to declare the length at the time of declaration. The length of the list is not fixed

 

 

Q.81. What is the purpose of ‘is’, ‘not’ and ‘in’ operators?

Ans.:

Python | ‘is’, ‘not’, and ‘in’ operators

is: Returns True if both variables are the same object

>>> x = 5
>>> y = 5
>>> z = 1

>>> x is y
True


>>> x is z
False

not: returns the inverse of the boolean value

>>> x = True
>>> not x
False


>>> y = False
>>> not y
True

in: Returns True if the specified value is present in a sequence. 

>>> x = [5,10,2,9,7]

>>> 7 in x
True

>>> 3 in x
False