Thank you for reading this post, don't forget to subscribe!

1. What is Python?

Python is a high-level, interpreted, general-purpose programming language known for its readability, simplicity, and versatility. It supports multiple programming paradigms including procedural, object-oriented, and functional programming.


2. List some key features of Python.

  • Easy to Learn and Use: Simple syntax similar to English.

  • Interpreted Language: No need for compilation; runs line by line.

  • Dynamically Typed: No need to declare variable types.

  • Extensive Standard Library: Includes modules for file I/O, regular expressions, etc.

  • Cross-platform: Runs on Windows, Linux, MacOS, etc.

  • Open-source: Freely available for modification and distribution.

  • Supports OOP: Object-oriented programming is supported.

  • Garbage Collection: Automatic memory management.

  • Integration: Can integrate with C/C++, Java, and .NET.


3. What are Python’s data types?

  • Numeric: int, float, complex

  • Text: str

  • Sequence: list, tuple, range

  • Set: set, frozenset

  • Mapping: dict

  • Boolean: bool

  • Binary: bytes, bytearray, memoryview

  • None: NoneType


4. What is a variable in Python?

A variable is a container for storing data values. It is created the moment you assign a value to it.


5. How do you declare a variable?

x = 10
name = "Alice"

You just assign a value; no need to declare the type explicitly.


6. What is dynamic typing?

In Python, variables do not have a fixed type. You can assign an integer to a variable, and later assign a string to the same variable.

x = 5       # x is an int
x = "five"  # x is now a str

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

Feature List Tuple
Mutability Mutable (can change) Immutable (cannot change)
Syntax [] ()
Performance Slower Faster
Use case Dynamic data Fixed data

8. What is a set in Python?

A set is an unordered collection of unique elements.

s = {1, 2, 3, 3}
print(s)  # Output: {1, 2, 3}

9. How is a dictionary different from a list?

  • List: Ordered collection of values.

    [10, 20, 30]
    
  • Dictionary: Key-value pairs, unordered.

    {"name": "Alice", "age": 25}
    

10. What are the basic operators in Python?

  • Arithmetic: +, -, *, /, %, //, **

  • Comparison: ==, !=, >, <, >=, <=

  • Logical: and, or, not

  • Assignment: =, +=, -=, etc.

  • Membership: in, not in

  • Identity: is, is not


11. What is the difference between == and is?

  • == checks if values are equal.

  • is checks if two references point to the same object in memory.

a = [1, 2]
b = [1, 2]
print(a == b)  # True
print(a is b)  # False

12. What is indentation and why is it important in Python?

Indentation defines blocks of code. Python uses it instead of braces {}. Improper indentation results in errors.

if True:
    print("Yes")

13. How do you write comments in Python?

  • Single-line:

    # This is a comment
    
  • Multi-line (conventionally):

    """
    This is a
    multi-line comment
    """
    

14. What are the different ways to take input from the user?

name = input("Enter your name: ")

Always returns a string. For numeric input:

age = int(input("Enter your age: "))

15. How to print output in Python?

Using the print() function:

print("Hello, World!")

16. What is the print() function?

It outputs the given text or variables to the console.

print("Sum is", 5 + 3)

17. What is a function in Python?

A function is a block of reusable code that performs a specific task.


18. How do you define a function?

Using the def keyword:

def greet(name):
    print("Hello", name)

19. What is a return statement?

It ends the function and optionally returns a value.

def add(a, b):
    return a + b

20. **What are *args and kwargs?

  • *args: Allows passing a variable number of positional arguments.

    def add(*numbers):
        return sum(numbers)
    
  • **kwargs: Allows passing a variable number of keyword arguments.

    def display(**info):
        print(info)
    

21. What are strings in Python?

Strings are sequences of characters enclosed in single ('...') or double ("...") quotes. They are immutable, meaning once created, they cannot be changed.

text = "Hello, Python!"

22. How do you concatenate strings in Python?

Strings can be concatenated using the + operator or formatted using f-strings or .format():

name = "Alice"
greeting = "Hello, " + name
# OR
greeting = f"Hello, {name}"

23. What are string methods in Python?

String methods help manipulate string data. Common examples include:

  • lower(), upper(), title(), strip(), replace(), split(), find(), startswith(), endswith()

s = " Hello World "
print(s.strip().upper())  # Output: HELLO WORLD

24. What is string formatting?

Python offers several ways to format strings:

  • f-strings (Python 3.6+): f"Hello, {name}"

  • format(): "Hello, {}".format(name)

  • % formatting: "Hello, %s" % name


25. What are Python’s built-in functions?

Python provides several useful built-in functions such as:

  • print(), len(), type(), range(), input(), int(), float(), str(), list(), sum(), max(), min(), sorted(), abs(), round()


26. What is the difference between isinstance() and type()?

  • type(obj) returns the actual type of the object.

  • isinstance(obj, Class) checks whether an object is an instance of a class or its subclass.

isinstance(10, int)  # True

27. What are Python classes?

A class is a blueprint for creating objects. It defines attributes and methods that the created objects will have.

class Person:
    def __init__(self, name):
        self.name = name
    def greet(self):
        print(f"Hi, I'm {self.name}")

28. What is __init__ in Python?

__init__() is a special method automatically called when a class object is created. It initializes the object’s attributes.

class Dog:
    def __init__(self, name):
        self.name = name

29. What is inheritance in Python?

Inheritance allows a class (child) to inherit attributes and methods from another class (parent).

class Animal:
    def sound(self):
        print("Some sound")

class Dog(Animal):
    pass

d = Dog()
d.sound()  # Output: Some sound

30. What are instance and class variables?

  • Instance variables are unique to each object and defined using self in methods.

  • Class variables are shared among all instances and defined at the class level.

class Car:
    wheels = 4  # class variable
    def __init__(self, color):
        self.color = color  # instance variable

 


31. What is encapsulation in Python?

Encapsulation is the concept of restricting direct access to some parts of an object to protect the internal state. It is implemented using private or protected attributes:

  • _protected (convention)

  • __private (name mangling)

class Example:
    def __init__(self):
        self._protected = "Protected"
        self.__private = "Private"

32. What is polymorphism in Python?

Polymorphism allows different classes to implement the same method in different ways.

class Cat:
    def sound(self):
        return "Meow"

class Dog:
    def sound(self):
        return "Woof"

for animal in (Cat(), Dog()):
    print(animal.sound())

33. What is abstraction in Python?

Abstraction hides the complexity and shows only the essential features. It is implemented using abstract base classes (ABC) and @abstractmethod from the abc module.

from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        pass

34. What is method overloading in Python?

Python doesn’t support traditional method overloading. Instead, you use default arguments or *args, **kwargs to achieve similar behavior.

def greet(name=None):
    if name:
        print(f"Hello, {name}")
    else:
        print("Hello")

35. What is method overriding in Python?

Method overriding allows a subclass to provide a specific implementation of a method already defined in its parent class.

class Parent:
    def show(self):
        print("Parent")

class Child(Parent):
    def show(self):
        print("Child")

36. What are static methods in Python?

A @staticmethod is bound to the class and not the object. It doesn’t access self or cls.

class Math:
    @staticmethod
    def add(a, b):
        return a + b

37. What are class methods in Python?

A @classmethod takes cls as its first argument and can access or modify the class state.

class Person:
    count = 0

    @classmethod
    def increase_count(cls):
        cls.count += 1

38. What are magic methods in Python?

Magic methods (or dunder methods) start and end with __. They define object behavior for built-in operations.
Examples:

  • __init__, __str__, __len__, __add__, __eq__, __getitem__

class Book:
    def __str__(self):
        return "Book instance"

39. What is inheritance hierarchy in Python?

It’s the relationship chain where subclasses inherit from base classes, which may in turn inherit from other classes.

  • Single inheritance: One parent class

  • Multiple inheritance: Inheriting from more than one class

  • Multilevel inheritance: Chain of inheritance


40. What is the super() function?

super() is used to call a method from the parent class, often in constructors or overridden methods.

class Parent:
    def __init__(self):
        print("Parent init")

class Child(Parent):
    def __init__(self):
        super().__init__()
        print("Child init")

 


41. What is exception handling in Python?

Exception handling manages runtime errors using try, except, else, and finally blocks.

try:
    x = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")

42. What is the use of finally in Python?

The finally block is executed no matter what—whether an exception occurs or not.

try:
    x = 1 / 0
except:
    print("Error")
finally:
    print("Always runs")

43. What is the raise keyword in Python?

raise is used to manually trigger an exception.

raise ValueError("Invalid input")

44. How do you define a custom exception in Python?

By creating a class that inherits from Exception.

class MyError(Exception):
    pass

45. What is file handling in Python?

File handling is used to read/write files using built-in functions:

file = open("example.txt", "r")
data = file.read()
file.close()

46. What are the modes used in open() function?

  • 'r': Read (default)

  • 'w': Write

  • 'a': Append

  • 'b': Binary

  • 'x': Create


47. What is the difference between read(), readline(), and readlines()?

  • read(): Reads entire file as one string

  • readline(): Reads one line at a time

  • readlines(): Reads all lines and returns a list of lines


48. How do you write to a file in Python?

with open("output.txt", "w") as file:
    file.write("Hello, world!")

49. What is the use of with statement in file handling?

It ensures the file is properly closed after operations, even if an error occurs.

with open("file.txt") as f:
    content = f.read()

50. What is a module in Python?

A module is a .py file containing Python code (variables, functions, classes) that can be reused.

import math
print(math.pi)

 


51. What is a package in Python?

A package is a directory that contains multiple related Python modules and a special __init__.py file.

mypackage/
│
├── __init__.py
├── module1.py
└── module2.py

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

Module Package
A single .py file A directory with __init__.py
Can contain classes, functions Can contain multiple modules
Example: math Example: numpy

53. How do you import a module in Python?

import math
from math import sqrt

You can also use as to alias:

import math as m

54. What is the __name__ == "__main__" statement?

It checks whether the file is being run directly or imported as a module.

if __name__ == "__main__":
    print("Run directly")

55. What are Python loops?

Loops execute a block of code repeatedly.

  • for loop: Iterates over a sequence

  • while loop: Runs as long as a condition is true


56. Explain the for loop.

The for loop iterates over elements of a sequence (like a list, string, or range).

for i in range(5):
    print(i)

57. Explain the while loop.

The while loop runs as long as the given condition is true.

i = 0
while i < 5:
    print(i)
    i += 1

58. What is a break statement?

break is used to exit a loop prematurely.

for i in range(5):
    if i == 3:
        break
    print(i)

59. What is a continue statement?

continue skips the current iteration and moves to the next one.

for i in range(5):
    if i == 2:
        continue
    print(i)

60. How does the pass statement work?

pass is a null operation used as a placeholder for future code. It does nothing when executed.

for i in range(5):
    pass  # placeholder

61. What is a list comprehension?

List comprehension is a concise way to create lists using a single line of code.

squares = [x**2 for x in range(5)]
print(squares)  # Output: [0, 1, 4, 9, 16]

62. What is slicing?

Slicing extracts a portion of a sequence (like a list or string) using [start:stop:step].

nums = [0, 1, 2, 3, 4, 5]
print(nums[1:4])  # Output: [1, 2, 3]

63. How do you access elements in a list?

Using indexing:

fruits = ["apple", "banana", "cherry"]
print(fruits[0])  # Output: apple

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

  • append() adds a single element at the end

  • insert() adds an element at a specific index

fruits.append("orange")
fruits.insert(1, "grape")

65. How do you remove an element from a list?

  • remove(value) removes the first occurrence

  • pop(index) removes and returns the item at the given index

  • del list[index] deletes by index

fruits.remove("banana")
fruits.pop(0)
del fruits[1]

66. What is the difference between append() and extend()?

  • append() adds a single item (as one element)

  • extend() adds multiple items from another iterable

a = [1, 2]
a.append([3, 4])   # [1, 2, [3, 4]]
a = [1, 2]
a.extend([3, 4])   # [1, 2, 3, 4]

67. How do you sort a list?

  • list.sort() sorts in place

  • sorted(list) returns a new sorted list

numbers = [3, 1, 4, 2]
numbers.sort()  # [1, 2, 3, 4]

68. What are tuples?

Tuples are immutable sequences of elements, defined using parentheses ().

t = (1, 2, 3)

69. Can you change tuple elements?

No, tuples are immutable, meaning their values cannot be changed after creation.

t = (1, 2, 3)
# t[0] = 5  # This will raise a TypeError

70. How do you convert between list and tuple?

  • Convert list to tuple: tuple(my_list)

  • Convert tuple to list: list(my_tuple)

list1 = [1, 2]
tuple1 = tuple(list1)