Showing 50 question(s)
Answer:
Python is a high-level, interpreted, object-oriented programming language known for its simple syntax, readability, and extensive standard library. It is widely used for web development, automation, data science, machine learning, and scripting.
Code Example:
print("Hello, World!")Answer:
Python is easy to learn, interpreted, dynamically typed, object-oriented, cross-platform, open source, and comes with a rich standard library.
Code Example:
# Dynamic Typing
x = 10
x = "Python"
print(x)Answer:
Lists are mutable, meaning they can be modified after creation. Tuples are immutable and cannot be changed once created.
Code Example:
numbers = [1, 2, 3]
numbers.append(4)
colors = ("Red", "Blue", "Green")
print(numbers)
print(colors)Answer:
Object-Oriented Programming (OOP) is a programming paradigm based on classes and objects. It supports encapsulation, inheritance, polymorphism, and abstraction.
Code Example:
class Student:
def __init__(self, name):
self.name = name
def display(self):
print(self.name)
student = Student("John")
student.display()Answer:
*args allows passing multiple positional arguments, whereas **kwargs allows passing multiple keyword arguments.
Code Example:
def display(*args):
for item in args:
print(item)
display(1, 2, 3)
def info(**kwargs):
print(kwargs)
info(name="John", age=25)Answer:
A dictionary is a mutable collection of key-value pairs. Keys must be unique and immutable.
Code Example:
employee = {
"id": 1,
"name": "Alice",
"salary": 50000
}
print(employee["name"])Answer:
Python uses try, except, else, and finally blocks to handle runtime exceptions.
Code Example:
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("Finished")Answer:
A module is a single Python file containing code, while a package is a collection of modules organized in directories.
Code Example:
import math
print(math.sqrt(25))Answer:
Files can be read using the open() function with read(), readline(), or readlines(). Using the with statement automatically closes the file.
Code Example:
with open("sample.txt", "r") as file:
content = file.read()
print(content)Answer:
List comprehension provides a concise way to create lists using a single line of code.
Code Example:
numbers = [1, 2, 3, 4, 5]
squares = [x * x for x in numbers]
print(squares)Answer:
A lambda function is a small anonymous function defined using the lambda keyword. It can have multiple arguments but only one expression.
Code Example:
square = lambda x: x * x
print(square(5))Answer:
Lists maintain insertion order and allow duplicate values. Sets store unique elements and are optimized for membership testing.
Code Example:
numbers = [1, 2, 2, 3]
unique = {1, 2, 2, 3}
print(numbers)
print(unique)Answer:
The enumerate() function adds a counter to an iterable and returns index-value pairs.
Code Example:
fruits = ["Apple", "Orange", "Banana"]
for index, fruit in enumerate(fruits):
print(index, fruit)Answer:
Decorators allow you to modify or extend the behavior of functions without changing their source code.
Code Example:
def logger(func):
def wrapper():
print("Executing...")
func()
return wrapper
@logger
def display():
print("Hello")
display()Answer:
Generators produce values one at a time using the yield keyword, making them memory efficient.
Code Example:
def numbers():
for i in range(5):
yield i
for num in numbers():
print(num)Answer:
append() adds a single element to the list, whereas extend() adds all elements from another iterable.
Code Example:
numbers = [1, 2]
numbers.append([3, 4])
print(numbers)
numbers = [1, 2]
numbers.extend([3, 4])
print(numbers)Answer:
Inheritance allows a class to inherit properties and methods from another class, promoting code reuse.
Code Example:
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def bark(self):
print("Dog barks")
dog = Dog()
dog.speak()
dog.bark()Answer:
Polymorphism allows different classes to define methods with the same name but different implementations.
Code Example:
class Dog:
def sound(self):
print("Bark")
class Cat:
def sound(self):
print("Meow")
animals = [Dog(), Cat()]
for animal in animals:
animal.sound()Answer:
The == operator compares the values of two objects, while the is operator checks whether two variables refer to the same object in memory.
Code Example:
list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = list1
print(list1 == list2) # True (values are equal)
print(list1 is list2) # False (different objects)
print(list1 is list3) # True (same object)Answer:
The global keyword is used to modify a variable defined at the global scope, whereas the nonlocal keyword is used to modify a variable in the nearest enclosing function scope.
Code Example:
count = 0
def outer():
value = 10
def inner():
nonlocal value
global count
value += 5
count += 1
print("Inner Value:", value)
inner()
print("Outer Value:", value)
outer()
print("Global Count:", count)Answer:
Abstraction hides implementation details and exposes only the essential features of an object. In Python, abstraction is commonly implemented using the abc module.
Code Example:
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Circle(Shape):
def area(self):
return 3.14 * 5 * 5
shape = Circle()
print(shape.area())Answer:
A shallow copy copies the object but shares nested objects. A deep copy recursively copies all nested objects, creating an independent clone.
Code Example:
import copy
numbers = [[1,2],[3,4]]
shallow = copy.copy(numbers)
deep = copy.deepcopy(numbers)
numbers[0][0] = 100
print(shallow)
print(deep)Answer:
Slicing extracts a portion of a sequence such as a list, tuple, or string using the syntax start:stop:step.
Code Example:
numbers = [10,20,30,40,50]
print(numbers[1:4])
print(numbers[::-1])Answer:
Strings can be reversed using slicing with a step value of -1.
Code Example:
text = "Python"
reverse = text[::-1]
print(reverse)Answer:
The zip() function combines multiple iterables into a single iterator of tuples.
Code Example:
names = ["John","Alice","Bob"]
ages = [25,30,35]
for item in zip(names, ages):
print(item)Answer:
The map() function applies a function to every item of an iterable and returns an iterator.
Code Example:
numbers = [1,2,3,4]
squares = list(map(lambda x: x*x, numbers))
print(squares)Answer:
The filter() function filters elements from an iterable based on a condition.
Code Example:
numbers = [1,2,3,4,5,6]
even = list(filter(lambda x: x % 2 == 0, numbers))
print(even)Answer:
The reduce() function applies a function cumulatively to iterable elements and returns a single value.
Code Example:
from functools import reduce
numbers = [1,2,3,4]
total = reduce(lambda x,y: x+y, numbers)
print(total)Answer:
Files can be written using the open() function with write mode ("w") or append mode ("a").
Code Example:
with open("sample.txt","w") as file:
file.write("Hello Python")
print("File written successfully")Answer:
You can create custom exceptions by inheriting from the Exception class and raising them using the raise keyword.
Code Example:
class InvalidAgeError(Exception):
pass
age = 15
if age < 18:
raise InvalidAgeError(
"Age must be at least 18."
)Answer:
Recursion is a programming technique where a function calls itself until a base condition is met. It is commonly used for problems like factorials and tree traversal.
Code Example:
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
print(factorial(5))Answer:
Python automatically manages memory using reference counting and a cyclic garbage collector to free unused objects.
Code Example:
import gc
gc.collect()
print("Garbage collection executed")Answer:
remove() deletes an item by value, pop() removes and returns an item by index, and del deletes an item or entire object.
Code Example:
numbers = [10,20,30,40]
numbers.remove(20)
numbers.pop()
del numbers[0]
print(numbers)Answer:
Virtual environments create isolated Python environments for projects, allowing each project to have its own dependencies.
Code Example:
# Create virtual environment
python -m venv myenv
# Activate (Windows)
myenv\Scripts\activate
# Activate (Linux/macOS)
source myenv/bin/activateAnswer:
An iterable is an object that can be looped over, while an iterator is an object that keeps track of the current position during iteration.
Code Example:
numbers = [1,2,3]
iterator = iter(numbers)
print(next(iterator))
print(next(iterator))
print(next(iterator))Answer:
*args accepts any number of positional arguments, while **kwargs accepts any number of keyword arguments.
Code Example:
def display(*args, **kwargs):
print(args)
print(kwargs)
display(1,2,3,name="John",age=25)Answer:
Method overriding allows a child class to provide its own implementation of a method already defined in the parent class.
Code Example:
class Animal:
def speak(self):
print("Animal")
class Dog(Animal):
def speak(self):
print("Dog Barks")
dog = Dog()
dog.speak()Answer:
Python does not support traditional method overloading. Similar functionality is achieved using default arguments or variable-length arguments.
Code Example:
class Calculator:
def add(self, a, b=0):
return a + b
calc = Calculator()
print(calc.add(5))
print(calc.add(5,10))Answer:
Decorators with parameters allow passing arguments to a decorator, providing greater flexibility when modifying function behavior.
Code Example:
def repeat(times):
def decorator(func):
def wrapper():
for _ in range(times):
func()
return wrapper
return decorator
@repeat(3)
def greet():
print("Hello")
greet()Answer:
The Global Interpreter Lock (GIL) allows only one thread to execute Python bytecode at a time in CPython. It simplifies memory management but limits CPU-bound multithreading.
Code Example:
import threading
def worker():
print("Running...")
t1 = threading.Thread(target=worker)
t2 = threading.Thread(target=worker)
t1.start()
t2.start()
t1.join()
t2.join()Answer:
Lists are built-in Python data structures that can store different data types, whereas NumPy arrays store elements of the same type and provide faster mathematical operations.
Code Example:
import numpy as np
numbers = [1, 2, 3]
array = np.array([1, 2, 3])
print(numbers)
print(array * 2)Answer:
Context managers manage resources automatically using the with statement. They ensure proper setup and cleanup of resources such as files and database connections.
Code Example:
with open("sample.txt", "r") as file:
content = file.read()
print(content)Answer:
Python supports string formatting using f-strings, format(), and the % operator. F-strings are the preferred approach because they are readable and efficient.
Code Example:
name = "John"
age = 25
print(f"{name} is {age} years old")Answer:
Dictionary comprehensions provide a concise way to create dictionaries using a single line of code.
Code Example:
numbers = [1,2,3,4]
squares = {x: x*x for x in numbers}
print(squares)Answer:
Set comprehensions are used to create sets in a concise way while automatically removing duplicate values.
Code Example:
numbers = [1,2,2,3,4,4]
unique = {x for x in numbers}
print(unique)Answer:
Dataclasses simplify the creation of classes that primarily store data by automatically generating methods such as __init__, __repr__, and __eq__.
Code Example:
from dataclasses import dataclass
@dataclass
class Employee:
id: int
name: str
emp = Employee(1, "Alice")
print(emp)Answer:
Monkey patching is the practice of modifying or extending classes or modules at runtime without changing their original source code.
Code Example:
class Person:
def greet(self):
print("Hello")
def welcome(self):
print("Welcome!")
Person.greet = welcome
Person().greet()Answer:
Multithreading uses multiple threads within the same process and shares memory, while multiprocessing creates separate processes with independent memory, making it suitable for CPU-intensive tasks.
Code Example:
from multiprocessing import Process
def worker():
print("Running process")
p = Process(target=worker)
p.start()
p.join()Answer:
Python provides the unittest framework for writing and executing unit tests. It helps verify that individual functions and methods work correctly.
Code Example:
import unittest
def add(a, b):
return a + b
class TestMath(unittest.TestCase):
def test_add(self):
self.assertEqual(add(2, 3), 5)
unittest.main()Answer:
Performance can be improved by using efficient data structures, list comprehensions, generators, built-in functions, NumPy for numerical operations, profiling tools, and avoiding unnecessary loops.
Code Example:
# Generator expression
numbers = (x * x for x in range(1000000))
print(next(numbers))
# Efficient membership test
values = {1,2,3,4,5}
print(3 in values)