Python Interview Questions
Top Python Technical Interview Questions with Answers
Here, Python Technical Interview Questions page will help you to get the Python-based Theoretical and Coding Questions that are frequently asked in Technical Interviews if you have opted for Python as your preferred language.
Go through this page to get all the sample questions for preparing for Python Technical Interview.
Introduction To Python
Python is a high-level, interpreted programming language known for its simplicity and readability. Created by Guido van Rossum in the late 1980s, Python supports code readability and a clear syntax that allows programmers to express concepts in fewer lines of code as compared to other languages.
Here are some key features of Python:
- Easy to Learn and Use: Python has a clean, simple, and small syntax that makes it easy for beginners to understand and write code.
- Versatile and Cross-Platform: Python can be used for a wide range of applications, including web development, data analysis, scientific computing, artificial intelligence, machine learning, automation, and more.
- Interpreted and Interactive: Python is an interpreted language, which means that the code is executed line by line without the need for explicit compilation.
- Large Standard Library: Python comes with a comprehensive standard library that provides a wide range of modules and functions for common tasks. It offers ready-to-use modules for file I/O, networking, regular expressions, database access, and much more, reducing the need for external dependencies.
- Third-Party Ecosystem: Python has a thriving ecosystem of third-party libraries and frameworks maintained by the community. These libraries extend Python’s capabilities and offer specialized tools for specific domains, such as Django and Flask for web development, NumPy and Pandas for data manipulation, TensorFlow and PyTorch for machine learning, and many others.
- Dynamic Typing: Python uses dynamic typing, which means that you don’t need to explicitly declare variable types. The type of a variable is determined at runtime based on the assigned value. This allows for flexibility and faster development but requires attention to type-related issues.
Python Interview Questions for Freshers
Question 1: Tell something about Python ?
Answer: Python is a general-purpose, high-level, and interpreted programming language. Python supports objects, modules, exception-handling, threads, and automatic memory management which help in solving real-world problems with less coding.
Question 2: What are the benefits of using Python?
Answer: Python benefits:
- Readable and simple syntax.
- Large standard library.
- Wide variety of third-party libraries and frameworks.
- Easy integration with other languages.
- Powerful for data analysis and scientific computing.
- Ideal for automation and scripting.
Question 3: Name some Libraries of Python Programing language and their application?
Answer:
NumPy: It provides operations on multi-dimensional arrays, mathematical functions, and tools for working with large datasets. In simple words it enables us to perform complex mathematical operations.
NumPy is mainly used in data analysis, scientific calculations, and machine learning.
Pandas: This library is used for data manipulation and analysis. Pandas offers data structures (such as DataFrames) and functions for cleaning, transforming and exploring structured data.
Matplotlib: This library for creating static, animated, and interactive visualizations in Python from the data provided by the user. Matplotlib enables the creation of various plots, charts, and graphs, making it a go-to choice for data visualization tasks.
TensorFlow: An open-source library for machine learning and deep learning. TensorFlow provides a flexible ecosystem for building and deploying machine learning models, especially neural networks. It is widely used in research, production-grade applications, and AI development.
Scikit-learn: A machine learning library that offers a range of algorithms and tools for data mining, classification, regression, clustering, and dimensionality reduction. Scikit-learn simplifies the implementation of machine learning models and pipelines.
Beautiful Soup: A library for web scraping and parsing HTML/XML documents. Beautiful Soup makes it easy to extract data from web pages, navigate the HTML/XML structure, and scrape information for various applications.
PyTorch: PyTorch is designed to take advantage of GPUs for fast computation in deep learning tasks. It provides a tensor library that enables efficient data storage and manipulation on GPUs. PyTorch is widely used in developing and training neural networks.
Question 4: What is the difference between Compiled Languages and Interpreted Languages?
Answer:
In the case of compiled languages, the source code is translated entirely into machine code by a compiler before execution. The resulting compiled program can be directly executed by the computer’s processor, providing fast and efficient performance.
Ex – C, C++, and Rust.
And in the case of Interpreted language, an interpreter reads and executes the source code line by line at runtime. The interpreter translates each line of code into machine code while the program is running.
Ex- Python, JavaScript, and Ruby.
Question 5: What is a module in Python with example?
Answer: Module is a file containing Python definitions, functions, classes, and variables. It acts as a container for related code and can be imported into other Python programs using the import statement. Modules help in modularizing code and promote code reuse.
“Import” is used to get all functionalities of any particular module.
Ex-
Python provides a wide range of built-in modules that offer various functionalities like:
- math: Provides mathematical functions and constants.
- random: Offers functions for generating pseudo-random numbers.
- datetime: Enables manipulation of dates, times, and time intervals.
- os: Allows interaction with the operating system, providing functions for file operations, directory handling, etc.
- sys: Provides access to system-specific parameters and functions.
- json: Enables encoding and decoding of JSON data.
- re: Provides regular expression matching operations.
- csv: Offers functionality for reading and writing CSV files.
- urllib: Allows making HTTP requests and working with URLs.
- sqlite3: Provides a simple and lightweight database interface for SQLite database
Example:
import math value = math.pi print("Value of Pi = : ",value)
Question 6: In python, arguments are passed by reference or value ?
Answer:
In python, arguments are passed through reference. This means that when a function is called and an argument is passed, a reference to the object is passed in place of the value itself.
Question 7: What is the use of Floor Division (//) in python?
Result = 10 // 3 print(Result) Output: 3
Question 8: What is the use Range function in python ?
Answer:
range() function in Python allows to create a sequence of numbers that can be used for iteration. It can be used to create a range of numbers with a specified start, stop, and step value.
[ i.e. range( start, stop, steps) ]
Code Ex –
for i in range(10): print(i) #Output: 0 1 2 3 4 5 6 7 8 9 for j in range(0, 10, 2): print(j) #Output: 0 2 4 6 8
Question 9: What is the difference between data structures like list, tuples, dictionaries and sets in python ?
List | Tuples | Dictionaries | Sets |
---|---|---|---|
Ordered collection of items. | Ordered collection of items. | Collection of key-value pairs. And Unordered (no specific order of elements). | Unordered collection of unique elements. |
Mutable (can be modified after creation). | Immutable (cannot be modified after creation). | Mutable | Mutable |
Allows duplicate elements. | Allows duplicate elements. | Keys are unique, and values can be duplicated. | Doesn’t allow duplicate elements. |
Elements are enclosed in square brackets [ ]. | Elements are enclosed in parentheses ( ) or can be without any enclosure. | Elements are enclosed in curly braces { }, with each item consisting of a key and its value separated by a colon : | Elements are enclosed in curly braces { }. |
Ex- fruits = [“apple”, “banana”, “orange”, “grape”] | Ex- numbers = (“Twenty”, 20, “Thirty”) | Ex- assassin = {“name”: “John Wick”, “age”: 28, “major”: “Self Defence & Martial Art”} | Ex- numbers = {1, 2, 3, 4, 5} |
Question 10: What is a Negative Index in Python? Give an Example.
Answer:
Negative indexing allows us to access elements from the end of a sequence by using negative numbers as their indices.
Last element has an index of -1
Second last has an index of -2
Third last has an index of -3 and so on.
Question 11: What are *args and **kwargs in python?
Answer:
*args (pronounced “star args”) allows you to pass multiple number of arguments to a function without specifying their names in advance. It collects all the arguments into a tuple, which you can access within the function.
def prac_function(*args): for ARG in args: print(ARG) prac_function(1,2,3,4,5,6) #Output: 1 2 3 4 5 6
def prac_function(**kwargs): for key, value in kwargs.items(): print(key, value) prac_function(Name='Viraj', Age=22, City='Lucknow')
Question 12: What is Slicing ?
Answer: Slicing is a technique used to extract a part or a subsequence of a sequence, such as a string, list, or tuple. It allows you to retrieve a specific range of elements or specific element from the sequence based on indices.
Basic syntax for slicing = “sequence_name[start:stop:step]”
Code Ex-
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] sliced = my_list[2:6] print(sliced) #Output: [3, 4, 5, 6] # Slicing with negative indices to get the last three elements sliced = my_list[-3:] print(sliced) #Output: [8, 9, 10]
Question 13: What is the Lambda expressions in Python ? Explain with an example.
Answer:
Lambda expressions are a way to quickly create what are known as anonymous functions, basically just, one-time-use functions that you don’t even really name. You just use them one time and then never reference them again.
Code Ex-
add = lambda x, y: x + y result = add(20,15) print(result) #Output: 35
Question 14: What is PEP 8 ?
Answer:
PEP 8 is a guide that helps in writing clean, consistent, and maintainable Python code that is easy to read and understand. It stands for Python Enhancement Proposal, it specifically provides guidelines and recommendations on how to format and structure Python code to enhance readability and reliability of the code.
Some key points of PEP 8 include:
- Indentation: Use 4 spaces for indentation to improve code readability.
- Line Length: Limit lines to a maximum of 79 characters to ensure readability, although it can be extended up to 120 characters in certain cases.
- Naming Conventions
- Function and Variable Names
- Imports: Import modules on separate lines and follow a specific ordering convention (standard library modules, third-party modules, local modules).
- It also provides numerous other guidelines covering various aspects of coding style, including whitespace, blank lines, operator spacing, and more.
Question 15: What are .py and .pyc files ?
Answer:
.py files:
- These files contain Python source code written in plain text.
- They are human-readable and editable using a text editor or integrated development environment (IDE).
- Python source code is typically saved with the .py extension.
.pyc files:
- These files are compiled bytecode files generated by the Python interpreter.
- They are not human-readable and cannot be edited directly.
- The Python interpreter compiles the .py source code into bytecode and saves it as a .pyc file for efficient execution in subsequent runs.
- The .pyc files speed up the loading and execution of Python programs since the interpreter can directly execute the bytecode without the need for recompilation.
Question 16: What are the types of literals in Python?
Answer:
- Numeric Literal: Numeric literals can be floating-point values, integers, or complex numbers.
- Character Literal: A character literal consists of a single character enclosed in double quotes.
- Boolean Literal: The boolean literals are True or False.
- Literal Collections: There are four types of literal collections, including list literals, tuple literals, set literals, and dictionary literals.
- String Literal: String literal is created by assigning text to a variable using single or double quotes. Multiline literals can be formed by enclosing text within triple quotes.
Question 17: What are some built in data types in python ?
Answer:
Numeric Types:
- int: Represents integer values (e.g., 1, 5, -10).
- float: Represents floating-point numbers with decimal values (e.g., 3.14, -0.5).
Sequence Types:
- str: Represents a sequence of characters, also known as strings (e.g., “hello”, ‘world’).
- list: Represents an ordered collection of items (e.g., [1, 2, 3], [‘apple’, ‘banana’]).
- tuple: Represents an ordered, immutable collection of items (e.g., (1, 2, 3), (‘a’, ‘b’, ‘c’)).
Mapping Type:
dict: Represents a collection of key-value pairs (e.g., {‘name’: ‘John’, ‘age’: 25}).
Set Types:
set: Represents an unordered collection of unique elements (e.g., {1, 2, 3}).
Boolean Type:
bool: Represents the truth values True and False.
None Type:
None: Represents the absence of a value or the null value.
Question 18: What is pickling and Unpickling in Python ?
Answer:
Pickling:
- Pickling is the process of converting a Python object hierarchy into a byte stream.
- It allows you to save the state of an object or a collection of objects as a file or transfer it over a network.
- The resulting byte stream can be stored persistently or transmitted between different systems.
- Pickling is commonly used for tasks like caching, serialization, and data persistence.
Unpickling:
- Unpickling is the process of reconstructing a Python object hierarchy from a byte stream.
- It is the reverse operation of pickling and allows you to restore the state of the objects.
- By unpickling, you can retrieve the original object or data structure that was pickled.
- Unpickling is essential when you want to retrieve and utilize the saved data or objects.
Question 19: How memory is managed in python programming language ?
Answer:
In Python, memory management operates in the following manner:
- Memory management in Python is handled by a private heap space. All Python objects and data structures are stored within this private heap, which remains inaccessible to programmers. The responsibility of managing this private heap lies with the Python interpreter.
- The allocation of heap space for Python objects is handled by Python’s memory manager. Although programmers do not have direct access to this process, Python’s core API provides certain tools that can be utilized.
- Python incorporates an internal garbage collector that is responsible for reclaiming unused memory. This ensures that memory becomes available within the heap space for future utilization.
Question 20: What are Deep Copy and Shallow Copy ?
Answer:
Shallow Copy:
- Shallow copy creates a new object and then copies the references of the original object’s elements into the new object.
- The new object and the original object share the same elements (references), so changes made to one object may affect the other.
- In a shallow copy, the top-level elements are copied, but the nested objects within them are not duplicated.
- Shallow copies are created using methods like slicing, the `copy()` method, or the `copy` module.
Deep Copy:
- Deep copy creates a new object and recursively copies all the elements and nested objects of the original object.
- The new object is completely independent of the original object, and any changes made to one object do not affect the other.
- Deep copies ensure that all levels of the object hierarchy are duplicated, including nested objects and their references.
- Deep copies are created using the `copy.deepcopy()` function from the `copy` module.
Python OOPS Interview Questions
Question 21: List some common Python interpreters.
Answer:
- CPython: The default and most widely used Python interpreter. It is written in C and serves as the reference implementation for the Python language.
- Jython: An implementation of Python that runs on the Java Virtual Machine (JVM). It allows seamless integration with Java code and libraries.
- IronPython: An implementation of Python targeting the .NET framework. It provides integration with the .NET ecosystem and allows Python code to interact with .NET languages and libraries.
- PyPy: A fast and highly optimized implementation of Python. It utilizes a Just-in-Time (JIT) compiler to improve execution speed.
- Stackless Python: A variant of CPython that provides support for micro threads, allowing lightweight concurrency without the need for traditional operating system threads.
- MicroPython: A lightweight implementation of Python specifically designed for microcontrollers and embedded systems. It provides a reduced subset of the Python language to optimize for limited resources.
Question 22: Write a program to produce the Fibonacci series in Python.
Answer:
def fibonacci(n): series = [ ] a, b = 0, 1 while len(series) < n: series.append(a) a, b = b, a + b return series n = int(input("Enter number of terms in the Fibonacci series: ")) fibonacci_series = fibonacci(n) print("Fibonacci series:", fibonacci_series)
Question 23: Differentiate between Pyramid, Django, and Flask.
Answer:
Django | Pyramid | Flask |
---|---|---|
Django is a high-level, full-featured web framework that follows the batteries included methodology. | Pyramid is a flexible, minimalist web framework that follows the “pay only for what you need”. | Flask is a lightweight web framework that has simplicity and extensibility. |
It provides a huge set of built-in features, such as an ORM (Object-Relational Mapping), authentication, routing, templating, and admin interface. | It provides a core set of tools for building web applications, allowing developers to choose and add additional components as needed. | It provides the resources for building web applications but keeps the core framework minimalistic. |
Django is suitable for building complex, database-driven web applications with less code and rapid development. | Pyramid is highly customizable and adaptable, making it suitable for a wide range of applications, from simple to complex. | Flask allows developers to choose extensions based on their specific requirements, making it highly modular. |
It enforces a specific project structure and follows the Model-View-Controller (MVC) architectural pattern. | It follows a “traversal” routing system and supports various templating engines. | It follows a route-decorator approach and supports various templating engines. |
Question 24: What is Dynamically typed and Statically typed languages ?
Answer:
Dynamically Typed: In dynamically typed languages, variable types are determined at runtime, meaning that type checking occurs during program execution. Variables can be assigned values of different types at different points in the program.
Code Ex-
# Dynamically typed language example (Python) x = 10 # x is an integer print(x) x = "Ten" # x is now a string print(x) x = [10, 20, 30] # x is now a list print(x)
Statically Typed: In statically typed languages, variable types are checked and resolved during compile-time, before the program is executed. Variables must be explicitly declared with their types, and type checking is performed at compile-time.
Code Ex-
#include<bits/stdc++.h> using namespace std; int main () { int x = 5; // x is an integer cout << x << endl; x = "Hello"; cout << x << endl; return 0; } // Error: invalid conversion from 'const char*' to 'int'
Question 25: What is OOPs Concepts ? Explain all of them with examples.
Answer:
1. Encapsulation:
Encapsulation is the process of hiding the internal implementation details of an object and exposing only the necessary information. It helps in achieving data security and code maintainability.
Ex-
class Car: def __init__(self, brand, model): self.brand = brand self.model = model def start_engine(self): print("Engine started.") my_car = Car("Ford", "Mustang") print(my_car.brand) Output: Ford my_car.start_engine() #Output: Engine started
2. Inheritance:
Inheritance is a mechanism where a class inherits properties and methods from a parent class. It allows code reuse and the creation of specialized classes based on more general classes.
Ex-
class Animal: def __init__(self, name): self.name = name def speak(self): print("Animal speaks.") class Dog(Animal): def speak(self): print("Woof!") my_dog = Dog("Buddy") print(my_dog.name) Output: Buddy my_dog.speak() #Output: Woof!
3. Polymorphism:
Polymorphism allows objects of different classes to be treated as objects of a common base class. It provides flexibility and extensibility in handling objects of different types.
Ex-
class Shape: def area(self): pass class Rectangle(Shape): def __init__(self, width, height): self.width = width self.height = height def area(self): return self.width * self.height class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return 3.14 * self.radius ** 2 shapes = [Rectangle(4, 5), Circle(3)] for shape in shapes: print(shape.area())
4. Abstraction:
Abstraction involves representing essential features of an object while hiding the unnecessary details. It allows programmers to work with high-level concepts without worrying about implementation specifics.
Ex-
from abc import ABC, abstractmethod class Shape(ABC): def area(self): pass class Rectangle(Shape): def __init__(self, width, height): self.width = width self.height = height def area(self): return self.width * self.height class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return 3.14 * self.radius ** 2 my_rectangle = Rectangle(4, 5) my_circle = Circle(3) print(my_rectangle.area()) #Output: 20 print(my_circle.area()) #Output: 28.26
Question 26: Write a python program to checks if a sequence is a Palindrome or not.
sequence = input ("Enter a sequence = ") reversed_sequence = sequence[::-1] if sequence == reverse_sequence: print("Palindrome Sequence.") else: print("Not a Palindrome.")
Question 27: What is PIP ? Name some common PIP Command.
PIP (Python Package Installer) is the default package manager for Python. It is a command-line tool that allows you to easily install, manage, and uninstall Python packages from the Python Package Index (PyPI) or other package repositories.
Some Common PIP Command are:
- pip install package_name: Installs a Python package.
- pip uninstall package_name: Uninstalls a Python package.
- pip list: Lists all installed packages.
- pip freeze > requirements.txt: Exports a list of installed packages and their versions to a requirements.txt file.
- pip install -r requirements.txt: Installs packages listed in a requirements.txt file.
Question 28: Elaborate the concept of Dictionaries with the help of Example.
# Creating a dictionary student = { "name": "John Wick", "age": 28, "major": "Martial Arts and Self Defence.", "university": "Shaolin University" } # Accessing dictionary values print("Name:", student["name"]) print("Age:", student["age"]) print("Major:", student["major"]) print("University:", student["university"])
Question 29: What is docstring in Python?
Answer:
Docstring is a string literal used to document modules, classes, functions, and methods. It serves as a documentation tool to describe the purpose, behavior, parameters, return values, and other important details of the code.
A docstring is enclosed in triple quotes (single or double) and is typically placed as the first line after the definition of a module, class, function, or method. It can span multiple lines and supports both single-line and multi-line docstrings.
def hello(name): """ This function says hello to the person with the given name. Parameters: name (str): The name of the person to be greeted. Returns: str: A greeting message. """ return "Hello, " + name + " !!!!!" print(hello("Isabelle"))
Question 30: What are python namespaces ? What are their applications ?
Answer:
Namespace is a mapping from names (identifiers) to objects. It serves as a system to organize and provide a unique context for names in a Python program. Namespaces help prevent naming conflicts and provide a way to access objects in a structured manner.
Python uses namespaces to determine the scope of names. When you use a variable, function, or any other object, Python looks for that name within the available namespaces to resolve it.
Here are a few types of namespaces in Python:
- Built-in Namespace: It contains the names of built-in functions, exceptions, and objects that are available by default in Python. Examples include print(), len(), str, etc.
- Global Namespace: It refers to the names defined at the top level of a module or declared as global within a function. These names are accessible throughout the module or function.
- Local Namespace: It represents the names defined within a function. These names are accessible only within the function’s scope.
- Class Namespace: It contains the names defined within a class. These names are accessible within the class and can be accessed using the class name.
Python Libraries Interview Questions
Question 31: Write a program in Python to check if a number is prime.
a = int(input("Enter a number = ")) if a == 1: print("Not a prime number.") else: for x in range(2, a): if (a % x) == 0: print("Not a prime number.") break else: print("Prime Number.")
Question 32 : Python program to print following ‘*’ pattern:
*
**
***
****
*****
def pattern_print(rows): for i in range(1, rows + 1): print("*" * i) # Take input from the user rows = int(input("Enter the number of rows: ")) # Call the function to print the pattern pattern_print(rows)
Question 33 : Python program to print following ‘*’ pattern:
****
***
**
*
def pattern(rows): for i in range(rows, 0, -1): print("*" * i) # Take input from the user num_rows = int(input("Enter the number of rows: ")) # Call the function to print the pattern pattern(num_rows)
Question 34 : Write a python program to perform bubble sort for given array.
def bubble_sort(arr): # Bubble Sort Function n = len(arr) for i in range(n - 1): for j in range(n - i - 1): if arr[j] > arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], arr[j] numbers = input("Enter the List of numbers: ").split() numbers = [int(num) for num in numbers] bubble_sort(numbers) # Calling bubble sort function print("Sorted list:", numbers) # Sorted List
Question 35 : Write a python program to perform merge sort for given array.
def merge_sort(arr): # Merge Sort Function if len(arr) > 1: mid = len(arr) // 2 left_part = arr[:mid] right_part = arr[mid:] merge_sort(left_part) merge_sort(right_part) i = j = k = 0 while i < len(left_part) and j < len(right_part): if left_part[i] < right_part[j]: arr[k] = left_part[i] i += 1 else: arr[k] = right_part[j] j += 1 k += 1 while i < len(left_part): arr[k] = left_part[i] i += 1 k += 1 while j < len(right_part): arr[k] = right_part[j] j += 1 k += 1 numbers = input("Enter the List of numbers= ").split() numbers = [int(num) for num in numbers] merge_sort(numbers) print("Sorted list =", numbers)
Question 36 : Write a python program to perform merge sort for given array.
def merge_sort(arr): # Merge Sort Function if len(arr) > 1: mid = len(arr) // 2 left_part = arr[:mid] right_part = arr[mid:] merge_sort(left_part) merge_sort(right_part) i = j = k = 0 while i < len(left_part) and j < len(right_part): if left_part[i] < right_part[j]: arr[k] = left_part[i] i += 1 else: arr[k] = right_part[j] j += 1 k += 1 while i < len(left_part): arr[k] = left_part[i] i += 1 k += 1 while j < len(right_part): arr[k] = right_part[j] j += 1 k += 1 numbers = input("Enter the List of numbers= ").split() numbers = [int(num) for num in numbers] merge_sort(numbers) print("Sorted list =", numbers)
Question 37 : Write a python program to print Star (*) Triangle:
*
**
***
****
*****
def star_triangle(rows): for i in range(1, rows + 1): print(" " * (rows - i), end="") print("*" * (2*i - 1)) num_rows = int(input("Enter the number of ROWS: ")) star_triangle(num_rows)
Question 38: What is PythonPath ?
PYTHONPATH is an environment variable in Python that tells the interpreter where to look for Python modules and packages.
It is a list of directory paths separated by colons (on Unix-based systems) or semicolons (on Windows). When you import a module or package, Python searches for it in the directories listed in PYTHONPATH. It allows you to specify additional directories outside the default ones where your Python code resides, enabling easy access to custom modules or packages.
Question 39: What are Global and Local Variable ?
Global variables are declared outside any function or block and can be accessed from anywhere within the program. They have a global scope, meaning they are visible to all functions and blocks within the program.
Ex:
x = 10 def print_global(): print(x) print_global() # Output: 10
Local variables are declared within a function or block and can only be accessed within that specific function or block. They have a local scope, meaning they are visible and accessible only within their respective function or block.
Ex:
def print_local(): y = 20 print(y) print_local() # Output: 20
Question 40: Make a Binary search program in Python
def binary_search(arr, target): low = 0 high = len(arr) - 1 while low <= high: mid = (low + high) // 2 mid_value = arr[mid] if mid_value == target: return mid elif mid_value < target: low = mid + 1 else: high = mid - 1 return -1 elements = input("Enter a list of numbers = ").split() target = int(input("Enter the number to be searched = ")) arr = [int(element) for element in elements] arr.sort() print("Sorted List =",arr) index = binary_search(arr, target) if index != -1: print(f"{target} is at index {index}") else: print(f"{target} is not present in the list")
Python Interview Questions for Experienced
Question 41: Make a linear search program in python.
def linear_search(arr, target): for i in range(len(arr)): if arr[i] == target: return i return -1 elements = input("Enter the list of numbers = ").split() target = int(input("Enter the number to be searched = ")) arr = [int(element) for element in elements] arr = sorted(arr) print("Sorted Array = ",arr) index = linear_search(arr, target) if index != -1: print(f"{target} is at index {index}") else: print(f"{target} is not present in list")
Question 42: What is map() function ?
map() function in Python is a built-in function that allows you to apply a specified function to every item in one or more iterable objects, such as lists, tuples, or strings. It takes in two or more arguments: the function to be applied and the iterable(s) on which the function should operate.
Question 43: How does continue, break, and pass work?
Continue, break, and pass are three control flow statements in Python that allow you to change the flow of your program under certain conditions.
Continue statement: When continue is used inside a loop, it tells Python to skip the current iteration and move on to the next one. Any code after the continue statement within the loop for that iteration will be ignored, and the loop will continue with the next iteration.
Break statement: When break is used inside a loop, it tells Python to immediately exit the loop, regardless of any remaining iterations. Any code after the break statement within the loop will be skipped, and the program will continue executing from the next statement after the loop.
Pass statement: pass is used as a placeholder when you need to have a statement for syntactic reasons, but you don’t want to do anything in that part of the code. It doesn’t do anything and is mainly used to avoid syntax errors when you’re still working on implementing certain parts of your code.
Question 44: What are Classes and Objects ?
Class is a blueprint or a template that defines the structure and behavior of objects. It is like a blueprint for creating multiple instances of similar objects with shared characteristics and functionalities.
It contains data (in the form of attributes or properties) and behaviors (in the form of methods or functions) that define the objects’ characteristics and actions. It provides a way to organize related data and functions into a single unit.
An object, on the other hand, is an instance of a class. It represents a specific entity or item created based on the class definition. Objects have their own unique state and can interact with other objects or perform operations defined within the class.
Question 45: Write a python code to illustrate classes and object.
class assassin: def __init__(self, name, age): self.name = name self.age = age a1 = assassin("John Wick", 28) print(a1.name) print(a1.age)
Question 46: How to add values or remove values to a python array?
Adding values:
- append(): Adds an element to the end of the array.
- extend(): Appends multiple elements from an iterable to the end of the array.
- insert(): Inserts an element at a specific index within the array.
Removing values:
- remove(): Removes the first occurrence of a specific element from the array.
- pop(): Removes and returns an element at a specified index from the array.
- del statement: Deletes an element or a slice of elements from the array.
Question 47: Which python framework is best flask or django ?
Django provides a wide range of built-in features and components, reducing the need for external libraries or packages.
- Rapid development: Django’s high-level abstractions and conventions simplify the development process, allowing you to build applications quickly.
- Scalability: Django has proven to be scalable and has been used successfully in handling high-traffic websites and complex applications.
- Larger Community: Django has a large and active community, offering extensive documentation, tutorials, and reusable packages.
- Better Security Module: Django incorporates security features by default, including protection against common vulnerabilities.
Flask, on the other hand, is a lightweight micro-framework that offers more flexibility and customization options.
It is suitable for smaller projects, APIs, or situations where simplicity and control are desired. Flask allows developers to have more control over the architecture and components they use but lacks some of the built-in functionalities provided by Django.
Conclusion is that Django’s comprehensive feature set, strong community support, and emphasis on convention-over-configuration make it a preferred choice for many web development projects.
Question 48: What is multi threading and how it can be achieved ?
Multithreading is a programming technique that allows multiple threads of execution to run concurrently within a single process. A thread is a lightweight unit of execution within a program that can perform tasks independently.
Multithreading can be achieved in various programming languages, including Python, by utilizing the operating system’s threading capabilities or using libraries that provide threading functionality.
Here are the basic steps to achieve multithreading in Python:
- Import the threading module: In Python, multithreading is facilitated by the built-in threading module. Import the module to gain access to its classes and functions.
- Define a task or function: Create a function or task that you want each thread to execute concurrently. This function represents the work that will be performed by each thread.
- Create thread objects: Instantiate thread objects from the Thread class provided by the threading module. Specify the target function or task to be executed by each thread. You can also pass any required arguments to the target function.
- Start the threads: Call the start() method on each thread object to start the execution of the threads. Each thread will begin running concurrently.
Wait for thread completion: If needed, use the join() method on each thread to wait for its completion. This ensures that the main program doesn’t proceed until all threads have finished their execution.
Question 49: Write the python code to perform Write and Read operation in Python ?
# Open the file in write file = open("file.txt", "w") file.write("Hello Prepsters.\n") file.write("We will assist you in getting IT Job.\n") file.write("Here, You’ll learn various skills.") file.close() # Opening the file in read mode. file = open("file.txt", "r") contents = file.read() print(contents) # file.close() # Closing the file
Question 50: Write the python code to append operation in existing file ?
#Appending operation file = open("file.txt", "a") file.write("\nHello we are PrepInsta.") file.write("\nPrepInsta and PrepInsta Prime.") contents = file.read() print(contents) file.close()
FAQs related to Python Technical Interview
Question 1: What questions are asked in Technical Interview in Python Programming Language?
The common topics that are included in Python Technical Interview are:
- Basic Syntax
- DSA Based Coding
- File Handling
- Libraries
- Supported Frameworks
.etc.
Question 2: In an Interview how do we explain why we chose Python ?
Due to its clean, simple and small syntax with Wide variety Libraries Support makes Python easy – to – learn language. It is Dynamically Typed Languages which makes it more easier language to understand.
Question 3: What are some real life applications of Python ?
Python is widely used for the following fields:
- Web Scraping Applications.
- Data Science.
- Artificial Intelligence and Machine Learning.
- Game Development.
- Software Development
- Web Development, etc.
Question 4: What is __init__ function ?
`__init__` is a special method in Python classes known as the constructor. It is automatically called when an object of the class is created and is used to initialize the object’s attributes or state.
Question 5: Why is Python best for scripting?
Due to its Short and Simple Syntax, Python can we easily used for Scripting purpose.
30+ Companies are Hiring
Get Hiring Updates right in your inbox from PrepInsta
Login/Signup to comment