Crack the Code: IT Interview Questions and Answers - Programming Language Institute

Programming practice questions and answer

Python Interview Questions for Freshers

 
1

Question- 1. What is Python? What are the benefits of using Python



Answer-

Python is a high-level, interpreted, general-purpose programming language. Being a general-purpose language, it can be used to build almost any type of application with the right tools/libraries. Additionally, python supports objects, modules, threads, exception-handling, and automatic memory management which help in modelling real-world problems and building applications to solve these problems.

Benefits of using Python:

  • Python is a general-purpose programming language that has a simple, easy-to-learn syntax that emphasizes readability and therefore reduces the cost of program maintenance. Moreover, the language is capable of scripting, is completely open-source, and supports third-party packages encouraging modularity and code reuse.
  • Its high-level data structures, combined with dynamic typing and dynamic binding, attract a huge community of developers for Rapid Application Development and deployment.

2

Question- 2. What is an Interpreted language?



Answer- An Interpreted language executes its statements line by line. Languages such as Python, Javascript, R, PHP, and Ruby are prime examples of Interpreted languages. Programs written in an interpreted language runs directly from the source code, with no intermediary compilation step.

3

Question- 3. What is Scope in Python?



Answer-

Every object in Python functions within a scope. A scope is a block of code where an object in Python remains relevant. Namespaces uniquely identify all the objects inside a program. However, these namespaces also have a scope defined for them where you could use their objects without any prefix. A few examples of scope created during code execution in Python are as follows:

  • local scope refers to the local objects available in the current function.
  • global scope refers to the objects available throughout the code execution since their inception.
  • module-level scope refers to the global objects of the current module accessible in the program.
  • An outermost scope refers to all the built-in names callable in the program. The objects in this scope are searched last to find the name referenced.

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

4

Question- 4.What are lists and tuples? What is the key difference between the two?



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

But what is the real difference between the two? The key difference between the two is that while lists are mutabletuples 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 errormy_list[0] = 'ansh' # modifying list => list modifiedprint(my_tuple[0]) # output => 'sara'print(my_list[0]) # output => 'ansh'

5

Question- 5. What is a dynamically typed language?



Answer-

Before we understand a dynamically typed language, we should learn about what typing is. Typing refers to type-checking in programming languages. In a strongly-typed language, such as Python, "1" + 2 will result in a type error since these languages don't allow for "type-coercion" (implicit conversion of data types). On the other hand, a weakly-typed language, such as Javascript, will simply output "12" as result.

Type-checking can be done at two stages -

  • Static - Data Types are checked before execution.
  • Dynamic - Data Types are checked during execution.

Python is an interpreted language, executes each statement line by line and thus type-checking is done on the fly, during execution. Hence, Python is a Dynamically Typed Language.

6

Question- 6. What are the common built-in data types in Python?



Answer- There are several built-in data types in Python. Although, Python doesn't require data types to be defined explicitly during variable declarations type errors are likely to occur if the knowledge of data types and their compatibility with each other are neglected. 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:
    None keyword represents the null values in Python. Boolean equality operation can be performed using these NoneType objects.
Class NameDescription
NoneType Represents the NULL values in Python.
  • Numeric Types:
    There are three distinct numeric types - integers, floating-point numbers, and complex numbers. Additionally, booleans are a sub-type of integers.
Class NameDescription
int Stores integer literals including hex, octal and binary numbers as integers
float Stores literals containing decimal values and/or exponent signs as floating-point numbers
complex Stores complex numbers in the form (A + Bj) and has attributes: real and imag
bool Stores boolean value (True or False).

Note: The standard library also includes fractions to store rational numbers and decimal to store floating-point numbers with user-defined precision.

  • Sequence Types:
    According to Python Docs, there are three basic Sequence Types - lists, tuples, and range objects. Sequence types have the in and not in operators defined for their traversing their elements. These operators share the same priority as the comparison operations.
Class NameDescription
list Mutable sequence used to store collection of items.
tuple Immutable sequence used to store collection of items.
range Represents an immutable sequence of numbers generated during execution.
str Immutable sequence of Unicode code points to store textual data.

Note: The standard library also includes additional types for processing:
1.
 Binary data such as bytearray bytes memoryview , and
2.
 Text strings such as str.

  • Mapping Types:

A mapping object can map hashable values to random objects in Python. Mappings objects are mutable and there is currently only one standard mapping type, the dictionary.

Class Name Description
dict Stores comma-separated list of key: value pairs
  • Set Types:
    Currently, Python has two built-in set types - set and frozensetset type is mutable and supports methods like add() and remove()frozenset type is immutable and can't be modified after creation.
Class NameDescription
set Mutable unordered collection of distinct hashable objects.
frozenset Immutable collection of distinct hashable objects.

Note: set is mutable and thus cannot be used as key for a dictionary. On the other hand, frozenset is immutable and thus, hashable, and can be used as a dictionary key or as an element of another set.

  • Modules:
    Module is an additional built-in type supported by the Python Interpreter. It supports one special operation, i.e., attribute accessmymod.myobj, where mymod is a module and myobj references a name defined in m's symbol table. The module's symbol table resides in a very special attribute of the module __dict__, but direct assignment to this module is neither possible nor recommended.
  • Callable Types:
    Callable types are the types to which function call can be applied. They can be user-defined functions, instance methods, generator functions, and some other built-in functions, methods and classes.
    Refer to the documentation at 
    docs.python.org for a detailed view of the callable types.

7

Question- What is pass in Python?



Answer-

The pass keyword represents a null operation in Python. It is generally used for the purpose of filling up empty blocks of code which may execute during runtime but has yet to be written. Without the pass statement in the following code, we may run into some errors during code execution.

def myEmptyFunc(): # do nothing passmyEmptyFunc() # nothing happens

8

Question- What are modules and packages in Python?



Answer-

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

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


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

Packages allow for hierarchial structuring of the module namespace using dot notation. As, modules help avoid clashes between global variable names, in a similar manner, packages help avoid clashes between module names.
Creating a package is easy since it makes use of the system's inherent file structure. So just stuff the modules into a folder and there you have it, the folder name as the package name. Importing a module or its contents from this package requires the package name as prefix to the module name joined by a dot.

9

Question- What are global, protected and private attributes in Python?



Answer-

  • Global variables are public variables that are defined in the global scope. To use the variable in the global scope inside a function, we use the global keyword.
  • Protected attributes are attributes defined with an underscore prefixed to their identifier eg. _sara. They can still be accessed and modified from outside the class they are defined in but a responsible developer should refrain from doing so.
  • Private attributes are attributes with double underscore prefixed to their identifier eg. __ansh. They cannot be accessed or modified from the outside directly and will result in an AttributeError if such an attempt is made.
  • 10

    Question- What is the use of self in Python?



    Answer-

    Self is used to represent the instance of the class. With this keyword, you can access the attributes and methods of the class in python. It binds the attributes with the given arguments. self is used in different places and often thought to be a keyword.

    11

    Question- Top 36 Python interview Question for fresher



    Answer-

    Here’s a list of 50 common Python interview questions along with their answers for freshers:

    1. What is Python?

      • Python is a high-level, interpreted programming language known for its readability and simplicity. It supports multiple programming paradigms, including procedural, object-oriented, and functional programming.
    2. How is Python different from other programming languages?

      • Python emphasizes code readability and simplicity, using indentation to define code blocks. It is dynamically typed and has a large standard library, which makes it versatile for various applications.
    3. What are Python's key features?

      • Key features include:
        • Easy-to-read syntax
        • Interpreted language
        • Dynamically typed
        • High-level data structures
        • Object-oriented
        • Extensive standard library
    4. What is PEP 8 and why is it important?

      • PEP 8 is the Python Enhancement Proposal that provides guidelines and best practices for writing Python code. It promotes code consistency and readability.
    5. How do you install Python and set up a development environment?

      • You can install Python from the official website (python.org) and use package managers like pip to install additional libraries. Development environments can be set up using IDEs like PyCharm, VSCode, or Jupyter Notebook.
    6. Explain the difference between a list and a tuple.

      • Lists are mutable, meaning their elements can be changed after creation. Tuples are immutable, so their elements cannot be altered once they are defined.
    7. How do you handle errors in Python?

      • Errors in Python are handled using exception handling. You can use try, except, else, and finally blocks to catch and manage exceptions.
    8. What are Python's built-in data types?

      • Built-in data types include integers, floating-point numbers, strings, lists, tuples, sets, and dictionaries.
    9. How do you create a function in Python?

      • Functions are created using the def keyword, followed by the function name and parameters. Example:
        python

        def my_function(param1, param2): return param1 + param2
    10. What is the difference between append() and extend() methods in lists?

      • append() adds a single element to the end of a list, while extend() adds elements from an iterable (like another list) to the end of the list.
    11. How does Python handle memory management?

      • Python uses automatic memory management with a built-in garbage collector that reclaims memory from objects no longer in use.
    12. What are Python decorators and how are they used?

      • Decorators are functions that modify the behavior of other functions or methods. They are applied using the @decorator_name syntax above the function definition.
    13. What is a lambda function?

      • A lambda function is a small anonymous function defined with the lambda keyword. It can have any number of arguments but only one expression. Example:
        python

        add = lambda x, y: x + y
    14. How do you use list comprehensions?

      • List comprehensions provide a concise way to create lists. Example:
        python

        squares = [x**2 for x in range(10)]
    15. What is the difference between == and is in Python?

      • == checks for value equality, while is checks for object identity (i.e., whether two references point to the same object in memory).
    16. How do you handle exceptions using try, except, finally?

      • Use try to execute code that might raise an exception, except to catch and handle the exception, and finally to execute code that should run regardless of whether an exception occurred. Example:
        python

        try: result = 10 / 0except ZeroDivisionError: print("Cannot divide by zero")finally: print("Execution completed")
    17. What is the purpose of self in a class?

      • self refers to the instance of the class and is used to access instance variables and methods within class definitions.
    18. Explain the concept of inheritance in Python.

      • Inheritance allows a class (child class) to inherit attributes and methods from another class (parent class), promoting code reuse and a hierarchical class structure.
    19. What are modules and packages in Python?

      • A module is a single file containing Python code, while a package is a collection of modules organized in directories. Packages include an __init__.py file.
    20. How do you create and use virtual environments?

      • Use venv or virtualenv to create isolated environments for projects. Example:
        bash

        python -m venv myenvsource myenv/bin/activate # On Windows, use `myenv\Scripts\activate`
    21. What is the use of the with statement?

      • The with statement simplifies exception handling by encapsulating common preparation and cleanup tasks. It is often used with file operations to ensure proper resource management. Example:
        python

        with open('file.txt', 'r') as file: content = file.read()
    22. Explain the concept of generators and how they differ from iterators.

      • Generators are a type of iterator created using functions with yield statements. They produce values on-the-fly and are more memory-efficient than creating large lists.
    23. What is the purpose of the yield keyword?

      • The yield keyword is used in a generator function to return a value and pause the function’s execution, allowing it to resume from where it left off.
    24. How do you read and write files in Python?

      • Use the open() function with modes 'r' for reading and 'w' for writing. Example:
        python

        with open('file.txt', 'w') as file: file.write('Hello, world!')
    25. What is the difference between deep copy and shallow copy?

      • A shallow copy creates a new object but does not recursively copy nested objects. A deep copy creates a new object and recursively copies all nested objects.
    26. How do you handle command-line arguments in Python?

      • Use the sys.argv list or the argparse module to handle command-line arguments. Example with argparse:
        python

        import argparseparser = argparse.ArgumentParser()parser.add_argument('name')args = parser.parse_args()print(args.name)
    27. What are regular expressions and how are they used in Python?

      • Regular expressions are patterns used to match strings. They are handled using the re module. Example:
        python

        import repattern = r'\d+'matches = re.findall(pattern, 'There are 123 apples and 456 oranges.')
    28. What are the built-in functions in Python?

      • Some built-in functions include print(), len(), type(), range(), max(), and sum().
    29. How do you perform unit testing in Python?

      • Use the unittest module to create test cases and run them. Example:
        python

        import unittestclass TestMath(unittest.TestCase): def test_add(self): self.assertEqual(1 + 1, 2)if __name__ == '__main__': unittest.main()
    30. Explain the difference between pop() and remove() methods in lists.

      • pop() removes and returns an element by index, while remove() removes the first occurrence of a value.
    31. What is a dict in Python and how is it used?

      • A dict (dictionary) is a collection of key-value pairs. Example:
        python

        my_dict = {'name': 'Alice', 'age': 25}
    32. How do you manage dependencies in a Python project?

      • Use requirements.txt files or pipenv to manage dependencies. Example with requirements.txt:
        bash

        pip freeze > requirements.txtpip install -r requirements.txt
    33. What are Python’s standard libraries and how do you use them?

      • Standard libraries include os, sys, math, and datetime. They provide modules and functions for various tasks. Example:
        python

        import mathprint(math.sqrt(16))
    34. How do you debug a Python program?

      • Use the built-in pdb module or debugging tools in IDEs. Example with pdb:
        python

        import pdbpdb.set_trace()
    35. Explain the concept of context managers.

      • Context managers handle resource management using the with statement. They ensure that resources are properly cleaned up after use, even if an error occurs.
    36. How does Python support multi-threading and multiprocessing?

      • Multi-threading is supported via the threading module, and multiprocessing is supported via the multiprocessing module, allowing concurrent execution of code.