Top Python Interview Questions For Freshers

Introduction:

Top Python Interview Questions For Freshers

Top Python Interview Questions For Freshers

1. What is Python? Why is it used?

Python is a high-level, interpreted programming language that was createdE by Guido van Rossum and first released in 1991. It emphasizes code readability and has a clean syntax that makes it easy to understand and write.

Python is used for a wide range of applications, including web development, data analysis, artificial intelligence, scientific computing, automation, and more.

2. What are the key features of Python?

Here are some of the key features of Python:

Easy to learn and use: Python has a simple, easy-to-learn syntax that makes it a great language for beginners.
Powerful: Python is a powerful language that can be used to create a wide variety of applications.
Versatile: Python can be used for a variety of tasks, including web development, data science, and machine learning.
Portable: Python is a portable language that can be used on a variety of platforms.
Free and open source: Python is a free and open source language, which means that it is available to everyone.

2.What are the different data types in Python?

Python supports several built-in data types, which are used to represent different kinds of values. Here are the commonly used data types in Python:

  1. Numeric Types:
  • int: Represents integers, e.g., 10, -5, 0.
  • float: Represents floating-point numbers, e.g., 3.14, -2.5, 0.0.
  • complex: Represents complex numbers in the form of a + bj, where a and b are floats or integers, and j is the imaginary unit.
  1. Sequence Types:
  • str: Represents a sequence of characters enclosed in single quotes (‘ ‘) or double quotes (” “), e.g., “Hello, World!”.
  • list: Represents an ordered collection of items enclosed in square brackets [ ], e.g., [1, 2, 3].
  • tuple: Represents an ordered collection of items enclosed in parentheses ( ), e.g., (1, 2, 3).

3.Mapping Type:

  • dict: Represents a collection of key-value pairs enclosed in curly braces { }, e.g., {‘name’: ‘John’, ‘age’: 25}.

4. Set Types:

  • set: Represents an unordered collection of unique elements enclosed in curly braces { }, e.g., {1, 2, 3}.
  • frozenset: Represents an immutable version of set, i.e., elements cannot be added or removed once defined.

5. Boolean Type:

  • bool: Represents a boolean value, which can be either True or False.

6. None Type:

  • None: Represents a special type that indicates the absence of a value or a null value.

These are the fundamental data types in Python. Additionally, Python also allows users to define their own custom data types using classes and objects, making it an object-oriented programming language.

4. How do you comment out code in Python?

Single-line comment: To comment out a single line of code, prepend the line with a hash symbol (#).

For example:
# This is a single-line comment
print("Hello, World!") # This line will be ignored
Multi-line comment: To comment out multiple lines of code, enclose the lines in triple quotes (""" or ''').
For example:
"""
This is a multi-line comment.
It spans across multiple lines.
"""

5. Explain the concept of Python decorators.

 A Python decorator is a function that takes another function as an argument and returns a modified version of it. The decorator can add functionality to the original function, such as logging, timing, or error handling.

Decorators are a powerful way to add functionality to your code without having to modify the original function. They are often used to improve the performance, security, or readability of your code.

Here is an example of a simple decorator that logs the execution time of a function:

def decorator_function(original_function):

def decorator_function(original_function):

    def wrapper_function():
        print 'Before the original function is called'
        original_function()
        print 'After the original function is called'

    return wrapper_function


@decorator_function
def greet():
    print 'Hello, world!'
def decorator_function(original_function):

    def wrapper_function():
        print 'Before the original function is called'
        original_function()
        print 'After the original function is called'

    return wrapper_function


@decorator_function
def greet():
    print 'Hello, world!'
greet()

6. How do you handle exceptions in Python?

In Python, exceptions are errors or exceptional events that occur during the execution of a program. 

Here’s how you can handle exceptions in Python:

Try-Except Block: The most common way to handle exceptions is by using a try-except block. The code that may raise an exception is placed inside the try block, and the code to handle the exception is placed inside the except block. Here’s the basic syntax:

try:
# Code that may raise an exception
except ExceptionType:
# Code to handle the exception
try:
x = 10 / 0
except ZeroDivisionError:
print("Error: Division by zero")
Multiple Except Blocks: You can use multiple except blocks to handle different types of exceptions separately. This allows you to handle specific exceptions differently based on your requirements. Here's an example:
try:
# Code that may raise an exception
except ExceptionType1:
# Code to handle ExceptionType1
except ExceptionType2:
# Code to handle ExceptionType2
Example
try:
x = int("abc")
except ValueError:
print("Error: Invalid integer value")
except TypeError:
print("Error: Invalid data type")
Finally Block: You can optionally include a finally block after the except block(s). The code inside the finally block is executed regardless of whether an exception occurred or not. It is commonly used to perform cleanup actions, such as closing files or releasing resources. Here's an example:
try:
# Code that may raise an exception
except ExceptionType:
# Code to handle the exception
finally:
# Code that always executes
try:
file = open("data.txt", "r")
# Perform some operations on the file
except FileNotFoundError:
print("Error: File not found")
finally:
if file:
file.close()

7. What is the purpose of the init method in Python classes?

Ans: The init method is a special method in Python classes that is automatically called when an object of the class is created. It is also known as the constructor method. The primary purpose of the init method is to initialize the attributes (or properties) of an object with the values provided during the object creation.

Here’s the basic syntax of the init method:

class ClassName:

def __init__(self, arg1, arg2, ...):

        # Initialization code

        self.attribute1 = arg1

        self.attribute2 = arg2

        ...

Example :

class Person:

    def __init__(self, name, age):

        self.name = name

        self.age = age

     def say_hello(self):

        print ('Hello, my name is', self.name, 'and I am', self.age,

               'years old.')

# Creating objects of the Person class

person1 = Person('Alice', 25)

person2 = Person('Bob', 30)

# Accessing object attributes

print person1.name  # Output: Alice

print person2.age  # Output: 30

# Calling object methods

person1.say_hello()  # Output: Hello, my name is Alice and I am 25 years old.

person2.say_hello()  # Output: Hello, my name is Bob and I am 30 years old.

8. Explain the difference between a shallow copy and a deep copy.

Feature Shallow Copy Deep Copy
Definition Creates a new object that references the same underlying objects as the original object. Creates a new object that contains independent copies of the objects referenced by the original object.
Speed Faster than a deep copy. Slower than a shallow copy.
Memory usage Uses less memory than a deep copy. Uses more memory than a shallow copy.
Appropriateness Appropriate for objects that do not contain any nested objects. Appropriate for objects that contain nested objects.

9. What is the difference between a tuple and a list in Python?

here is a table that summarizes the differences between tuples and lists in Python:

Feature Tuple List
Data structure Immutable sequence Mutable sequence
Delimiter Parentheses () Square brackets []
Size Fixed Variable
Speed Faster Slower
Memory usage Less More
Use cases Constants, keys in dictionaries, return values from functions Dynamic data structures, sorting, searching, iteration

10. How do you open and read a file in Python?

Ans: To open and read a file in Python, you can use the open() function. The open() function takes two arguments: the name of the file to open and the mode in which to open the file. The mode can be one of the following:

r: Read-only mode. This is the default mode.
w: Write-only mode. The file will be created if it does not exist, or truncated if it does exist.
a: Append-only mode. The file will be created if it does not exist, or the existing file will be appended to.

Once you have opened the file, you can use the read() method to read the contents of the file. The read() method takes an optional argument that specifies the number of bytes to read. If no argument is specified, the entire file will be read.

For example, the following code will open a file named myfile.txt in read-only mode and print the contents of the file:

file = open(‘myfile.txt’, ‘r’)

Use the read() method to read the contents of the file. It reads the entire file as a string.

content = file.read()

Close the file using the close() method to free up system resources.

file.close()

python

Leave a Comment

Your email address will not be published. Required fields are marked *