LogoLogo

Basic Python [Core] Interview Questions for Freshers and Short Sample Answers — 2022

Prasun Das| June 25, 2022 at 3:53 PM | 11 minutes Read

The most popular high-level, multipurpose programming language right now is Python.

Python supports procedural and object-oriented programming paradigms.

Compared to other programming languages like Java, Python programmes are typically smaller. Programmers have to type comparatively less, and the language's indentation requirement keeps their work always readable.

Python, fortunately, has a straightforward syntax that is simple to use which makes it a great language for beginners to learn to program.






As we know that python is a very advanced language and due to its ability to support powerful computations using powerful libraries it has huge applications in almost every domain. It can be used for ml, iot, web dev etc. But our concern here is to learn the fundamentals of python which is necessary to start with the basic coding, getting accustomed to the syntax and performing basic operations.

Also one should keep in mind that if someone lists Python as a strength on their resume, they must also specify the domain which they have worked on in order to not get tricked by the interviewer and avoid further confusions.


Following are basic python interview question :







1. What is the main difference between an interpreter and a compiler?

The interpreter translates one statement at a time into machine code, whereas the compiler translates the entire code at a time into machine code.


2. Is Python interpreted or compiled?

As noted in Why Are There So Many Pythons?, this is, frankly, a bit of a trick question in that it is malformed. Python itself is nothing more than an interface definition (as is true with any language specification) of which there are multiple implementations. Accordingly, the question of whether "Python" is interpreted or compiled does not apply to the Python language itself; rather, it applies to each specific implementation of the Python specification.


Further complicating the answer to this question is the fact that, in the case of CPython (the most common Python implementation), the answer really is "sort of both". Specifically, with CPython, code is first compiled and then interpreted. More precisely, it is not precompiled to native machine code, but rather to bytecode. While machine code is certainly faster, bytecode is more portable and secure. The bytecode is then interpreted in the case of CPython (or both interpreted and compiled to optimised machine code at runtime in the case of PyPy).









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

Lists and Tuples are both sequence data types that can store a collection of objects in Python. The objects stored in both sequences can have different data types. Lists are represented with square brackets ['sara', 6, 0.19], while tuples are represented with parantheses ('ansh', 5, 0.97).

But what is the real difference between the two? The key difference between the two is that while lists are mutable, tuples on the other hand are immutable objects. This means that lists can be modified, appended or sliced on the go but tuples remain constant and cannot be modified in any manner. You can run the following example on Python IDE to confirm the difference:





tuple1 = ('sara', 6, 5, 0.97)
list1 = ['sara', 6, 5, 0.97]
print(tuple1[0])  # output => 'sara'
print(list1[0])  # output => 'sara'
tuple1[0] = 'ansh'  # modifying tuple => throws an error
list1[0] = 'ansh'  # modifying list => list modified
print(tuple1[0])  # output => 'sara'
print(list1[0])  # output => 'ansh'






4. What is the difference between range and xrange? How has this changed over time?


As follows:

xrange returns the xrange object while range returns the list, and uses the same memory and no matter what the range size is.

For the most part, xrange and range are the exact same in terms of functionality. They both provide a way to generate a list of integers for you to use, however you please.

The only difference is that range returns a Python list object and x range returns an xrange object. This means that xrange doesn't actually generate a static list at run-time like range does. It creates the values as you need them with a special technique called yielding. This technique is used with a type of object known as generators. That means that if you have a really gigantic range you'd like to generate a list for, say one billion, xrange is the function to use.

This is especially true if you have a really memory sensitive system such as a cell phone that you are working with, as range will use as much memory as it can to create your array of integers, which can result in a Memory Error and crash your program. It's a memory hungry beast.





5. What is a method?

A method is a function on some object x that you normally call as x.name(arguments...). Methods are defined as functions inside the class definition:







class PepHub: 
    def method (self, arg): 
        return arg*2 + self.attribute




6. How do I call a method defined in a base class from a derived class that overrides it?


If you're using new-style classes, use the built-in super() function:







class Derived(Base):
    def my_method (self): 
       super(Derived, self).my_method()

 

If you're using classic classes: For a class definition such as class Derived(Base): ... you can call method my_method() defined in Base (or one of Base's base classes) as Base.meth(self,arguments). Here, Base.meth is an unbound method, so you need to provide the self argument.



7. How do I access a module written in Python from C?

You can get a pointer to the module object as follows:







module = PyImport_ImportModule("");


If the module hasn't been imported yet (i.e. it is not yet present in sys.modules), this initialises the module; otherwise it simply returns the value of sys.modules[""]. Note that it doesn't enter the module into any namespace -- it only ensures it has been initialised and is stored in sys.modules. You can then access the module's attributes (i.e. any name defined in the module) as follows: attr = PyObject_GetAttrString(module, ""); Calling PyObject_SetAttrString() to assign to variables in the module also works.



8. Does Python have a switch-case statement?


 In languages like C++, we have something like this:







switch(birth_month)
{
    case 'Jenny':
        cout<<"February";
        break;
    case 'Sam':
        cout<<"June";
        break;
    default:
        cout<<"Not Known";
}


But in Python, we do not have a switch-case statement. Here, you may write a switch function to use. Else, you may use a set of if-elif-else statements. To implement a function for this, we may use a dictionary.







def switch(choice):     
    switcher={
        'Jenny':'February',
        'Sam':'June',
        print(switcher.get(choice,'Not Known'))
    return 
    switch('Sam')
    June
    switch('Jenny')
    February
    switch('Ben')
    Not Known
    }



Here, the get() method returns the value of the key. When no key matches, the default value (the second argument) is returned.









9. What is Pythonpath?

A Pythonpath tells the Python interpreter to locate the module files that can be imported into the program. It includes the Python source library directory and source code directory.







10. Can we preset Pythonpath?

Yes, we can preset Pythonpath as a Python installer.







11. Why do we use Pythonstartup environment variable?

We use the Pythonstartup environment variable because it consists of the path in which the initialization file carrying Python source code can be executed to start the interpreter. 







12. What is the Pythoncaseok environment variable?

Pythoncaseok environment variable is applied in Windows with the purpose to direct Python to find the first case insensitive match in an import statement.







13. What are the supported standard data types in Python?

The supported standard data types in Python include the following.







14. How will you differentiate between deep copy and shallow copy?

Answer: We use a shallow copy when a new instance type gets created. It keeps the values that are copied in the new instance. Just like it copies the values, the shallow copy also copies the reference pointers.

Reference points copied in the shallow copy reference to the original objects. Any changes made in any member of the class affect the original copy of the same. Shallow copy enables faster execution of the program.

Deep copy is used for storing values that are already copied. Unlike shallow copy, it doesn’t copy the reference pointers to the objects. Deep copy makes the reference to an object in addition to storing the new object that is pointed by some other object.

Changes made to the original copy will not affect any other copy that makes use of the referenced or stored object. Contrary to the shallow copy, deep copy makes execution of a program slower. This is due to the fact that it makes some copies for each object that is called.

 

15. What is pass in Python?

The pass keyword 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. Without the pass statement in the following code, we may run into some errors during code execution.






def myEmptyFuncDemo():
   # do nothing
   pass
myEmptyFuncDemo()    # nothing happens






## Without the pass keyword
# File "<stdin>", line 3
# IndentationError: expected an indented block

 






16 . What is __init__?

__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. It helps in distinguishing methods and attributes of a class from local variables.





# class definition
class Employee:
   def __init__(empname, fname, lname, age, section):
       empname.firstname = fname
       empname.lastname = lname
       empname.age = age
       empname.section = section
# creating a new object
emp1 = Employee("Sara", "Ansh", 22, "A2")




 

17. What are modules and packages in Python?

Python packages and Python modules are two mechanisms that allow for modular programming in Python. Modularizing has several advantages -


Simplicity: Working on a single module helps you focus on a relatively small portion of the problem at hand. This makes development easier and less error-prone.

Maintainability: Modules are designed to enforce logical boundaries between different problem domains. If they are written in a manner that reduces interdependency, it is less likely that modifications in a module might impact other parts of the program.

Reusability: Functions defined in a module can be easily reused by other parts of the application.

Scoping: Modules typically define a separate namespace, which helps avoid confusion between identifiers from other parts of the program.

Modules, in general, are simply Python files with a .py extension and can have a set of functions, classes, or variables defined and implemented. They can be imported and initialised once using the import statement. If partial functionality is needed, import the requisite classes or functions using from foo import bar.


Packages allow for hierarchical structuring of the module namespace using dot notation. As modules help avoid clashes between global variable names, in a similar manner, packages help avoid clashes between module names.

Creating a package is easy since it makes use of the system's inherent file structure. So just stuff the modules into a folder and there you have it, the folder name as the package name. Importing a module or its contents from this package requires the package name as prefix to the module name joined by a dot.


Note: You can technically import the package as well, but alas, it doesn't import the modules within the package to the local namespace, thus, it is practically useless.



18. Do we need to call the explicit methods to destroy the memory allocated in Python?


In Python “Garbage” collection is an in-built feature that takes care of allocating and de-allocating memory. This is very similar to the feature in Java. Hence, there are very fewer chances of memory leaks in your application code.


19. What is slicing in Python?






  • As the name suggests, ‘slicing’ is taking parts of.
  • Syntax for slicing is [start : stop : step]
  • start is the starting index from where to slice a list or tuple
  • stop is the ending index or where to sop.
  • step is the number of steps to jump.
  • Default value for start is 0, stop is number of items, step is 1.
  • Slicing can be done on strings, arrays, lists, and tuples.





my_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(my_numbers[1 : : 2])  #output : [2, 4, 6, 8, 10]


20. What are decorators in Python?

Decorators in Python are essentially functions that add functionality to an existing function in Python without changing the structure of the function itself. They are represented the @decorator_name in Python and are called in a bottom-up fashion. For example:





# decorator function to convert to lowercase
def lowercase_decorator(function):
   def wrapper():
       func = function()
       string_lowercase = func.lower()
       return string_lowercase
   return wrapper






# decorator function to split words
def splitter_decorator(function):
   def wrapper():
       func = function()
       string_split = func.split()
       return string_split
   return wrapper


@splitter_decorator # this is executed next

@lowercase_decorator # this is executed first







def hello():
   return 'Hello World'
hello()   # output => [ 'hello' , 'world' ]


The beauty of the decorators lies in the fact that besides adding functionality to the output of the method, they can even accept arguments for functions and can further modify those arguments before passing it to the function itself. The inner nested function, i.e. 'wrapper' function, plays a significant role here. It is implemented to enforce encapsulation and thus, keep itself hidden from the global scope.







# decorator function to capitalise names
def names_decorator(function):
   def wrapper(arg1, arg2):
       arg1 = arg1.capitalize()
       arg2 = arg2.capitalize()
       string_hello = function(arg1, arg2)
       return string_hello
   return wrapper
@names_decorator
def say_hello(name1, name2):
   return 'Hello ' + name1 + '! Hello ' + name2 + '!'
say_hello('sara', 'ansh')   # output => 'Hello Sara! Hello Ansh!'


21. What are iterators in Python?






  • An iterator is an object.
  • It remembers its state i.e., where it is during iteration (see code below to see how)
  • __iter__() method initialises an iterator.
  • It has a __next__() method which returns the next item in iteration and points to the next element. Upon reaching the end of the iterable object __next__() must return StopIteration exception.
  • It is also self-iterable.
  • Iterators are objects with which we can iterate over iterable objects like lists, strings, etc.








class ArrayListDemo:
   def __initr__(arr, num_list):
       arr.numbers = num_list
   def __itrer__(arr):
       arr.pos = 0
       return arr
   def __next__(arr):
       if(arr.pos < len(arr.numbers)):
           arr.pos += 1
           return arr.numbers[arr.pos - 1]
       else:
           raise StopIteration
myarray_obj = ArrayListDemo([1, 2, 3])
itr = iter(myarray_obj)
print(next(itr)) #output: 2
print(next(itr)) #output: 3
print(next(itr))
#Throws Exception
#Traceback (most recent call last):
#...
#StopIteration




22. How is an empty class created in python?

An empty class does not have any members defined in it. It is created by using the pass keyword (the pass command does nothing in python). We can create objects for this class outside the class.

For example-







class MyEmptyClass:
   pass
obj=MyEmptyClass()
obj.name="PepHub"
print("Name created= ",obj.name)
Output:
Name created = PepHub
#interview questions#python#interview preparation#fundamentals to learn
View Count:6.1k
0

Comments

Similar Articles

PWC Placement Experince

PricewaterhouseCooper Pvt Ltd (PwC Pvt Ltd) is a leading multinational professional service network of firms, operating as partnerships under the PwC ......

Cover image

DSA Cheatsheet Curated list (Leetcode)

If you're looking to prepare for a job in the tech industry, Data Structures and Algorithms (DSA) are essential to master. Practising problems on plat......

Cover image

How to Start with DSA

Each and every programmer needs a strong grasp in DSA to write efficient and optimised codes. However, DSA has a reputation of being one of the most f......

Cover image

Campus Placement Roadmap for Batch 2024

Its that time round the calendar again, but different for you all as for the first time now. You all will be facing the on campus placement season.Wit......

Cover image

Busting myths about web3

WHAT IS WEB3?Web3 is the catch-all term for the vision of an upgraded version of the internet aimed at giving power back to the users. It is truly the......

Cover image

Operating System INTERVIEW QUESTIONS

Operating Systems is one of the core subjects for a computer science student. As such a lot of important questions are asked on this subject in interv......

Cover image

Cognizant previous year QnA and Interview Experience

Cognizant helps organizations remain ahead of the competition by modernizing technology, reinventing processes, and redefining customer experiences. I...

Cover image

Cloud Computing Cheatsheet

Getting started with cloud computing ?The words "cloud" and "web" will be interchangeable. What kind of business operates today without the internet? ...

Cover image

Software Engineering — SOFTWARE MAINTENANCE [Part-4]

SOFTWARE MAINTENANCE:Software Maintenance can be defined as the process of modifying a software product after its delivery. The main purpose of softwa...

Cover image

Software Engineering — Software Process Activities [Part - 3]

A quick summary upto what we did this far&nbsp; from this series:Software EngineeringSoftware engineering is a discipline of engineering concerned wit...

Cover image

Capgemini Previous Year Questions with Study Materials

Capgemini is a global leader in consulting, digital transformation, technology, and engineering services. In the rapidly evolving world of cloud, digi...

Cover image

MINDTREE Interview Experience and Previous Year Questions Part 2

Technical Round :Candidates who pass the online test will be invited to the technical interview...

Cover image

MINDTREE Interview Experience and Previous Year Questions Part 1

About Mindtree:Mindtree Ltd, located in Bangalore, India, is a prominent Indian multinational information technology and outsourcing company. The&nbsp...

Cover image

TCS NQT Latest Questions and Answers

TCS NQT Interview kicks off with the aptitude test. The test follows the following pattern :&nbsp;TCS uses the TCS-iON software for their online aptit...

Cover image

INTERVIEW TIPS AND TRICKS FOR FRESHERS

Increased competition for fewer jobs in the current economy means that just being right for the role on paper, is not enough on its own anymore. You h...

Cover image

TCS NINJA INTERVIEW EXPERIENCE [2023]

About TCS NinjaTCS administers the NQT to select candidates for a variety of positions (National Qualifier Test). Tens of thousands of people apply fo...

Cover image

Understanding Time Complexity with Interview Examples

Introduction:Understanding time complexity of a function is imperative for every programmer to execute a program in the most efficient manner. Time co...

Cover image

Software Engineering — Software Development lifecycle and software process(Part 2)

&nbsp;Software MethodologyA software methodology (which is also known as software process) is a set of related development Phases that leads to the pr...

Cover image

TCS Digital Interview Experience [2023]

About TCS DigitalTCS selects applicants for a variety of jobs by conducting the NQT (National Qualifier Test). About 10,000-15,000 job applicants subm...

Cover image

Software Engineering [Part 1] - Introduction

Software Engineering is a subject that requires when you are a software developer as well as when you are in your college preparing for a semester or ...

Cover image

SQL Interview Questions

Are you getting ready for your SQL developer job interview?You've come to the correct place.This tutorial will assist you in brushing up on your SQL s...

Cover image

SQL CHEATSHEET

Introduction: What is SQL?To understand SQL, we must first understand databases and database management systems (DBMS).Data is essentially a collectio...

Cover image

TCS NQT Technical Interview Questions

TCS Recruitment ProcessInterview RoundsInterview round 1:&nbsp; TCS NQTTCS NQT (National Qualifier T...

Cover image

TCS NQT Aptitude Questions

TCS NQT Aptitude has three sections, namely the Numerical Ability, Verbal Ability, and Reasoning Abi...

Cover image

TCS NQT Interview Experience [2023]

About TCS NQTTCS NQTs, also known as TCS National Qualifier Tests or Tata Consultancy Services Natio...

Cover image

Computer Networking Cheatsheet (Last Minute Notes)

&nbsp;Networking: Importance in real life!Using a computer for work, as well as for personal use, ha...

Cover image

Database Management System Last Minute Notes [Part - 2]

ER-DiagramWhat are ER Models ?An Entity Relationship Diagram (ERD) is a visual representation of dif...

Cover image

Database Management System Last Minute Notes [Part - 1]

What is actually DBMS?A Database Management System (DBMS) is system software used to manage the orga...

Cover image

Final year Placement Roadmap in India

Nowadays students tend to go more for off campus placements rather than on campus placements.One of ...

Cover image

C Cheatsheet

C CHEATSHEETINTRODUCTION:C programming language was developed by Dennis Ritchie of Bell Labs in 1972...

Cover image

C Interview Questions — 2022

C is a general purpose high-level language most popular amongst coders, it is the most compatible, e...

Cover image

Cognizant GenC Next Interview

What is GenC and GenC Next?GenC stands for Generation Cognizant. It basically means the fresher hiri...

Cover image

C++ STL Cheat Sheet

C++ programming language has templates which basically allows functions and classes to work with gen...

Cover image

C++ CHEAT SHEET

C++ was conceived in the late 1970s to overcome the limitations of C. It&nbsp; is an extension of th...

Cover image

Python [Advanced] Interview Questions — 2022

Interview Questions are a great source to test your knowledge about any specific field. But remember...

Cover image

Python Cheat Sheet - Learn the basics of Python

IntroductionPython is a high-level programming language with dynamic binding and high-level inherent...

Cover image

Basic Java Interview Questions for Freshers and Short Sample Answers — 2022

Interview Questions are a great source to test your knowledge about any specific field. But remember...

Cover image

Java OOP Cheat Sheet — A Quick Guide to Object-Oriented Programming in Java

Object-Oriented Programming or better known as OOPs is one of the major pillars of Java that has lev...

Cover image

Learn Java: Basics to Advanced Concepts [Java Cheatsheet]

Java is a high-level programming language known for its robustness, object-oriented nature, enhanced...

Cover image

A Complete Roadmap for On-Campus Placements

Placements are an important part of engineering life, and while everyone hopes to be placed in a reputable company, only a few are successful. This is primarily due to a...

Cover image