Our Blog

BY : Deepa Sreekumar 0 comment

Top Python Interview Questions and Answers

1.What is a lambda function? Give an example of when it’s useful and when it’s not.

A lambda function is a small anonymous function, which returns an object.The object returned by lambda is usually assigned to a variable or used as a part of other bigger functions.Instead of the conventional def keyword used for creating functions, a lambda function is defined by using the lambda keyword. 

The purpose of lambdas

A lambda is much more readable than a full function since it can be written in-line. Hence, it is a good practice to use lambdas when the function expression is small.

The beauty of lambda functions lies in the fact that they return function objects. This makes them helpful when used with functions like map or filter which require function objects as arguments.

Lambdas aren’t useful when the expression exceeds a single line.

2.What is PYTHONPATH?

It is an environment variable, which is used when a module is imported. Whenever a module is imported, PYTHONPATH is also looked up to check for the presence of the imported modules in various directories. The interpreter uses it to determine which module to load.

3.What is init?

__init__ is a method or constructor in Python. This method is automatically called to allocate memory when a new object/ instance of a class is created. All classes have the __init__ method.

4.What are global and local variables in Python?

Global Variables:

Variables declared outside a function or in global space are called global variables. These variables can be accessed by any function in the program.

Local Variables:

Any variable declared inside a function is known as a local variable. This variable is present in the local space and not in the global space.

5.How would you make a deep copy in Python?

A deep copy refers to cloning an object. When we use the = operator, we are not cloning the object; instead, we reference our variable to the same object (a.k.a. shallow copy).

This means that changing one variable’s value affects the other variable’s value because they are referring (or pointing) to the same object. This difference between a shallow and a deep copy is only applicable to objects that contain other objects, like lists and instances of a class.

Method

To make a deep copy (or clone) of an object, we import the built-in copy module in Python. This module has the deepcopy() method which simplifies our task.

6.Explain Python Functions?

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.

7.How Python is interpreted?

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

8.What is pass in Python?

Pass means, no-operation Python statement, or in other words it is a place holder in compound statement, where there should be a blank left and nothing has to be written there.

9.In Python what is slicing?

A mechanism to select a range of items from sequence types like list, tuple, strings etc. is known as slicing.

10.What is negative index in Python?

Python sequences can be index in positive and negative numbers. For positive index, 0 is the first index, 1 is the second index and so forth. For negative index, (-1) is the last index and (-2) is the second last index and so forth.

11.Explain how can you generate random numbers in Python?

To generate random numbers in Python, you need to import command as

import random

random.random()

12.Mention five benefits of using Python?

  • Python comprises of a huge standard library for most Internet platforms like Email, HTML, etc.
  • Python does not require explicit memory management as the interpreter itself allocates the memory to new variables and free them automatically
  • Provide easy readability due to use of square brackets
  • Easy-to-learn for beginners
  • Having the built-in data types saves programming time and effort from declaring variables

13.Why is Python called a dynamically typed language?

Typing means type-checking in programming languages. Python is a strongly typed language which means “1” + 2 will result in a type error since these languages don’t allow for “type-coercion” (implicit conversion of data types). On the other side, a weakly-typed language like JavaScript will simply output “12” as a result.

Type-checking can be done at two stages –

Static – Data Types are checked before execution.

Dynamic – Data Types are checked during execution.

Python is known as an interpreted language as it executes each statement line by line and thus type-checking is done on the fly, during execution. By this means, Python is a Dynamically Typed language.

14.How to check if all characters in a string are alphanumeric?

For this, we use the method isalnum()

15.How will you find which directory you are currently in?

With the use of a function named getcwd(). It is used by importing it from the module OS.

For example:

import os

os.getcwd()

16.How can you reverse a list in Python?

Using reverse() method

listname.reverse()

Or using a slicing method from right to left

listname[::-1]

17.What is the use of break and continue statements in Python?

Both break and continue statements are the control flow statements in Python loops. Break statement stops the current loop from executing further and transfers the control to the next block. Continue statement jumps to the next iteration of the loop without exhausting it.

18.How can you remove a duplicate element from a list?

By turning elements into a set

For example:

>>> list=[1,2,1,3,4,2] >>> set(list)

19.What are membership operators?

With the operators ‘in’ and ‘not in’, we can confirm if a value is a member in another.

>>> ‘me’ in ‘disappointment’

True

>>> ‘us’ not in ‘disappointment’

True

20.Explain recursion.

When a function makes a call to itself, it is termed recursion. But then, in order for it to avoid forming an infinite loop, we must have a base condition.

For example:

>>> def fact(n):if n==1: return 1return n*fact(n-1)>>>fact(4)

21.How can you swap two numbers?

>>>a,b=2,3>>>a,b=b,a>>>a,b

22.What makes Python an object-oriented language?

In Python, we have the following object-oriented features:

  • Encapsulation
  • Abstraction
  • Inheritance
  • Polymorphism
  • Data hiding

23.What type of objects does Python support?

Mutable objects 

These let you modify their contents. Examples of these are lists, sets, and dicts. Iterations on such objects are slower.

>>> [2,4,9]

Immutable objects

These do not let us modify their contents. Examples of these will be tuples, booleans, strings, integers, floats, and complexes. Iterations on such objects are faster

>>> tuple=(1,2,4)>>> tuple

24.What is Python’s parameter passing mechanism?

  • Pass by value
  • Pass by reference

25.What is a Lambda function?

The anonymous function is called a Lambda function in Python. Lambda function has a number of parameters but has a single statement.

For example:

a = lambda x,y : x+yprint(a(5, 6))  

26.What is the difference between list and tuple in Python?

List  Tuple
The list is mutable (can be changed) A tuple is immutable (remains constant)
These lists performance is slower Tuple performance is faster when compared to lists
Syntax: list_1 = [20, ‘Mindmajix’, 30] Syntax: tup_1 = (20, ‘Mindmajix’, 30)

 

27.What are the two major loop statements?

Ans: for and while

28. What do you understand by the term namespace in Python?

A namespace in Python can be defined as a system that is designed to provide a unique name for every object in python. Types of namespaces that are present in Python are:

  • Local namespace
  • Global namespace
  • Built-in namespace

29.What happens when a function doesn’t have a return statement? Is this valid?

Yes, this is valid. The function will then return a None object. The end of a function is defined by the block of code is executed (i.e., the indenting) not by any explicit keyword.

30.What is a boolean in Python?

Boolean is one of the built-in data types in Python, it mainly contains two values, and they are true and false. 

Python bool() is the method used to convert a value to a boolean value.

31. Explain the concept of constructor?

  • Constructors are generally used for instantiating an object.
  • The task of constructors is to initialize(assign values) to the data members of the class when an object of class is created.
  • In Python the __init__() method is called the constructor and is always called when an object is created

32. What is self in Python?

  • self represents the instance of the class.
  • By using the “self” keyword we can access the attributes and methods of the class in python.
  • It does not have to be named self , you can call it whatever you like, but it has to be the first parameter of any function in the class.

33. Explain Inheritance

Inheritance enables a class to acquire all the members of another class. These members can be attributes, methods, or both. By providing reusability, inheritance makes it easier to create as well as maintain an application.The class which acquires is known as the child class or the derived class. The one that it acquires from is known as the superclass or base class or the parent class.

34. List few string methods in Python

  • find() finds the first occurrence of the specified value.
  • isalnum() returns True if all the characters are alphanumeric, meaning alphabet letter (a-z) and numbers (0-9).
  • isalpha() returns True if all the characters are alphabet letters (a-z)
  • isdigit() returns True if all the characters are digits, otherwise False.
  • replace() method replaces a specified phrase with another specified phrase.
  • rfind() method finds the last occurrence of the specified value.
  • rindex() method finds the last occurrence of the specified value.
  • split() method splits a string into a list.
  • splitlines() method splits a string into a list. The splitting is done at line breaks.

35. What is *args and **kwargs?

*args is used when the programmer is not sure about how many arguments are going to be passed to a function, or if the programmer is expecting a list or a tuple as argument to the function.

**kwargs is used when a dictionary (keyword arguments) is expected as an argument to the function.

36. Name some standard Python errors.

TypeError: Occurs when the expected type doesn’t match with the given type of a variable.

ValueError: When an expected value is not given- if you are expecting 4 elements in a list and you gave 2.

NameError: When trying to access a variable or a function that is not defined.

IOError: When trying to access a file that does not exist. 

IndexError: Accessing an invalid index of a sequence will throw an IndexError.

KeyError: When an invalid key is used to access a value in the dictionary.

37. What is the purpose of id() function in Python?

The id() is one of the built-in functions in Python.

id(object)

It accepts one parameter and returns a unique identifier associated with the input object.

38. What is the purpose of “end” in Python?

Python’s print() function always prints a newline in the end. The print() function accepts an optional parameter known as the ‘end.’ Its value is ‘\n’ by default. We can change the end character in a print statement with the value of our choice using this parameter.

print(“Let’s learn” , end = ‘ ‘) 

print(“Python”)

Output:

Let’s learn Python

39. What is the use of globals() function in Python?

The globals() function in Python returns the current global symbol table as a dictionary object.

Python maintains a symbol table to keep all necessary information about a program. This info includes the names of variables, methods, and classes used by the program.

All the information in this table remains in the global scope of the program and Python allows us to retrieve it using the globals() method.

40. What is Regular Expression?

A Regular Expression (RE) in a programming language is a special text string used for describing a search pattern.

It is extremely useful for extracting information from text such as code, files, log, spreadsheets or even documents.

41. What does the function re.match do?

re.match() function of re in Python will search the regular expression pattern and return the first occurrence.

The Python RegEx Match method checks for a match only at the beginning of the string.

If a match is found in the first line, it returns the match object. But if a match is found in some other line, the Python RegEx Match function returns null.

42. What does the function re.search() do?

re.search() function will search the regular expression pattern and return the first occurrence.

Unlike Python re.match(), it will check all lines of the input string. The Python re.search() function returns a match object when the pattern is found and “null” if the pattern is not found

43. How to join two tables in MySQL?

We can connect two or more tables in MySQL using the JOIN clause. MySQL allows various types of JOIN clauses. These clauses connect multiple tables and return only those records that match the same value and property in all tables.

Inner Join

Left Join

Right Join

Cross Join

44. What is the main difference between ‘BETWEEN’ and ‘IN’ condition operators?

BETWEEN is used to display rows based on a range of values in a row

IN is used to check for values contained in a specific set of values.

SELECT * FROM Students where ROLL_NO BETWEEN 10 AND 50

SELECT * FROM students where ROLL_NO IN (8,15,25)

45. How does DISTINCT work in MySQL?

DISTINCT returns only distinct (i.e. different) values. The DISTINCT keyword eliminates duplicate records from the results.

DISTINCT can be used with the SELECT clause.

SELECT DISTINCT column_name FROM tablename.

46. What are python modules? Name some commonly used built-in modules in Python?

Python modules are files consisting of Python code. A Python module can define functions, classes, and variables. A Python module is a .py file containing runnable code.

47. What is slicing in Python?

Slicing is a string operation used to select a range of items from sequence type like list, tuple, and string. The slice object represents the indices specified by range(start, stop, step). The slice() method allows three parameters ie., start, stop, and step.

start – starting number for the slicing to begin.

stop – the number which indicates the end of slicing.

step – the value to increment after each index (default = 1).

48. What are generators in Python?

Generators are functions that return an iterable collection of items, one at a time, in a set manner. Generators, in general,are used to create iterators with a different approach. They employ the use of yield keyword rather than return to return a generator object.

List of Authors

M.Sc, OCAJP, STAR Python, Team Lead: Software Training Division, IPSR Solutions Limited. Has 11+ years experience in IT training and has previously worked with the Ministry of Education- Maldives, NIIT, and Aptech. Expertise in Python, Machine Learning, Java, My SQL, HTML, JavaScript, AJAX, jQuery, etc., and has an exceptional career record, conducted placement support activities and corporate training, and FDP's.

Leave a Reply

Your email address will not be published.

Tags

#ansibleautomates#AWS#blog#cicd#Container#DO180#DO280#ipsronlinetraining#kubernetes#OpenShift#OpenShiftTraining#redhatautomation#redhatcertification#redhatcertification #redhatlinux #redhatsystemadministration #ansibleautomates #containers #kubernetes #RHCSA #RHCE #DO180 #DO280 #ipsr #ipsronlinetraining #openshift#RedHatLearningSubscription#redhatlinux#RedHatOpenShift#redhatsystemadministration#RedHatTraining#RHCE#RHCSA#RHLS#RHLSPremium#tiktokanalyticsandroidansiblearticleArtificial IntelligenceASP.NETaws online trainingbacklinkboot campcareercareer advancementcareer opportunitycertificationcloudclougcontainerscybersecurityCyberSecurityCertificationdata analyticsdata analytics certificationdata analytics trainingdemandDev-OpsDevopDevOpsDigital marketingExam resultsfiles typesForrester ResearchindiaInfluencer MarketingInstagraminterview questionsinterview quetioninterview techniqueIOTipsrITit careerIT Finishing schoolsIT jobsIT proffessionalsITFSjavajob interviewjob opportunitiesjob opportunitiessjobskeywordKMEA Collegelearn python onlinelink buildingLinuxlinux online trainingLinux System Administrationmachine learningMastering DevOpsnetworkingonline python trainingopen sourcephytonplacementsPrivate Cloudpythonpython certificationpython certification coursepython trainingRankingsRed HatRed Hat Academyred hat linuxRed Hat Linux TrainingredhatresultsRHCARHCE certificationrolessocial media marketing online coursesoftwarestudent poststudents postsuccess storiestablueThreads by Instagramtraining