Python_Interview_Questions

Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

Core Python

1. Question: Can you explain important features of Python? Answer: Python features: Easy to
read, versatile, dynamically typed, object-oriented, and supports modules and exceptions.
2. Question: What is a frozen binary? Answer: Frozen binary: A self-contained, executable file
with all dependencies bundled, ensuring consistent execution.
3. Question: What is the role of PVM? Answer: PVM role: Python Virtual Machine interprets
and executes Python code, making it platform-independent.
4. Question: What is garbage collector? Answer: Garbage collector: Automatically deallocates
memory occupied by objects no longer in use, ensuring efficient memory usage.
5. Question: Why Python is called interpreted language? Answer: Python's interpreted: Code is
executed line by line, translating to machine code at runtime without compilation.
6. Question: Why variables are not declared in Python? Answer: Variables in Python:
Dynamically typed, their types are inferred during runtime, eliminating the need for explicit
declaration.
7. Question: How can you know the datatype of a variable? Answer: Check variable datatype:
Use the type(variable) function to determine the datatype of a variable.
8. Question: What is the difference between C and Python? Answer: C vs Python: C is
compiled, low-level, and statically typed; Python is interpreted, high-level, and dynamically
typed.
9. Question: What is the difference between Java and Python? Answer: Java vs Python: Java is
statically typed, compiled, and emphasizes strong typing; Python is dynamically typed,
interpreted, and more concise.
10. Question: What is a sequence? Answer: Sequence: Ordered collection of elements, like lists,
tuples, or strings, accessible by index.
11. Question: What are various datatypes in Python? Answer: Python datatypes: Include int,
float, str, list, tuple, dict, set, bool, etc.
12. Question: What is the difference between list and tuple? Answer: List vs Tuple: Lists are
mutable, dynamic arrays; tuples are immutable, fixed-size sequences.
13. Question: What is the difference between bytes and bytearray? Answer: Bytes vs Bytearray:
Bytes are immutable sequences of integers; bytearray is mutable, allowing modifications.
14. Question: What is the difference between set and frozenset? Answer: Set vs Frozenset: Sets
are mutable, unordered collections; frozensets are immutable sets, hashable and suitable as
dictionary keys.
15. Question: What is indexing? Answer: Indexing: Accessing elements in a sequence using their
position, starting from 0.
16. Question: What is the difference between list and array? Answer: List vs Array: Lists can
contain mixed datatypes; arrays hold elements of the same type, more memory efficient.
17. Question: Explain about slicing? How can you do reverse slicing? Answer: Slicing: Extracting
portions of a sequence; reverse slicing uses negative indices.
18. Question: Explain about assert statement? Answer: Assert statement: Raises an exception if
a specified condition is False, aiding in debugging.
19. Question: What is a function? What is its use? Answer: Function: A reusable block of code;
used for modularity, improving code readability, and ease of debugging.
20. Question: What is the difference between local and global variable? Answer: Local vs Global
variable: Local variables are confined to the function where they are declared; global
variables are accessible throughout the program.
21. Question: What are mutable objects and immutable objects? Answer: Mutable vs
Immutable objects: Mutable objects (lists, dictionaries) can be modified after creation;
immutable objects (tuples, strings) cannot be changed.
22. Question: Why strings are created as immutable objects? Answer: Immutable strings:
Ensures data integrity, prevents unintended modifications.
23. Question: What are keyword arguments? How they are used? Answer: Keyword arguments:
Passed with key-value pairs, allowing flexible function invocation.
24. Question: What is the use of a star ‘*’ before an argument in the function? Answer: Star ‘*’ in
function: Allows variable number/variable length of non-keyword arguments to be passed.
25. Question: What is a decorator? Can you give examples for already available decorators in
python? Answer: Decorator: Modifies functions or classes at the time of definition; examples
include @staticmethod, @classmethod.
26. Question: What is a lambda? What is its advantage? Answer: Lambda: Anonymous function
for short, simple operations; concise syntax.
27. Question: What is the difference between normal function and lambda? Answer: Normal
function vs Lambda: Lambdas are small, unnamed, and limited to one expression; normal
functions can be more complex.
28. Question: What is the difference between package and module? Answer: Package vs
Module: Module is a single file containing Python definitions; package is a collection of
modules.
29. Question: Explain the ways of importing a module in Python? Answer: Importing modules:
Use import module_name or from module_name import function_name.
30. Question: What is the use of arange() ? Answer: arange(): Creates an array with specified
range and step values.
31. Question: How can you know the number of elements in an array? Answer: Number of
elements: Use len(array) to find the number of elements in an array.
32. Question: What is the difference between reshape() and flatten() ? Answer: reshape() vs
flatten(): Reshape changes array dimensions; flatten() returns a 1D copy of an array.
33. Question: In numpy, all arrays are internally objects of which class? Answer: Numpy arrays:
Internally, all arrays are objects of the class 'numpy.ndarray'.
34. Question: Which methods are used to find matrix transpose? (HINT: transpose(), T) Answer:
Matrix transpose: Achieved using transpose() or .T attribute in Numpy arrays.
35. Question: What is list comprehension? What is its advantage? Answer: List comprehension:
Concise way to create lists; reduces the need for traditional loops, enhancing readability.
36. Question: What is the difference between script and program? Will Python come under
script or program? Answer: Script vs Program: Scripts are small, single-purpose, whereas
programs are larger, multifunctional; Python can be used for both scripts and programs.
Advanced Python.

1. Question: How can you create a class and object to it, explain.
Answer: To create a class in Python, use the class keyword. Define methods within the class. To
create an object, instantiate the class with object_name = ClassName().

2. Question: What is the use of self variable?


Answer: self in Python refers to the instance of the class. It allows access to instance variables
and methods. It must be the first parameter in class methods.

3. Question: What is the difference between default constructor and parameterized constructor?
Answer: Default constructor has no parameters; it's automatically invoked when an object is
created. Parameterized constructor accepts parameters and initializes instance variables with
the given values.

4. Question: When is a constructor called?


Answer: The constructor is called when an object of the class is created, initializing the object's
attributes and performing necessary setup.

5. Question: What is the difference between instance variable and class variable?
Answer: Instance variables are specific to each instance of a class, while class variables are
shared by all instances of the class. Class variables are defined outside any method in the class.

6. Question: What is the difference between class methods and static methods?
Answer: Class methods take cls as the first parameter and can access and modify class state.
Static methods don't depend on class or instance state; they're defined using the @staticmethod
decorator.

7. Question: What is name mangling?


Answer: Name mangling is a technique in Python where names of variables that start with
double underscores are changed to avoid conflicts between different classes. It's used to make
the variables private to the class.
8. Question: What are dunders / double underscores / magic methods in Python?

Answer: Dunders (short for "double underscores") or magic methods are special methods in Python with
double underscores at the beginning and end of their names (e.g., __init__, __str__). They enable
customization of behavior for built-in operations.

9. Question: Can you inherit a class from another class? How?

Answer: Yes, inheritance in Python is achieved by placing the parent class name in parentheses after the
child class name during class definition. For example: class ChildClass(ParentClass):.

10. Question: What is duck typing?


Answer: Duck typing is a programming concept in which the type or the class of an object is less
important than the methods and properties it defines. If an object walks like a duck and quacks
like a duck, it's treated as a duck, regardless of its actual type.

*Duck Typing refers to the principle of not constraining or binding the code to specific data
types.*

11. Question: What is the procedure of creating an abstract class?


Answer: To create an abstract class in Python, import the ABC module from the abc package,
define the class with methods marked as abstract using the @abstractmethod decorator.
Abstract methods have no implementation in the abstract class.

12. Question: What is the difference between an abstract class and an interface?
Answer: Abstract class can have abstract and concrete methods; an interface can only have
abstract methods. Python doesn't have interfaces. Abstract classes are created using the ABC
module, while interfaces are not explicitly defined.

13. Question: How can you override a method?


Answer: To override a method in Python, define a method with the same name and parameters
in the child class. This method will override the method with the same name in the parent class.

14. Question: All exceptions are subclasses of which class?


Answer: All exceptions in Python are subclasses of the BaseException class.

15. Question: What is a regular expression?


Answer: A regular expression is a sequence of characters defining a search pattern. It can be
used for pattern matching within strings.

16. Question: What is the difference between search() and findall()?


Answer: search() finds the first occurrence of a pattern in a string and returns a match object.
findall() finds all occurrences of a pattern in a string and returns them as a list.

17. Question: What is the use of ^, $, *, +, ?, \d, and \w in regular expressions?


Answer:
^ matches the start of a string.
$ matches the end of a string.

* matches zero or more occurrences.

+ matches one or more occurrences.


? matches zero or one occurrence.
\d matches any digit (0-9).
\w matches any alphanumeric character and underscore.

18. Question: How can you display system date and time?
Answer: Use the datetime module in Python to display the system date and time. For example:
import datetime and then print(datetime.datetime.now()).

19. Question: What is the difference between Series and DataFrame?


Answer: Series is a one-dimensional labeled array, while DataFrame is a two-dimensional labeled
data structure with columns that can be of different types.

20. Question: What is the difference between iloc() and loc()?


Answer: iloc[] is used for integer-location based indexing, while loc[] is label-based indexing.

21. Question: How can you create a DataFrame from a .csv file and excel files?
Answer: Use the pandas library. For .csv: df = pd.read_csv('filename.csv'). For Excel: df =
pd.read_excel('filename.xlsx').

22. Question: When the DataFrame in the memory is modified, will it modify the data in the original
file from where the DataFrame is created?
Answer: No, modifications to a DataFrame in memory do not change the original file.

23. Question: How can you view the first 5 rows and last 5 rows in a DataFrame?
Answer: Use df.head() to view the first 5 rows and df.tail() to view the last 5 rows of a
DataFrame.

24. Question: How can you sort the rows of a DataFrame into ascending order?
Answer: Use df.sort_values(by='column_name') to sort the DataFrame by a specific column in
ascending order.

25. Question: How can you remove NaN values found in the data?
Answer: Use df.dropna() to remove rows containing NaN values from the DataFrame.

26. Question: What does the attribute 'inplace=True' do in a DataFrame?


Answer: When inplace=True is set, the modifications are made directly to the DataFrame and do
not need to be assigned back to a variable.

27. Question: Why do we use matplotlib?


Answer: Matplotlib is a popular data visualization library in Python used for creating static,
interactive, and animated plots and charts.

28. Question: With what packages have you worked in Python? (Hint: numpy, re, tkinter, threading,
socket, pandas, matplotlib, etc)
Answer: I have worked with various Python packages, including numpy, re, pandas, matplotlib,
and more.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy