KEMBAR78
Cognizand GenC Python Cluster Mock Interview | PDF | Class (Computer Programming) | Inheritance (Object Oriented Programming)
0% found this document useful (0 votes)
23 views13 pages

Cognizand GenC Python Cluster Mock Interview

The document provides a comprehensive set of mock interview questions for the Cognizant Gen C Python role, categorized by difficulty levels: beginner, intermediate, and advanced. Each question includes a sample answer and keywords to highlight essential concepts. Topics covered include Python features, data types, object-oriented programming, exception handling, and more.

Uploaded by

venkat Mohan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views13 pages

Cognizand GenC Python Cluster Mock Interview

The document provides a comprehensive set of mock interview questions for the Cognizant Gen C Python role, categorized by difficulty levels: beginner, intermediate, and advanced. Each question includes a sample answer and keywords to highlight essential concepts. Topics covered include Python features, data types, object-oriented programming, exception handling, and more.

Uploaded by

venkat Mohan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Cognizant Gen C Python Mock Interview

Questions
Here is a comprehensive set of mock interview questions for the Cognizant Gen C Python role,
categorized by difficulty. Each question includes a sample answer and keywords to look for.

Beginner Level

1. What is Python?

Answer: Python is a high-level, interpreted programming language known for its simple syntax, which
promotes readability and reduces the cost of program maintenance. It supports multiple programming
paradigms, including procedural, object-oriented, and functional programming.

Keywords: High-level, interpreted, simple syntax, readability, multi-paradigm.

2. What are the key features of Python?

Answer: Key features of Python include its simple and easy-to-learn syntax, its interpreted nature,
cross-platform compatibility, extensive standard library, and support for multiple programming
paradigms like object-oriented and procedural programming.

Keywords: Easy to learn, interpreted, cross-platform, large standard library,


object-oriented, procedural.

3. What are keywords in Python? Give some examples.

Answer: Keywords in Python are reserved words that have special meanings and purposes and cannot
be used as variable or function names. Examples include if , else , for , while , def , class ,
import , True , False , and None .

Keywords: Reserved words, special meaning, cannot be used as identifiers.

4. What is the difference between a list and a tuple?

Answer: The primary difference is that lists are mutable, meaning their elements can be changed after
creation, while tuples are immutable, meaning they cannot be modified. Lists are defined with square
brackets [] , whereas tuples use parentheses () .

Page 1 of 13
Keywords: Mutable, immutable, square brackets, parentheses, changeable,
unchangeable.

5. How do you comment in Python?

Answer: Single-line comments in Python start with a hash symbol ( # ). For multi-line comments, you
can use triple quotes ( """ or ''' ) at the beginning and end of the block of text, although this is
technically a docstring.

Keywords: Hash symbol, single-line, triple quotes, multi-line, docstring.

6. What are variables in Python?

Answer: Variables are used to store data values. In Python, a variable is created the moment you first
assign a value to it. You don't need to declare the type of a variable explicitly.

Keywords: Store data, assign value, dynamically typed.

7. What are the different data types in Python?

Answer: Python has several built-in data types, including numeric types (int, float, complex), sequence
types (list, tuple, range), text type (str), mapping type (dict), set types (set, frozenset), and boolean type
(bool).

Keywords: Numeric, sequence, text, mapping, set, boolean.

8. How do you reverse a string in Python?

Answer: A common way to reverse a string in Python is to use slicing with a step of -1:
my_string[::-1] .

Keywords: Slicing, negative step, [::-1] .

9. What is the purpose of the len() function?

Answer: The len() function is used to get the number of items in an object. It can be used on
sequences like strings, lists, tuples, and dictionaries.

Keywords: Length, number of items, sequence.

10. What is type casting in Python?

Answer: Type casting is the process of converting a variable from one data type to another. This can be
done using functions like int() , float() , str() , etc.

Keywords: Convert data type, int() , float() , str() .

11. What are loops in Python?


Page 2 of 13
Answer: Loops are used to execute a block of code repeatedly. The two main types of loops in Python
are for loops and while loops.

Keywords: for loop, while loop, iteration, repetition.

12. Explain the break and continue statements.

Answer: The break statement is used to exit a loop prematurely. The continue statement skips
the rest of the code inside the current iteration of the loop and proceeds to the next iteration.

Keywords: break , continue , exit loop, skip iteration.

13. How do you define a function in Python?

Answer: You define a function in Python using the def keyword, followed by the function name,
parentheses for arguments, and a colon. The function body is indented.

Keywords: def keyword, function name, parameters, indented block.

14. What is a dictionary in Python?

Answer: A dictionary is a collection of key-value pairs. It is unordered, mutable, and indexed by keys.
Dictionaries are defined with curly braces {} .

Keywords: Key-value pairs, unordered, mutable, curly braces.

15. How do you access a value in a dictionary?

Answer: You can access a value in a dictionary by providing its key in square brackets, like
my_dict['key'] .

Keywords: Key, square brackets, indexing.

16. What is a set in Python?

Answer: A set is an unordered collection of unique elements. Sets are mutable and are defined with
curly braces {} or the set() function.

Keywords: Unordered, unique elements, mutable, curly braces.

17. How do you add an element to a list?

Answer: You can add an element to the end of a list using the append() method. To insert an element
at a specific position, you can use the insert() method.

Keywords: append() , insert() , add element.

Page 3 of 13
18. What is the difference between == and is ?

Answer: The == operator checks for equality of values, while the is operator checks if two variables
refer to the same object in memory.

Keywords: Value equality, object identity, memory location.

19. What are Python's string methods? Give examples.

Answer: Python strings have a rich set of built-in methods to perform common operations. Examples
include upper() , lower() , split() , strip() , and replace() .

Keywords: String manipulation, upper() , lower() , split() .

20. What is concatenation?

Answer: Concatenation is the process of combining two or more strings into a single string. In Python,
you can use the + operator for this.

Keywords: Combine strings, + operator.

21. How do you get user input in Python?

Answer: You can get user input using the input() function, which reads a line from the input,
converts it to a string, and returns it.

Keywords: input() function, user interaction.

22. What are modules in Python?

Answer: A module is a file containing Python code, such as function definitions, variables, and classes.
It allows you to logically organize your Python code.

Keywords: File, reusable code, import .

23. How do you import a module in Python?

Answer: You can import a module using the import statement followed by the module name, for
example, import math .

Keywords: import , module name.

24. What is the range() function?

Answer: The range() function generates a sequence of numbers. It is often used in for loops to
iterate a specific number of times.

Page 4 of 13
Keywords: Sequence of numbers, for loop, iteration.

25. What is slicing in Python?

Answer: Slicing is used to access a specific range of elements from a sequence like a list or a string.
The syntax is [start:stop:step] .

Keywords: Sub-sequence, range of elements, start, stop, step.

26. What does the pass statement do?

Answer: The pass statement is a null operation; nothing happens when it executes. It is used as a
placeholder in code where a statement is syntactically required but you have nothing to write.

Keywords: Placeholder, null operation, empty block.

27. What is a boolean data type?

Answer: The boolean data type represents one of two values: True or False . It is used to represent
truth values.

Keywords: True , False , logical values.

28. How do you check the data type of a variable?

Answer: You can use the type() function to check the data type of a variable.

Keywords: type() function, data type inspection.

29. What is the difference between an argument and a parameter?

Answer: A parameter is the variable listed inside the parentheses in the function definition. An
argument is the value that is sent to the function when it is called.

Keywords: Function definition, function call, variable, value.

30. What is exception handling in Python?

Answer: Exception handling is a mechanism to handle runtime errors or exceptional situations in a


program. In Python, you use try...except blocks for this.

Keywords: try , except , error handling, runtime errors.

Intermediate Level

1. What is Object-Oriented Programming (OOP)?

Page 5 of 13
Answer: Object-Oriented Programming is a programming paradigm based on the concept of "objects,"
which can contain data in the form of fields (attributes) and code in the form of procedures (methods).

Keywords: Objects, classes, attributes, methods, paradigm.

2. What are the main principles of OOP?

Answer: The four main principles of OOP are Encapsulation, Abstraction, Inheritance, and
Polymorphism.

Keywords: Encapsulation, Abstraction, Inheritance, Polymorphism.

3. What is a class and an object in Python?

Answer: A class is a blueprint for creating objects. An object is an instance of a class. The class defines
the attributes and methods that all objects of that class will have.

Keywords: Blueprint, instance, attributes, methods.

4. What is inheritance?

Answer: Inheritance is a mechanism in which one class acquires the properties (attributes and
methods) of another class. The class that inherits is the child class, and the class from which it inherits
is the parent class.

Keywords: Parent class, child class, code reusability, super() .

5. What is polymorphism?

Answer: Polymorphism allows objects of different classes to be treated as objects of a common


superclass. It enables a single interface to be used for a general class of actions. Method overriding is a
common example.

Keywords: Multiple forms, method overriding, duck typing.

6. What is encapsulation?

Answer: Encapsulation is the bundling of data (attributes) and methods that operate on the data into a
single unit, or class. It restricts direct access to some of an object's components.

Keywords: Data hiding, access modifiers (private, protected).

7. What is the difference between a shallow copy and a deep copy?

Answer: A shallow copy creates a new object but inserts references into it to the objects found in the
original. A deep copy creates a new object and recursively copies all objects found in the original.

Keywords: copy module, copy() , deepcopy() , reference, recursion.

Page 6 of 13
8. What are list comprehensions?

Answer: List comprehensions provide a concise way to create lists. They consist of brackets
containing an expression followed by a for clause, then zero or more for or if clauses.

Keywords: Concise, readable, for loop, if condition.

9. What is a lambda function?

Answer: A lambda function is a small anonymous function. It can take any number of arguments but can
only have one expression. They are defined using the lambda keyword.

Keywords: Anonymous function, lambda keyword, single expression.

10. What are decorators in Python?

Answer: Decorators are a design pattern in Python that allows a user to add new functionality to an
existing object without modifying its structure. Decorators are usually called before the definition of a
function you want to decorate.

Keywords: Metaprogramming, wrapper function, @ symbol.

11. What are generators in Python?

Answer: Generators are a simple way of creating iterators. A generator is a function that returns an
iterator object that we can iterate over (one value at a time). It uses the yield keyword.

Keywords: Iterator, yield keyword, memory efficient, lazy evaluation.

12. What is the difference between __init__ and __new__ ?

Answer: __new__ is the first step of instance creation. It's called first and is responsible for returning
a new instance of your class. __init__ is the initializer method; it takes the instance returned by
__new__ and initializes it.

Keywords: Instance creation, constructor, initializer.

13. What is the Global Interpreter Lock (GIL)?

Answer: The Global Interpreter Lock (GIL) is a mutex that protects access to Python objects, preventing
multiple threads from executing Python bytecode at the same time. This means that in CPython, only
one thread can be executing at any given time.

Keywords: Multithreading, thread-safe, CPython, concurrency vs. parallelism.

14. What are *args and **kwargs ?

Page 7 of 13
Answer: *args and **kwargs are used to pass a variable number of arguments to a function.
*args is used for non-keyworded variable-length arguments, while **kwargs is for keyworded
variable-length arguments.

Keywords: Variable-length arguments, positional arguments, keyword arguments.

15. What is the purpose of the if __name__ == "__main__" block?

Answer: This block of code will only be executed when the Python script is run directly, not when it is
imported as a module into another script. It's used to make code reusable and runnable.

Keywords: Script execution, module import, entry point.

16. How does Python's memory management work?

Answer: Python's memory management is handled by the Python Memory Manager, which uses a
private heap. It uses a combination of reference counting and a cyclic garbage collector.

Keywords: Private heap, reference counting, garbage collection.

17. What is context management and the with statement?

Answer: Context management allows for the setup and teardown of resources automatically. The
with statement is used to wrap the execution of a block of code within methods defined by a context
manager.

Keywords: with statement, __enter__ , __exit__ , resource management.

18. What are iterators and iterables?

Answer: An iterable is an object that can be looped over. An iterator is an object that represents a
stream of data; it returns the data one element at a time using the next() method.

Keywords: __iter__() , __next__() , for loop, lazy iteration.

19. What are abstract classes?

Answer: An abstract class is a class that cannot be instantiated. It is designed to be subclassed by


other classes that implement the abstract methods defined in it.

Keywords: abc module, @abstractmethod , cannot be instantiated.

20. How do you handle exceptions in Python?

Answer: Exceptions are handled using try...except blocks. The code that might raise an
exception is in the try block, and the handler is in the except block. finally and else clauses
can also be used.

Page 8 of 13
Keywords: try , except , finally , else , raise .

21. What is the difference between a module and a package?

Answer: A module is a single Python file, while a package is a collection of modules in a directory. A
package must contain an __init__.py file (which can be empty).

Keywords: File, directory, __init__.py .

22. What are Python namespaces?

Answer: A namespace is a mapping from names to objects, implemented as dictionaries. There are
different types: built-in, global, and local.

Keywords: Name-to-object mapping, scope, LEGB rule.

23. What is the super() function used for?

Answer: The super() function is used to call a method from a parent class. It is often used in the
__init__ method of a child class to call the parent's __init__ .

Keywords: Parent class, method overriding, inheritance.

24. How do you serialize and deserialize a Python object?

Answer: Serialization is converting a Python object into a byte stream, and deserialization is the
reverse. The pickle module is commonly used for this.

Keywords: pickle , dump() , load() , JSON.

25. What is monkey-patching in Python?

Answer: Monkey-patching refers to the dynamic modification of a class or module at runtime. This can
be used to add or change the behavior of existing code without altering the original source.

Keywords: Dynamic modification, runtime, patching.

26. What are metaclasses in Python?

Answer: A metaclass is a class whose instances are classes. Just as a class defines how an object
behaves, a metaclass defines how a class behaves.

Keywords: Class of a class, type .

27. What is the difference between static methods and class methods?

Answer: A class method takes the class as its first argument ( cls ), while a static method knows
nothing about the class and just deals with its parameters. Class methods are often used as factory

Page 9 of 13
functions.

Keywords: @classmethod , @staticmethod , cls , factory functions.

28. What are Python's built-in data structures?

Answer: Python's main built-in data structures are lists, tuples, dictionaries, and sets.

Keywords: List, tuple, dictionary, set.

29. What is the purpose of the yield keyword?

Answer: The yield keyword is used in generator functions. It pauses the function's execution and
saves the state, so it can be resumed later from the same point.

Keywords: Generator, pause, resume, iterator.

30. What are virtual environments in Python?

Answer: A virtual environment is a self-contained directory that contains a Python installation for a
particular version, plus additional packages. It allows you to work on multiple projects with different
dependencies without conflicts.

Keywords: venv , virtualenv , isolated environment, dependency management.

Advanced Level

1. Explain the inner workings of Python's for loop.

Answer: The for loop in Python works with iterators. When a for loop is used, Python calls
__iter__() on the iterable to get an iterator. Then, it repeatedly calls __next__() on the iterator
to get the next item until a StopIteration exception is raised.

Keywords: Iterator protocol, __iter__() , __next__() , StopIteration .

2. How does garbage collection work in Python?

Answer: Python primarily uses reference counting. Every object has a reference count, which is
changed when a reference is made or removed. When the count reaches zero, the object's memory is
deallocated. To handle reference cycles, Python also has a cyclic garbage collector.

Keywords: Reference counting, cyclic garbage collector, gc module.

3. What is the MRO (Method Resolution Order) in Python?

Page 10 of 13
Answer: The MRO is the order in which Python searches for a method in a class hierarchy in case of
multiple inheritance. Python uses the C3 linearization algorithm to determine the MRO.

Keywords: Multiple inheritance, C3 linearization, __mro__ .

4. Explain descriptors in Python.

Answer: Descriptors are Python objects that implement a __get__ , __set__ , or __delete__
method. They are used to control access to an attribute of an object. Properties are a common use of
descriptors.

Keywords: __get__ , __set__ , __delete__ , attribute access control.

5. How can you achieve true parallelism in Python?

Answer: Due to the Global Interpreter Lock (GIL), true parallelism with threads is not possible in
CPython for CPU-bound tasks. To achieve parallelism, you can use the multiprocessing module,
which spawns new processes, each with its own interpreter and memory, bypassing the GIL.

Keywords: multiprocessing module, processes, bypassing GIL.

6. What are coroutines in Python?

Answer: Coroutines are a more general form of subroutines. They are program components that
generalize subroutines for non-preemptive multitasking, by allowing execution to be suspended and
resumed. Python's async/await syntax is built upon coroutines.

Keywords: asyncio , async , await , cooperative multitasking.

7. How do you optimize Python code for performance?

Answer: Performance can be optimized by using efficient data structures, built-in functions, and
libraries like NumPy. Profiling the code to identify bottlenecks is crucial. For CPU-bound tasks, C
extensions or libraries like Cython can be used.

Keywords: Profiling, efficient algorithms, NumPy, Cython.

8. What are some new features in recent Python versions (e.g., 3.8, 3.9, 3.10)?

Answer: Python 3.8 introduced assignment expressions ( := ), 3.9 brought dictionary union operators
( | ), and 3.10 introduced structural pattern matching ( match...case ).

Keywords: Assignment expressions, dictionary union, pattern matching.

9. What is the difference between duck typing and strong typing?

Page 11 of 13
Answer: Python uses duck typing, which means an object's type is less important than the methods it
defines. If it acts like a duck, it's a duck. Strong typing means an object's type is enforced, and
operations on objects of the wrong type are not allowed.

Keywords: Duck typing, strong typing, dynamic typing.

10. How can you secure your Python application?

Answer: Security measures include validating user input to prevent injection attacks, using secure
libraries for sensitive operations, managing dependencies to avoid vulnerabilities, and following secure
coding practices.

Keywords: Input validation, dependency management, secure coding.

11. What is the difference between WSGI and ASGI?

Answer: WSGI (Web Server Gateway Interface) is the standard for synchronous Python web
applications, while ASGI (Asynchronous Server Gateway Interface) is the standard for asynchronous
applications. ASGI allows for long-lived connections, like WebSockets.

Keywords: WSGI, ASGI, synchronous, asynchronous, web servers.

12. Explain how multithreading and multiprocessing work in Python.

Answer: multithreading allows for concurrent execution within the same process, sharing
memory, and is suitable for I/O-bound tasks. multiprocessing creates separate processes with
their own memory, allowing for parallel execution on multiple CPUs, which is ideal for CPU-bound tasks.

Keywords: Concurrency, parallelism, I/O-bound, CPU-bound.

13. What are function annotations in Python?

Answer: Function annotations are a way of associating arbitrary metadata with function arguments and
return values. They are stored in the __annotations__ attribute of the function and are often used
for type hints.

Keywords: Type hints, metadata, __annotations__ .

14. What is the role of the __slots__ attribute in a class?

Answer: The __slots__ attribute allows you to explicitly declare data members and prevent the
creation of __dict__ for each instance. This can save memory for classes with many instances.

Keywords: Memory optimization, __dict__ .

15. How do you implement a singleton pattern in Python?

Page 12 of 13
Answer: A singleton pattern ensures that a class has only one instance. This can be implemented using
a decorator, a base class, or by overriding the __new__ method.

Keywords: Singleton, design pattern, single instance.

16. What is memoization?

Answer: Memoization is an optimization technique used to speed up programs by storing the results of
expensive function calls and returning the cached result when the same inputs occur again.

Keywords: Caching, performance optimization, dynamic programming.

17. What is the difference between a process and a thread?

Answer: A process is an instance of a program running with its own memory space. A thread is a unit of
execution within a process, and threads within the same process share the same memory space.

Keywords: Process, thread, memory space, execution context.

18. What are some common design patterns you have used in Python?

Answer: Candidates should discuss common design patterns like Singleton, Factory, Decorator, and
Observer, and provide examples of their implementation in Python.

Keywords: Design patterns, Singleton, Factory, Decorator, Observer.

19. How does Python handle integer overflow?

Answer: Python's standard integers have arbitrary precision, meaning they can grow to accommodate
any value. This effectively means that integer overflow is not an issue in Python as it is in fixed-size
integer types in other languages.

Keywords: Arbitrary precision integers, no overflow.

20. What is the purpose of sys.argv ?

Answer: sys.argv is a list in Python that contains the command-line arguments passed to a script.
sys.argv[0] is the script name itself.

Keywords: Command-line arguments, sys module.

Page 13 of 13

You might also like