33 Python Interview Questions for Beginner in 2021: Part 1

33 Python Interview Questions for Beginner in 2021: Part 1
33 Python Interview Questions for Beginner in 2021: Part 1

Introduction

Guido Van Rossum created the Python programming language in the early 1990s, one of the most popular programming languages. No wonder Python is the second most demanded programming language with around 7 million job postings in May 2021, as per Stack Overflow. Over 90% of the Fortune 500 companies are using Python for glueing their development projects. Whether it is for machine learning, web servers or large-scale apps globally, over 8 million Python developers are available.

So if you get an interview call for the Python developer role and are looking for a quick guide before your interview, then you have come to the right place. The whole blog consists of 100 interview questions divided into three parts: Beginner, Intermediate and Advanced. This article is Part 1 of the Python Interview Questions and Answer Series covering beginner-level questions.

Python Interview Questions for Beginners

Question 1) What are the core features of Python?

Answer 1) Following are the main features of the Java programming language:

  • Platform-Independent: Python is a platform-independent language. If you write a program, it will run on different platforms like Windows, Mac, Linux, etc. You are not required to register them separately for each platform.
  • Object-Oriented: Python supports the concepts of Object-Oriented Programming Language such as Inheritance, Encapsulation, Polymorphism, and Abstraction. 
  • Ease of Readability: The Python language is designed to make the life of developers easy. Reading Python programs is like reading an English sentence. This is one of the key reasons that make Python most suitable for beginners.

Python uses indentation, unlike other programming languages, that makes the code look clean and easier to understand.

  • Extensive Standard Library: The standard library is vast and has many packages and modules with common and critical functionalities. If you need something available in the standard library, you probably don’t need to write from scratch. This can help you focus on more important things. 

You may also mention that Python is an interpreted, high-level and general-purpose programming language with one of the most significant community support on StackOverflow, etc. It is a scalable language with a high-performance and robust set of use cases than any other programming language available out there.

Question 2) Is Python a compiled or an Interpreted Language?

Answer 2) Python is an interpreted language. It comes with the ‘IDLE’ (Interactive Development Environment) interpreter. An interpreter that follows the REPL structure (Read-Evaluate-Print-Loop) executes and displays the output of one line at a time.

So it displays errors while you’re running a line and displays the entire stack trace for the error.

Question 3) How do you write comments in Python?

blog banner 1

Answer 3) Comments in Python start with a # character. However, at times, commenting is also done using docstrings(strings enclosed within triple quotes).

Example:

# Comments in Python start like this
print("Comments in Python start with a #")

Output:  Comments in Python start with a #

Question 4) How does memory management take place in Python?

Answer 4) Memory management in Python is handled by the Python Memory Manager, i.e. allocated by the manager is in the form of a private heap space dedicated to Python. All Python objects are stored in a heap, and being personal, it is inaccessible to the programmer. Python does provide some core API functionalities to work upon the private heap space.

 Python also has an in-built garbage collection to recycle the unused memory for the private heap space.

memory_management
Image Source 

Question 5) What is pep 8, and why is it important?

Answer 5) The term ‘PEP’ stands for the Python Enhancement Proposal. It is a set of rules that specifies how to format Python code for maximum readability. A PEP is an official design document that provides information to the Python community serving as guidelines or describing a new feature for Python or its processes and the formats for contributing. PEP 8 is especially significant since it documents the style guidelines for python programs. It contributes to the Python open-source community that requires you to follow these style guidelines sincerely and strictly.

Question 6) What is Scope in Python?

Answer 6) Every object in Python always functions within a scope which is done using indentations. A range is a block/part of code where a thing in Python remains relevant, similar to namespaces that are uniquely used to identify all the objects inside a program. However, these namespaces also have scopes defined for them; where is it that you could use their things without any prefixes. An example of such range created during code execution in Python is as follows:

A local scope in python refers to the local objects that are available in the current function.

 While, for a global scope, it refers to the objects available through the code executions ever since their inception.

A module-level scope refers to global objects of that current module that are accessible in a program.

An outermost scope refers to all those built-in names that are callable in the program. The objects in this scope are searched at the end to find the required name referenced.

Note: Local scope objects can also be synced with global scope objects using keywords such as global.

Image Source

Question 7) What is Scope Resolution in Python?

Answer 7) Sometimes, objects within the same scope have the same name but function differently. In such a case, scope resolution often comes into play in Python automatically. A few examples of such behaviours are as follows:

Python modules, viz. ‘math’ and ‘cmath’ have a lot of functions that are common to both of them – log10(), acos(), exp() etc. To resolve the ambiguity, it is necessary to prefix them with their respective modules, like math.exp() and cmath.exp().

Consider the code below, where an object temp has been initialized with a value of 10 globally and then to 20 on a function call. However, the value didn’t trigger a function call and didn’t change the value of the temp variable globally. We can also observe that Python draws a clear distinction between global and local variables, treating their namespaces as separate identities.

temp = 10 # global-scope variable

def func():
      temp = 20   # local-scope variable
      print(temp)

print(temp) # output => 10
func() # output => 20
print(temp) # output => 10

This behaviour can be overridden using the global keyword inside the function, as shown in the following example:

temp = 10 # global-scope variable

def func():
      global temp
      temp = 20   # local-scope variable
      print(temp)

print(temp) # output => 10
func() # output => 20
print(temp) # output => 20

Question 8) What are python modules, and how are they used? Name some commonly used built-in modules present in Python?

Answer 8) Python modules are files that contain Python programs, which can either be functions, classes or variables. A Python module is a ‘.py’ file that contains executable programs.

Some of the most commonly used built-in modules are:

  • os
  • sys
  • math
  • random
  • DateTime
  • JSON

Question 9) What are the common built-in data types in Python?

Answer 9) There are several built-in data types; However, Python doesn’t require data types to be defined explicitly during variable declarations; type errors are more likely to occur if the knowledge about data types and their compatibility and conversions with each other isn’t well understood. Python provides ‘type()’ and ‘isinstance()’ functions to check the type of these variables. These data types can be grouped into the following categories-

  • None Type

The ‘None’ keyword represents all null values in Python. Boolean equality operations can also be performed using these NoneType objects.

Class NameDescription
NoneTypeRepresents the NULL values in Python
  • Numeric Types

There are three distinct numeric types viz. integers, floating-point numbers and complex numbers. Additionally, an FYI, booleans are a subtype of the built-in integer-type.

Class NameDescription
intStores all integer literals including hex, octal and binary numbers as integers too
floatStores literals comprising of decimal values and/or exponent signs as floating-point numbers
complexStores a complex number in the form (A + Bj) and has attributes: real and imag
boolStores boolean value (True or False)
  • Sequence Types

According to Python Docs, there are three different types of basic Sequence Types – lists, tuples, and range objects. Sequence types have the ‘in’ and the ‘not’ in operators defined for traversing their elements. These operators share the same priority as comparison operations.

Class NameDescription
listIt is a mutable sequence that is used to store a collection of items.
tupleThe immutable sequence is used to store a collection of items.
A rangerepresents an immutable sequence of numbers generated during execution.
strAn immutable sequence of Unicode code points to store textual data.
  • Mapping Types

One can use a mapping object to map hash-able values to random objects. Mapping objects are mutable, and there is currently a single standard mapping type, i.e. dictionary.

Class NameDescription
dictStores a comma-separated list of key-value pairs
  • Set Types

Currently, Python supports built-in set types – set and frozensets. The set type is mutable and helps support methods like add() and remove(). frozenset type is an immutable data type and can’t be modified after its creation.

Class NameDescription
setIs a Mutable an unordered collection of distinct hashable objects
frozensetImmutable collection of distinct hashable objects
  • Modules

The module is an additional built-in type that the Python Interpreter also supports. It also supports one special operation, i.e., attribute access: mymod. myobj, where ‘mymod’ is a module, and ‘myobj’ references a name defined in an m’s symbol table. The module’s symbol table resides in the special attribute of the module ‘__dict__’, but direct assignments to this module are neither possible nor recommended.

  • Callable Types

Callable types are those types to which One can also apply function calls. They can either be user-defined functions, instance methods, generator functions, or other built-in functions, methods, and classes.

Refer to the documentation at docs.python.org for a detailed view of the callable types.

Question 10) What are modules and packages in Python?

Answer 10) Python packages and Python modules are two mechanisms that allow for modular programming in Python. Modularizing has several advantages –

  • Simplicity: Working on single modules helps you focus on a relatively small portion of the existing problem. This makes development easier and less prone to errors.
  • Maintainability: Modules are designed to enforce the logical boundaries between different problem domains. If they are written in a way that reduces interdependency, it is less likely that the modifications in a module might also impact other parts of the program.
  • Reusability: Functions defined in a module can easily be reused by the other parts of the application.
  • Scoping: Modules are typically defined as separate namespaces, which help avoid confusion between identifiers from other aspects of the program.

Modules are simply Python files with a ‘.py’ extension and can have a set of functions, classes and variables defined. They can be imported and initialized using import statements if partial functionality is required to import the requisite classes or functions, such as using the foo import bar.

Packages provide for hierarchical structuring of the module namespace using a ‘.’ dot notation. As modules help avoid clashes between global and local variable names, similarly, packages can help avoid clashes between module names.

Creating a package is easy since it also makes use of the system’s inherent file structure that exists. Modules combined into a folder are known as packages . Importing a module or its contents from a package requires the package name as a prefix to the module’s name joined by a dot.

Question 11) What is the use of the ‘pass’ keyword in Python?

Answer 11) The pass keyword represents null operations in Python. It is used for the purpose of filling up empty blocks of code that may execute during runtime but has yet to be written. Without the ‘pass’ statements in the following code, we may run into errors during code execution.

def anEmptyFunc():
    # does nothing
    pass

anEmptyFunc()    # nothing will happen

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

Question 12) What is the use of help() and dir() functions?

Answer 12) The ‘help()’ function in Python is used to display the documentation of modules, classes, functions, keywords, etc. If no parameter is passed to the ‘help()’ function, an interactive help utility is launched on the console.

While the ‘dir()’ function tries to return a valid list of attributes and methods of the object when called upon, it behaves differently than with the different objects as it aims to produce most relevant data rather than the complete information.

For modules and libraries objects, it returns a list of all attributes present in that module.

Class Objects return a list of all valid attributes and base attributes

 that have no arguments passed, which returns a list of attributes in the current scope.

Question 13) How Python is interpreted?

Answer 13) Python as a language is neither interpreted or compiled. Interpreted or compiled is the property of its implementation. Python is a bytecode (set of interpreter readable instructions) that is generally interpreted.

Source code is a file with a ‘.py’ extension.

Python compiles a source program to a set of instructions for a virtual machine. A Python interpreter is an implementation of this virtual machine. This intermediate format is called “bytecode”.

.py source code is first compiled to give .pyc which is bytecode. This bytecode can be interpreted by the official CPython or JIT(Just in Time compiler) compiled by PyPy.

Question 14) What is the difference between .py and .pyc files?

Answer 14) ‘.py’ files contain the source code of a program. At the same time, a .pyc file contains the bytecode of a program. We get bytecode after the compilation of the .py file (source code). ‘.pyc’ files are not created for all the files that you run. It is only created for the files that you import.

Before executing a python program the interpreter checks for the compiled files; if the file is present, the virtual machine executes it. If not found, it checks for the .py file. If found, compiles it to a .pyc file, and then the Python virtual machine executes it.

Having a ‘.pyc’ file saves you compilation time.

Question 15) What is an Interpreted language?

Answer 15) An Interpreted language executes its statements line by line. Many languages such as Python, Javascript, R, PHP and Ruby are prime examples of being known/built as Interpreted languages. Programs written in these interpreted languages run directly from the source code, with no intermediary compilation step.

Question 16) What are lists and tuples? What are the key differences between them?

Answer 16) Lists and Tuples are both sequences that data types can store a collection of objects. The objects stored in both sequences can also have different data types. Lists are represented with square brackets [‘sara’, 6, 0.19], while tuples are represented with parentheses (‘ansh’, 5, 0.97).

But what’s the real difference between the two? The key differences between them 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 IDLE to confirm the difference:

my_tuple = ('sara', 6, 5, 0.97)
my_list = ['sara', 6, 5, 0.97]

print(my_tuple[0])     # output => 'sara'
print(my_list[0])     # output => 'sara'

my_tuple[0] = 'ansh'    # modifying tuple => throws an error
my_list[0] = 'ansh'    # modifying list => list modified

print(my_tuple[0])     # output => 'sara'
print(my_list[0])     # output => 'ansh'
LISTSTUPLES
Lists are mutable python data types, i.e. One can edit them.Tuples are immutable (tuples are lists that one can’t edit).
Lists are slower than tuples.Tuples are faster than a list.
Syntax: list_1 = [10, ‘Chelsea’, 20]Syntax: tup_1 = (10, ‘Chelsea’ , 20)

Question 17) What is the difference between Python Arrays and lists?

Answer 17) Arrays and lists, in Python, have the same way of storing data with one difference being But, arrays can hold only a single data type element, whereas lists can hold any data type elements.

Example:

import array as arr
My_Array=arr.array('i',[1,2,3,4])
My_list=[1,'abc',1.20]
print(My_Array)
print(My_list)

Output:

array(‘i’, [1, 2, 3, 4]) [1, ‘abc’, 1.2]

Question 18) What are functions in Python?

Answer 18) A function is a block of code that is executed only when it is called to define Python functions; the def keyword is used.

Example:

def Newfunc():
    print("Hi, Welcome to Coding Ninjas!")

Newfunc(); #calling the function

Output: Hi, Welcome to Coding Ninjas!

Question 19) What is __init__?

Answer 19)  Ans: ‘__init__’ is a method or constructor in Python. This method automatically allocates memory when a new object/ instance of a class is created. All classes have the ‘__init__’ method.

Example to show how to use it.

class Employee:
    def __init__(self, name, age,salary):
        self.name = name
        self.age = age
        self.salary = 20000

E1 = Employee("XYZ", 23, 20000)
# E1 is the instance of class Employee.
#__init__ allocates memory for E1. 
print(E1.name)
print(E1.age)
print(E1.salary)

Output:

XYZ

23

20000

Question 20) What platforms are supported by the Python programming language?

Answer 20) Python runs on almost all the major platforms, including Windows, Mac OS, various versions of Linux/UNIX.

Question 21) What is the purpose of is, not and in operators?

Answer 21)  Operators are special type of functions that take one or more values and produce a corresponding result.

is: returns ‘True’ when two operands are true.

not: returns the inverse of any boolean value

in: checks whether some element is present in some sequence

Question 22) What is a dictionary in Python?

Answer 22) The built-in data type in Python is called a dictionary. It defines the one-to-one relationship between the keys and values. Dictionaries contain a pair of keys and their corresponding values. Keys indexes dictionaries.

For Example:

The following example contains some keys. Country, Capital & Continent. Their corresponding values are India, Delhi and Asia, respectively.

dict={'Country':'India','Capital':'Delhi','Continent':'Asia'}
print(dict['Country'])
India
print(dict['Capital'])
Delhi
print(dict['Continent'])
Asia

Question 23) How can the ternary operators be used in Python?

Answer 23) A Ternary operator is an operator that is used to show the conditional statements. It consists of the true or false values along with a statement that has to be evaluated.

Syntax:

The Ternary operator will be given as:

[on_true] if [expression] else [on_false]x, y = 25, 50big = x if x < y else y

Example:

The expression gets evaluated like if x<y else y, in this case, if x<y is true, then the value is returned as big=x, and if it is incorrect, then big=y will be sent as a result.

Question 24) What does len() do?

Answer 24) It is used to determine the length of a string, a list, an array, etc.

Example:

stg='ABCD'
len(stg)

Question 25) What are Python packages?

Answer 25) Python packages are namespaces containing multiple modules.

Question 26) How to import modules in Python?

Answer 26) Modules can be imported using the import keyword where you can import modules in three ways-

i.e.:

import array           # using import statements to import using the original name of the module
import array as arr    # using an alias name
from array import *    #imports everything present in the array module

Question 27) What is the difference between Method overloading and method overriding in Python?

Answer 27) The difference between Method overloading and overriding are summarized in the following table:

Method OverloadingMethod overriding
When a class has multiple methods with the same name but different parameters in the same class.The derived/child class provides a different implementation of the method from the parent class.
Method overloading is done within a single class.Method overriding is done using two classes that have an Is-A or inheritance relation.
Parameters must be differentParameters must be the same
It is an example of compile-time polymorphism.It is an example of run time polymorphism.

Question 28) What are the main concepts of OOPs in Python that it supports?

Answer 28) Object-oriented programming is a methodology to design a program using classes and objects. Java supports the following concepts of OOPs:

  • Class
  • Object
  • Inheritance
  • Polymorphism
  • Abstraction
  • Encapsulation

Question 29) How are classes created in Python? 

Answer 29) Class in Python is created using the class keyword.

Example:

class Employee:
    def __init__(self, name):
        self.name = name

E1=Employee("Eric")
print(E1.name)

Output: Eric

Question 30) What is self in Python?

Answer 30) The ‘self’ keyword is an instance of an object of a class. In Python, it is explicitly included as the first parameter. However, this is not the case with Java, where it’s optional. The ‘self’ argument helps differentiate between the methods and attributes of classes with local variables.

The ‘self’ variable in an ‘init’ method refers to a newly created object, while when passed with other methods, it refers to the object whose method was called.

Question 31) Does Python support multiple inheritance?

Answer 31) Multiple inheritances means that a class can be derived from more than one parent class. Python does support multiple inheritance, unlike Java.

Question 32) How do you copy an object in Python? How can this be used to pass arguments by value or by reference in Python?

Answer 32) In Python, the assignment statement/operator (= operator) does not copy objects. Instead, it creates bindings between existing objects and the target variable names. To create copies of objects in Python, we need to use the copy module. There are two such ways of creating copies for the given object using the copy module –

A shallow copy is a bitwise copy of objects. The copied object created has an exact copy of the values in the original object. If either of the values references other objects, just all the reference addresses for the same are copied.

While a Deep Copy copies all values recursively from source to the target object, i.e. it even duplicates objects referenced by a source object.

from copy import deepcopy, copy 

first_list = [1, 2, [3, 5], 4]

## shallow copy

second_list = copy(first_list) 
second_list[3] = 7
second_list[2].append(6)

second_list    # output => [1, 2, [3, 5, 6], 7]
first_list    # output => [1, 2, [3, 5, 6], 4]

## deep copy

third_list = deepcopy(list_1)
third_list[3] = 8
third_list[2].append(7)

third_list    # output => [1, 2, [3, 5, 6, 7], 8]
first_list    # output => [1, 2, [3, 5, 6], 4]
  • Pass by value: Copy of the actual objects are passed. Changing the values of the copied objects will not change the value of original objects.
  • Pass by reference: References to the actual object are passed in a pass by reference method. Changing the value of a new object will also change the value of the original object.

In Python, arguments are by defualt passed by reference, i.e., reference to the actual object is passed.

from copy import copy


def appendNumber(arr):
    arr.append(4)
    print(arr)


arr = [1, 2, 3]

print(arr)  # Output: => [1, 2, 3]
appendNumber(arr) # Passing By reference
# Output appendNumber : => [1, 2, 3, 4]
print(arr)  # Output outside appendNumber: => [1, 2, 3, 4]


print(arr)  # Output: => [1, 2, 3, 4]
appendNumber(copy(arr)) # Passing By value
# Output appendNumber : => [1, 2, 3, 4, 4]
print(arr)  # Output outside appendNumber: => [1, 2, 3, 4]

Question 33) What are the differences between Stack and heap memory in Python?

Answer 33) Stack Memory:- A physical space allocated to threads at run time follows the LIFO(Last in first out) structure. Variables, References to objects, and partial results are stored in the stack memory.

Heap Memory: The memory is created when the Python Virtual Machine starts and is used as long as the application runs. Python runtime uses heap memory to allocate memory to objects and Python Runtime Environment classes.

In addition to the above questions, one may also ask questions related to Input and Output, Packages, In-built methods. 

Tips

It is always recommended to research the company and your interview role. In addition, the following tips are useful for beginners when preparing for your next big tech interview:

  1. Get your Basics Right: You cannot build a great building on a weak foundation. First of all, I have a solid grip on Python fundamentals. You may refer to our free guided path.
  2. Explaining concepts using examples: Anyone can theoretically answer the difference between lists or dictionaries or the meaning of duck-typing in Python, but explaining the concept using a program will set you apart from others. The interviewer will understand that you know the concepts well.
  3. OOPs: OOPs concepts are one of the most frequently asked questions in Python interviews. It’s recommended to have a clear understanding of the various concepts like Inheritance, Encapsulation etc.
  4. Data Structures and Algorithms: Have a good understanding of the Python programming language’s various data structures and algorithms. You may practice questions asked in top product based companies on Code studio.

Key Takeaways

The article discussed frequently asked Python interview questions for freshers with little or no experience. Once you are done with this, you may check out our Interview Preparation Course to level up your programming journey and get placed at your dream company. 

By: Dhruv Sharma