#18. What is type casting?
A: Type casting (or type conversion) is the process of converting a variable from one data type to another. Functions like
#19. What are Python literals?
A: A literal is a notation for representing a fixed value in source code. Examples include:
• String literals:
• Numeric literals:
• Boolean literals:
• Special literal:
#20. How do you create a multi-line string?
A: Use triple quotes, either
---
Part 2: Data Structures (Q21-40)
#21. What is the main difference between a List and a Tuple?
A: The primary difference is that Lists are mutable, meaning their elements can be changed, added, or removed. Tuples are immutable, meaning once they are created, their elements cannot be changed. Tuples are generally faster than lists.
#22. What are list comprehensions? Provide an example.
A: A list comprehension is a concise and readable way to create a list. It consists of brackets containing an expression followed by a
#23. How do you remove duplicates from a list?
A: The simplest way is to convert the list to a set and then back to a list. Sets automatically discard duplicate elements. This method does not preserve the original order.
#24. What is the difference between
A:
•
•
#25. Explain slicing in Python.
A: Slicing is a feature that allows you to access a range of elements from a sequence (like a list, string, or tuple). The syntax is
•
•
•
---
#26. Can a dictionary key be a list? Why or why not?
A: No. Dictionary keys must be of an immutable type. Since lists are mutable, they cannot be used as dictionary keys. You can use immutable types like strings, numbers, or tuples as keys.
A: Type casting (or type conversion) is the process of converting a variable from one data type to another. Functions like
int(), float(), str(), and list() are used for this.string_num = "123"
integer_num = int(string_num)
print(integer_num + 7)
130
#19. What are Python literals?
A: A literal is a notation for representing a fixed value in source code. Examples include:
• String literals:
"hello", 'world'• Numeric literals:
100, 3.14• Boolean literals:
True, False• Special literal:
None#20. How do you create a multi-line string?
A: Use triple quotes, either
""" or '''.multi_line = """This is a string
that spans across
multiple lines."""
print(multi_line)
This is a string
that spans across
multiple lines.
---
Part 2: Data Structures (Q21-40)
#21. What is the main difference between a List and a Tuple?
A: The primary difference is that Lists are mutable, meaning their elements can be changed, added, or removed. Tuples are immutable, meaning once they are created, their elements cannot be changed. Tuples are generally faster than lists.
#22. What are list comprehensions? Provide an example.
A: A list comprehension is a concise and readable way to create a list. It consists of brackets containing an expression followed by a
for clause, then zero or more for or if clauses.# Create a list of squares for numbers 0 through 9
squares = [x**2 for x in range(10)]
print(squares)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
#23. How do you remove duplicates from a list?
A: The simplest way is to convert the list to a set and then back to a list. Sets automatically discard duplicate elements. This method does not preserve the original order.
my_list = [1, 2, 3, 2, 4, 1, 5]
unique_list = list(set(my_list))
print(unique_list)
[1, 2, 3, 4, 5]
#24. What is the difference between
.sort() and sorted()?A:
•
.sort() is a list method that sorts the list in-place (modifies the original list) and returns None.•
sorted() is a built-in function that takes an iterable as an argument and returns a new sorted list, leaving the original iterable unchanged.my_list = [3, 1, 2]
sorted_list = sorted(my_list)
print(f"Original list after sorted(): {my_list}")
print(f"New list from sorted(): {sorted_list}")
my_list.sort()
print(f"Original list after .sort(): {my_list}")
Original list after sorted(): [3, 1, 2]
New list from sorted(): [1, 2, 3]
Original list after .sort(): [1, 2, 3]
#25. Explain slicing in Python.
A: Slicing is a feature that allows you to access a range of elements from a sequence (like a list, string, or tuple). The syntax is
sequence[start:stop:step].•
start: The index of the first element to include.•
stop: The index of the first element to exclude.•
step: The amount to increment by.my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Elements from index 2 up to (not including) 5
print(my_list[2:5])
# Every second element
print(my_list[::2])
# Reverse the list
print(my_list[::-1])
[2, 3, 4]
[0, 2, 4, 6, 8]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
---
#26. Can a dictionary key be a list? Why or why not?
A: No. Dictionary keys must be of an immutable type. Since lists are mutable, they cannot be used as dictionary keys. You can use immutable types like strings, numbers, or tuples as keys.
#27. How do you merge two dictionaries?
A: In Python 3.9+, you can use the
#28. How do you iterate over the keys, values, and items of a dictionary?
A: Use the
#29. What is a set? What are its main properties?
A: A set is an unordered collection of unique elements.
• Unique: Sets cannot have duplicate members.
• Unordered: The elements are not stored in any specific order.
• Mutable: You can add or remove elements from a set.
#30. What is a
A: A
---
#31. How do you find the intersection of two sets?
A: Use the
#32. What is the difference between
A:
•
•
#33. How do you reverse a list?
A:
• Use the
• Use slicing
#34. What is
A:
#35. What is the time complexity of a key lookup in a list vs. a dictionary?
A:
• List: O(n), because in the worst case, you may have to scan the entire list to find an element.
• Dictionary/Set: O(1) on average. Dictionaries use a hash table, which allows for direct lookup of a key's location without scanning.
#36. How do you create an empty set?
A: You must use the
A: In Python 3.9+, you can use the
| (union) operator. For earlier versions, you can use the ** unpacking operator or the .update() method.dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
# Using the | operator (Python 3.9+)
merged_dict = dict1 | dict2
print(merged_dict){'a': 1, 'b': 3, 'c': 4}#28. How do you iterate over the keys, values, and items of a dictionary?
A: Use the
.keys(), .values(), and .items() methods.my_dict = {'name': 'Alice', 'age': 25}
for key, value in my_dict.items():
print(f"{key}: {value}")name: Alice
age: 25
#29. What is a set? What are its main properties?
A: A set is an unordered collection of unique elements.
• Unique: Sets cannot have duplicate members.
• Unordered: The elements are not stored in any specific order.
• Mutable: You can add or remove elements from a set.
#30. What is a
frozenset?A: A
frozenset is an immutable version of a set. Once created, you cannot add or remove elements. Because they are immutable and hashable, they can be used as dictionary keys or as elements of another set.---
#31. How do you find the intersection of two sets?
A: Use the
& operator or the .intersection() method.set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
print(set1 & set2){3, 4}#32. What is the difference between
.append() and .extend() for lists?A:
•
.append(element): Adds its argument as a single element to the end of a list.•
.extend(iterable): Iterates over its argument and adds each element to the list, extending the list.list_a = [1, 2, 3]
list_b = [1, 2, 3]
list_a.append([4, 5])
list_b.extend([4, 5])
print(f"After append: {list_a}")
print(f"After extend: {list_b}")
After append: [1, 2, 3, [4, 5]]
After extend: [1, 2, 3, 4, 5]
#33. How do you reverse a list?
A:
• Use the
.reverse() method to reverse the list in-place.• Use slicing
[::-1] to create a new, reversed copy of the list.my_list = [1, 2, 3, 4]
reversed_copy = my_list[::-1]
print(reversed_copy)
[4, 3, 2, 1]
#34. What is
defaultdict?A:
defaultdict is a subclass of the standard dict that is found in the collections module. It overrides one method and adds one writable instance variable. Its main advantage is that it does not raise a KeyError if you try to access a key that does not exist. Instead, it provides a default value for that key.from collections import defaultdict
d = defaultdict(int) # Default value for non-existent keys will be int(), which is 0
d['a'] += 1
print(d['a'])
print(d['b']) # Accessing a non-existent key
1
0
#35. What is the time complexity of a key lookup in a list vs. a dictionary?
A:
• List: O(n), because in the worst case, you may have to scan the entire list to find an element.
• Dictionary/Set: O(1) on average. Dictionaries use a hash table, which allows for direct lookup of a key's location without scanning.
#36. How do you create an empty set?
A: You must use the
set() constructor. Using {} creates an empty dictionary, not an empty set.empty_dict = {}
empty_set = set()
print(type(empty_dict))
print(type(empty_set))<class 'dict'>
<class 'set'>
❤1
#37. How can you get a value from a dictionary without raising a
A: Use the
#38. What is a hashable object?
A: An object is hashable if it has a hash value that never changes during its lifetime. This means it must be immutable. Hashable objects can be used as dictionary keys and set members. Examples:
#39. What is dictionary comprehension?
A: It is a concise and readable way to create a dictionary.
#40. Explain how to use
A: The
---
Part 3: Functions & Functional Programming (Q41-55)
#41. What are
A: They are used to pass a variable number of arguments to a function.
•
•
#42. What is a lambda function?
A: A lambda function is a small, anonymous function defined with the
#43. What is a decorator?
A: A decorator is a design pattern in Python that allows a user to add new functionality to an existing object (like a function) without modifying its structure. Decorators are usually called before the definition of a function you want to decorate.
#44. What is a generator? What is the
A: A generator is a special type of iterator that is simpler to create. Instead of returning a value and terminating, a generator function uses the
KeyError?A: Use the
.get(key, default_value) method. It returns the value for the key if it exists, otherwise it returns the default_value (which is None if not specified).my_dict = {'a': 1}
print(my_dict.get('a'))
print(my_dict.get('b', 'Not Found'))1
Not Found
#38. What is a hashable object?
A: An object is hashable if it has a hash value that never changes during its lifetime. This means it must be immutable. Hashable objects can be used as dictionary keys and set members. Examples:
int, str, tuple.#39. What is dictionary comprehension?
A: It is a concise and readable way to create a dictionary.
# Create a dictionary of numbers and their squares
squares_dict = {x: x**2 for x in range(5)}
print(squares_dict)
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}#40. Explain how to use
zip() to combine two lists.A: The
zip() function takes two or more iterables and returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument iterables. It stops when the shortest input iterable is exhausted.names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
combined = list(zip(names, ages))
print(combined)
[('Alice', 25), ('Bob', 30), ('Charlie', 35)]---
Part 3: Functions & Functional Programming (Q41-55)
#41. What are
*args and **kwargs?A: They are used to pass a variable number of arguments to a function.
•
*args (Non-Keyword Arguments): Gathers extra positional arguments into a tuple.•
**kwargs (Keyword Arguments): Gathers extra keyword arguments into a dictionary.def my_func(a, b, *args, **kwargs):
print(f"a: {a}, b: {b}")
print(f"args: {args}")
print(f"kwargs: {kwargs}")
my_func(1, 2, 3, 4, name="Alice", city="NY")
a: 1, b: 2
args: (3, 4)
kwargs: {'name': 'Alice', 'city': 'NY'}
#42. What is a lambda function?
A: A lambda function is a small, anonymous function defined with the
lambda keyword. It can take any number of arguments but can only have one expression. They are often used when a simple function is needed for a short period.# A lambda function that doubles its input
double = lambda x: x * 2
print(double(5))
10
#43. What is a decorator?
A: A decorator is a design pattern in Python that allows a user to add new functionality to an existing object (like a function) without modifying its structure. Decorators are usually called before the definition of a function you want to decorate.
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
Something is happening before the function is called.
Hello!
Something is happening after the function is called.
#44. What is a generator? What is the
yield keyword?A: A generator is a special type of iterator that is simpler to create. Instead of returning a value and terminating, a generator function uses the
yield keyword. When yield is called, it "pauses" the function, returns the value, and saves its state. On the next call, it resumes execution from where it left off. Generators are memory efficient for working with large data sequences.def count_up_to(max):
count = 1
while count <= max:
yield count
count += 1
counter = count_up_to(3)
print(next(counter))
print(next(counter))
print(next(counter))
1
2
3
#45. What is the difference between an iterator and a generator?
A:
• Iterator: An object that implements the iterator protocol (
__iter__() and __next__() methods). It's more complex to create as you have to write a class.• Generator: A simpler way to create an iterator using a function with the
yield keyword. All generators are iterators, but not all iterators are generators.---
#46. Explain the
map() function.A: The
map(function, iterable) function applies the given function to every item of the iterable and returns a map object (an iterator) with the results.numbers = [1, 2, 3, 4]
squared_numbers = map(lambda x: x**2, numbers)
print(list(squared_numbers))
[1, 4, 9, 16]
#47. Explain the
filter() function.A: The
filter(function, iterable) function constructs an iterator from elements of the iterable for which the function returns True.numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter(lambda x: x % 2 == 0, numbers)
print(list(even_numbers))
[2, 4, 6]
#48. What does the
global keyword do?A: The
global keyword is used to modify a global variable from inside a function. Without it, assigning a value to a variable inside a function creates a new local variable.count = 0
def increment():
global count
count += 1
increment()
print(count)
1
#49. Can a function return multiple values?
A: Yes. A Python function can return multiple values by separating them with commas. Internally, Python packs these values into a single tuple and returns that tuple.
def get_name_and_age():
return "Alice", 25
name, age = get_name_and_age()
print(f"Name: {name}, Age: {age}")
Name: Alice, Age: 25
#50. What are docstrings?
A: A docstring is a string literal that occurs as the first statement in a module, function, class, or method definition. It is used to document what the code does. It is accessible via the
__doc__ attribute.def add(a, b):
"""This function adds two numbers and returns the result."""
return a + b
print(add.__doc__)
This function adds two numbers and returns the result.
---
#51. What are closures in Python?
A: A closure is a function object that remembers values in the enclosing scope even if they are not present in memory. It's a function that is defined inside another function (the enclosing function) and references variables from that enclosing function.
def outer_function(text):
def inner_function():
print(text) # inner_function "closes over" the text variable
return inner_function
my_func = outer_function("Hello")
my_func()
Hello
#52. What is recursion? Provide a simple example.
A: Recursion is a programming technique where a function calls itself in order to solve a problem. A recursive function must have a base case that stops the recursion.
# Calculate factorial using recursion
def factorial(n):
if n == 1:
return 1 # Base case
else:
return n * factorial(n - 1) # Recursive call
print(factorial(5))
120
#53. What is the difference between a function and a method?
A:
• A method is a function that "belongs to" an object. It is called on an object (
• A function is not associated with any object. It is called by its name (
#54. What does the
A: The
#55. What is a first-class function?
A: In Python, functions are "first-class citizens". This means they can be treated like any other object: they can be assigned to variables, stored in data structures (like lists), passed as arguments to other functions, and returned from functions.
---
Part 4: Object-Oriented Programming (OOP) (Q56-70)
#56. What are the four main principles of OOP?
A:
• Encapsulation: Bundling data (attributes) and methods that operate on the data into a single unit (a class).
• Inheritance: A mechanism where a new class (subclass) inherits attributes and methods from an existing class (superclass).
• Polymorphism: The ability of an object to take on many forms. For example, different classes can have methods with the same name that perform different actions.
• Abstraction: Hiding complex implementation details and showing only the essential features of the object.
#57. What is the difference between a class and an object?
A:
• A Class is a blueprint or template for creating objects. It defines a set of attributes and methods.
• An Object is an instance of a class. It is a concrete entity created from the class blueprint, with actual values for its attributes.
#58. What is
A:
#59. What is the
A:
#60. What is inheritance?
A: Inheritance allows us to define a class that inherits all the methods and properties from another class. The parent class is the class being inherited from, and the child class is the class that inherits.
---
#61. What is multiple inheritance?
A: Multiple inheritance is a feature where a class can inherit attributes and methods from more than one parent class. Python supports multiple inheritance.
A:
• A method is a function that "belongs to" an object. It is called on an object (
object.method()) and can access and modify the object's data (its attributes).• A function is not associated with any object. It is called by its name (
function()).#54. What does the
nonlocal keyword do?A: The
nonlocal keyword is used in nested functions to refer to a variable in the nearest enclosing scope (but not the global scope). It's used to modify variables in an outer (but not global) function.def outer():
x = "local"
def inner():
nonlocal x
x = "nonlocal"
print("inner:", x)
inner()
print("outer:", x)
outer()
inner: nonlocal
outer: nonlocal
#55. What is a first-class function?
A: In Python, functions are "first-class citizens". This means they can be treated like any other object: they can be assigned to variables, stored in data structures (like lists), passed as arguments to other functions, and returned from functions.
---
Part 4: Object-Oriented Programming (OOP) (Q56-70)
#56. What are the four main principles of OOP?
A:
• Encapsulation: Bundling data (attributes) and methods that operate on the data into a single unit (a class).
• Inheritance: A mechanism where a new class (subclass) inherits attributes and methods from an existing class (superclass).
• Polymorphism: The ability of an object to take on many forms. For example, different classes can have methods with the same name that perform different actions.
• Abstraction: Hiding complex implementation details and showing only the essential features of the object.
#57. What is the difference between a class and an object?
A:
• A Class is a blueprint or template for creating objects. It defines a set of attributes and methods.
• An Object is an instance of a class. It is a concrete entity created from the class blueprint, with actual values for its attributes.
#58. What is
self?A:
self represents the instance of the class. By using the self keyword, we can access the attributes and methods of the class in Python. It is the first argument passed to instance methods.#59. What is the
__init__ method?A:
__init__ is a special method in Python classes, also known as the constructor. It is automatically called when a new object of the class is created. It is used to initialize the object's attributes.class Dog:
def __init__(self, name):
self.name = name # Initialize the name attribute
print(f"{self.name} was born!")
my_dog = Dog("Rex")
Rex was born!
#60. What is inheritance?
A: Inheritance allows us to define a class that inherits all the methods and properties from another class. The parent class is the class being inherited from, and the child class is the class that inherits.
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal): # Dog inherits from Animal
def bark(self):
print("Woof!")
d = Dog()
d.speak() # Inherited from Animal
d.bark()
Animal speaks
Woof!
---
#61. What is multiple inheritance?
A: Multiple inheritance is a feature where a class can inherit attributes and methods from more than one parent class. Python supports multiple inheritance.
class A:
def method(self):
print("Method from A")
class B:
def method(self):
print("Method from B")
class C(B, A): # Inherits from B, then A
pass
c = C()
c.method() # Calls method from B due to MRO
Method from B
#62. What is MRO (Method Resolution Order)?
A: MRO is the order in which Python looks for a method in a hierarchy of classes. In the case of multiple inheritance, it determines which parent class's method is called. You can view the MRO of a class using
#63. What is polymorphism?
A: Polymorphism means "many forms". In programming, it refers to methods/functions/operators with the same name that can be executed on many objects or classes.
#64. What is the difference between a class method and a static method?
A:
• Instance Method: Takes
•
•
#65. What is
A:
---
#66. What are public, protected, and private members?
A: These are conventions for encapsulation.
• Public: Accessible from anywhere. (e.g.,
• Protected: Conventionally treated as non-public; accessible within the class and its subclasses. Denoted by a single underscore prefix. (e.g.,
• Private: Accessible only from within the class. Python enforces this through name mangling. Denoted by a double underscore prefix. (e.g.,
#67. What is name mangling?
A: When an identifier starts with two underscores (like
#68. What are magic methods (or dunder methods)?
A: Magic methods are special methods with double underscores at the beginning and end of their names (e.g.,
#69. Explain the difference between
A:
•
•
A: MRO is the order in which Python looks for a method in a hierarchy of classes. In the case of multiple inheritance, it determines which parent class's method is called. You can view the MRO of a class using
ClassName.mro().#63. What is polymorphism?
A: Polymorphism means "many forms". In programming, it refers to methods/functions/operators with the same name that can be executed on many objects or classes.
class Cat:
def speak(self):
return "Meow"
class Dog:
def speak(self):
return "Woof"
def make_sound(animal):
print(animal.speak())
make_sound(Cat())
make_sound(Dog())
Meow
Woof
#64. What is the difference between a class method and a static method?
A:
• Instance Method: Takes
self as the first argument. It can access and modify instance attributes.•
@classmethod: Takes cls (the class itself) as the first argument. It can access and modify class attributes but not instance attributes. Often used as alternative constructors.•
@staticmethod: Does not take self or cls as an implicit first argument. It's essentially a regular function namespaced within the class. It cannot access or modify class or instance state.#65. What is
super()?A:
super() is a built-in function that returns a proxy object that allows you to refer to the parent class. It's commonly used in __init__ methods of child classes to call the parent class's __init__ method, ensuring that parent initializations are not missed.class Parent:
def __init__(self):
print("Parent init")
class Child(Parent):
def __init__(self):
super().__init__() # Call the Parent's init method
print("Child init")
c = Child()
Parent init
Child init
---
#66. What are public, protected, and private members?
A: These are conventions for encapsulation.
• Public: Accessible from anywhere. (e.g.,
member)• Protected: Conventionally treated as non-public; accessible within the class and its subclasses. Denoted by a single underscore prefix. (e.g.,
_member)• Private: Accessible only from within the class. Python enforces this through name mangling. Denoted by a double underscore prefix. (e.g.,
__member)#67. What is name mangling?
A: When an identifier starts with two underscores (like
__spam), it is textually replaced with _classname__spam. This is done to avoid naming conflicts with subclasses.#68. What are magic methods (or dunder methods)?
A: Magic methods are special methods with double underscores at the beginning and end of their names (e.g.,
__init__, __len__, __str__). They are not meant to be called directly but are invoked internally by Python in response to certain operations. For example, len(my_object) calls my_object.__len__().#69. Explain the difference between
__str__ and __repr__.A:
•
__str__(): Called by str(object) and print(object). It should return a user-friendly, readable string representation of the object.•
__repr__(): Called by repr(object). It should return an unambiguous, official string representation of the object, which can ideally be used to recreate the object (e.g., eval(repr(object)) == object). If __str__ is not defined, __repr__ is used as a fallback.#70. What is operator overloading?
A: Operator overloading allows you to redefine the behavior of built-in operators (like
---
Part 5: Advanced Concepts & Libraries (Q71-85)
#71. Explain exception handling in Python.
A: Exception handling is a mechanism for responding to runtime errors.
•
•
•
•
#72. How do you raise a custom exception?
A: You can define a custom exception by creating a new class that inherits from the built-in
#73. What is the purpose of the
A: The
#74. What is the difference between multithreading and multiprocessing?
A:
• Multithreading: Multiple threads run within the same process, sharing the same memory space. Due to the GIL, it's best for I/O-bound tasks (like network requests or file operations) where threads can wait without blocking the entire program.
• Multiprocessing: Multiple processes run, each with its own memory space and Python interpreter. This allows for true parallelism and is ideal for CPU-bound tasks (like heavy calculations) as it bypasses the GIL.
#75. What is the difference between a module and a package?
A:
• Module: A single Python file (
• Package: A way of organizing related modules into a directory hierarchy. A directory must contain a file named
---
#76. What are virtual environments? Why are they important?
A: A virtual environment is an isolated Python environment that allows you to manage dependencies for a specific project separately. They are important because they prevent package version conflicts between different projects on the same machine.
#77. What is
A:
A: Operator overloading allows you to redefine the behavior of built-in operators (like
+, -, *) for your custom classes. This is done by implementing the corresponding magic methods (e.g., __add__ for +, __mul__ for *).---
Part 5: Advanced Concepts & Libraries (Q71-85)
#71. Explain exception handling in Python.
A: Exception handling is a mechanism for responding to runtime errors.
•
try: The block of code to be attempted, which may cause an error.•
except: This block is executed if an error occurs in the try block. You can specify the type of exception to catch.•
else: This block is executed if no exceptions are raised in the try block.•
finally: This block is always executed, whether an exception occurred or not. It's often used for cleanup operations.try:
result = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print(f"Result is {result}")
finally:
print("Execution finished.")
Result is 5.0
Execution finished.
#72. How do you raise a custom exception?
A: You can define a custom exception by creating a new class that inherits from the built-in
Exception class. Then, use the raise keyword to throw it.class MyCustomError(Exception):
pass
raise MyCustomError("Something went wrong!")
#73. What is the purpose of the
with statement?A: The
with statement simplifies exception handling by encapsulating common try...finally cleanup patterns. It is used with objects that support the context management protocol (which have __enter__ and __exit__ methods). It's most commonly used for managing file streams, ensuring the file is closed automatically.# The file is automatically closed after this block
with open('file.txt', 'w') as f:
f.write('hello')
#74. What is the difference between multithreading and multiprocessing?
A:
• Multithreading: Multiple threads run within the same process, sharing the same memory space. Due to the GIL, it's best for I/O-bound tasks (like network requests or file operations) where threads can wait without blocking the entire program.
• Multiprocessing: Multiple processes run, each with its own memory space and Python interpreter. This allows for true parallelism and is ideal for CPU-bound tasks (like heavy calculations) as it bypasses the GIL.
#75. What is the difference between a module and a package?
A:
• Module: A single Python file (
.py) containing statements and definitions.• Package: A way of organizing related modules into a directory hierarchy. A directory must contain a file named
__init__.py (which can be empty) to be considered a package.---
#76. What are virtual environments? Why are they important?
A: A virtual environment is an isolated Python environment that allows you to manage dependencies for a specific project separately. They are important because they prevent package version conflicts between different projects on the same machine.
#77. What is
pip?A:
pip is the standard package manager for Python. It allows you to install and manage third-party libraries and packages from the Python Package Index (PyPI).#78. How does Python's
A: The
#79. What is the
A: The
#80. How do you work with JSON files in Python?
A: Use the built-in
•
•
---
#81. What is the
A: The
#82. What is monkey-patching?
A: Monkey-patching is a technique used to dynamically modify or extend code at runtime. For example, you can change the behavior of a function or a method in a third-party library without altering the original source code.
#83. What is a metaclass?
A: A metaclass is a "class of a class". It defines how a class behaves. A class is an instance of a metaclass. In Python,
#84. What is the difference between
A: This is a Python 2 question.
• In Python 2,
• In Python 3, the old
#85. What are some popular Python frameworks for web development?
A:
• Django: A high-level, "batteries-included" framework that encourages rapid development and clean, pragmatic design.
• Flask: A lightweight microframework that is simpler and more flexible, allowing developers to choose their own libraries and tools.
• FastAPI: A modern, high-performance web framework for building APIs with Python 3.7+ based on standard Python type hints.
---
Part 6: Coding Problems & Algorithms (Q86-100)
#86. Write a function to check if a string is a palindrome.
A: A palindrome reads the same forwards and backward. The easiest way is to compare the string with its reversed version.
#87. Write a Fibonacci sequence generator.
A: A generator is memory-efficient for this task.
for loop work internally?A: The
for loop in Python works with the iterator protocol. When you write for item in iterable:, Python first calls iter(iterable) to get an iterator object. Then, it repeatedly calls next() on this iterator object and assigns the result to item until a StopIteration exception is raised, which signals the end of the loop.#79. What is the
requests library used for?A: The
requests library is the de-facto standard for making HTTP requests in Python. It simplifies the process of interacting with web services and APIs.import requests
response = requests.get('https://api.github.com')
print(response.status_code)
200
#80. How do you work with JSON files in Python?
A: Use the built-in
json module.•
json.dump() / json.dumps(): To serialize a Python object into a JSON formatted stream or string.•
json.load() / json.loads(): To de-serialize a JSON formatted stream or string into a Python object.import json
data = {'name': 'John', 'age': 30}
json_string = json.dumps(data)
print(json_string)
{"name": "John", "age": 30}---
#81. What is the
os module used for?A: The
os module provides a way of using operating system-dependent functionality like reading or writing to the file system, interacting with environment variables, and managing directories.#82. What is monkey-patching?
A: Monkey-patching is a technique used to dynamically modify or extend code at runtime. For example, you can change the behavior of a function or a method in a third-party library without altering the original source code.
#83. What is a metaclass?
A: A metaclass is a "class of a class". It defines how a class behaves. A class is an instance of a metaclass. In Python,
type is the default metaclass. It's an advanced concept used for creating custom class behaviors.#84. What is the difference between
range() and xrange()?A: This is a Python 2 question.
• In Python 2,
range() created an actual list in memory, which was inefficient for very large ranges. xrange() created a generator-like object that yielded numbers on demand.• In Python 3, the old
range() was removed, and xrange() was renamed to range(). So, Python 3's range() behaves like Python 2's memory-efficient xrange().#85. What are some popular Python frameworks for web development?
A:
• Django: A high-level, "batteries-included" framework that encourages rapid development and clean, pragmatic design.
• Flask: A lightweight microframework that is simpler and more flexible, allowing developers to choose their own libraries and tools.
• FastAPI: A modern, high-performance web framework for building APIs with Python 3.7+ based on standard Python type hints.
---
Part 6: Coding Problems & Algorithms (Q86-100)
#86. Write a function to check if a string is a palindrome.
A: A palindrome reads the same forwards and backward. The easiest way is to compare the string with its reversed version.
def is_palindrome(s):
# Clean the string (optional, depends on requirements)
s = ''.join(filter(str.isalnum, s)).lower()
return s == s[::-1]
print(is_palindrome("A man, a plan, a canal: Panama"))
print(is_palindrome("racecar"))
print(is_palindrome("hello"))
True
True
False
#87. Write a Fibonacci sequence generator.
A: A generator is memory-efficient for this task.
❤1
def fibonacci_generator(n):
a, b = 0, 1
count = 0
while count < n:
yield a
a, b = b, a + b
count += 1
for num in fibonacci_generator(10):
print(num, end=' ')
0 1 1 2 3 5 8 13 21 34
#88. Solve the FizzBuzz problem.
A: Print numbers from 1 to n. But for multiples of three, print "Fizz" instead of the number, and for the multiples of five, print "Buzz". For numbers which are multiples of both three and five, print "FizzBuzz".
def fizzbuzz(n):
for i in range(1, n + 1):
if i % 3 == 0 and i % 5 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)
fizzbuzz(15)
#89. Find the factorial of a number using recursion.
A: The factorial of n is the product of all positive integers up to n.
def factorial(n):
if n < 0:
return "Factorial does not exist for negative numbers"
elif n == 0:
return 1
else:
return n * factorial(n - 1)
print(factorial(5))
120
#90. Reverse a string in Python.
A: The simplest and most Pythonic way is to use slicing.
my_string = "hello"
reversed_string = my_string[::-1]
print(reversed_string)
olleh
---
#91. Find the most frequent element in a list.
A: The
collections.Counter class is perfect for this.from collections import Counter
my_list = [1, 2, 3, 2, 4, 2, 5, 2]
count = Counter(my_list)
most_common_element = count.most_common(1)[0][0]
print(most_common_element)
2
#92. Check if two strings are anagrams.
A: Anagrams are words formed by rearranging the letters of another. If the sorted versions of the two strings are equal, they are anagrams.
def are_anagrams(s1, s2):
return sorted(s1) == sorted(s2)
print(are_anagrams("listen", "silent"))
print(are_anagrams("hello", "world"))
True
False
#93. Flatten a nested list.
A: This can be solved with recursion.
def flatten(nested_list):
flat_list = []
for item in nested_list:
if isinstance(item, list):
flat_list.extend(flatten(item))
else:
flat_list.append(item)
return flat_list
nested = [1, [2, 3], 4, [5, [6, 7]]]
print(flatten(nested))
[1, 2, 3, 4, 5, 6, 7]
#94. Find all pairs of an integer array whose sum is equal to a given number.
A: A hash set (or a dictionary) can be used to solve this in O(n) time.
def find_sum_pairs(arr, target_sum):
seen = set()
pairs = []
for num in arr:
complement = target_sum - num
if complement in seen:
pairs.append((complement, num))
seen.add(num)
return pairs
my_array = [2, 7, 4, 1, 5, 6]
print(find_sum_pairs(my_array, 8))
[(1, 7), (2, 6)]
#95. Write a simple decorator that logs the execution time of a function.
A: Use the
time module and wrap the function call.import time
def timer_decorator(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"Function {func.__name__} took {end_time - start_time:.4f} seconds to run.")
return result
return wrapper
@timer_decorator
def long_running_function():
time.sleep(1)
long_running_function()
Function long_running_function took 1.0010 seconds to run.
---
#96. Write a function that takes a list of numbers and returns a new list containing only the even numbers.
A: List comprehension is a great way to do this.
def filter_even_numbers(numbers):
return [num for num in numbers if num % 2 == 0]
my_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(filter_even_numbers(my_numbers))
[2, 4, 6, 8, 10]
#97. Explain what
* does when unpacking a list or tuple.A: The
* operator can be used to unpack an iterable into individual elements. It's often used for function arguments or in assignments.numbers = [1, 2, 3, 4, 5]
first, *middle, last = numbers
print(f"First: {first}")
print(f"Middle: {middle}")
print(f"Last: {last}")
First: 1
Middle: [2, 3, 4]
Last: 5
#98. Write a function to merge two sorted lists into a single sorted list.
A: You can simply concatenate them and sort, but a more efficient approach (O(n+m)) is to iterate through both lists simultaneously.
def merge_sorted_lists(list1, list2):
# The simple, Pythonic way
return sorted(list1 + list2)
l1 = [1, 3, 5]
l2 = [2, 4, 6]
print(merge_sorted_lists(l1, l2))
[1, 2, 3, 4, 5, 6]
#99. What will be the output of the following code?
A: This question tests understanding of mutable default arguments.
def my_func(item, my_list=[]):
my_list.append(item)
return my_list
print(my_func(1))
print(my_func(2))
print(my_func(3))
[1]
[1, 2]
[1, 2, 3]
The default list is created only once when the function is defined. It is then shared across all subsequent calls, leading to this surprising behavior. The correct way is to use
my_list=None as the default.#100. How would you count the occurrences of each word in a given text sentence?
A: The
collections.Counter is the ideal tool for this task.from collections import Counter
import re
sentence = "The quick brown fox jumps over the lazy dog dog"
# Pre-process: lowercase and split into words
words = re.findall(r'\w+', sentence.lower())
word_counts = Counter(words)
print(word_counts)
Counter({'the': 2, 'dog': 2, 'quick': 1, 'brown': 1, 'fox': 1, 'jumps': 1, 'over': 1, 'lazy': 1})━━━━━━━━━━━━━━━
By: @DataScience4 ✨
❤3
💡 Top 50 Operations for Text Processing in Python
I. Case & Whitespace Manipulation
• Convert to lowercase.
• Convert to uppercase.
• Capitalize the first letter of the string.
• Convert to title case (each word starts with a capital).
• Swap character case.
• Remove leading and trailing whitespace.
• Remove leading whitespace.
• Remove trailing whitespace.
II. Searching, Replacing & Counting
• Find the first index of a substring.
• Check if a string starts with a substring.
• Check if a string ends with a substring.
• Replace a substring with another.
• Count occurrences of a substring.
III. Splitting & Joining
• Split a string into a list of words.
• Join a list of strings into a single string.
• Split a string into lines.
• Partition a string at the first occurrence of a separator.
IV. Character & String Checks
• Check if all characters are alphabetic.
• Check if all characters are digits.
• Check if all characters are alphanumeric.
• Check if all characters are whitespace.
V. Regular Expressions (
• Find the first match of a pattern.
• Find all matches of a pattern.
• Substitute a pattern with a replacement string.
• Split a string by a regex pattern.
VI. Basic NLP - Tokenization & Cleaning
(Requires
• Sentence Tokenization.
• Word Tokenization.
• Remove punctuation.
• Remove stop words.
I. Case & Whitespace Manipulation
• Convert to lowercase.
text = "Hello World"
lower_text = text.lower()
• Convert to uppercase.
upper_text = text.upper()
• Capitalize the first letter of the string.
capitalized = "hello world".capitalize()
• Convert to title case (each word starts with a capital).
title_text = "hello world".title()
• Swap character case.
swapped = "Hello World".swapcase()
• Remove leading and trailing whitespace.
padded_text = " hello "
stripped_text = padded_text.strip()
• Remove leading whitespace.
left_stripped = padded_text.lstrip()
• Remove trailing whitespace.
right_stripped = padded_text.rstrip()
II. Searching, Replacing & Counting
• Find the first index of a substring.
index = "hello world".find("world") # Returns 6• Check if a string starts with a substring.
starts_with_hello = text.startswith("Hello") # True• Check if a string ends with a substring.
ends_with_world = text.endswith("World") # True• Replace a substring with another.
new_text = text.replace("World", "Python")• Count occurrences of a substring.
count = "hello hello".count("hello") # Returns 2III. Splitting & Joining
• Split a string into a list of words.
words = text.split(' ') # ['Hello', 'World']• Join a list of strings into a single string.
word_list = ["Hello", "Python"]
joined_text = " ".join(word_list)
• Split a string into lines.
multiline = "line one\nline two"
lines = multiline.splitlines()
• Partition a string at the first occurrence of a separator.
parts = "user@domain.com".partition('@') # ('user', '@', 'domain.com')IV. Character & String Checks
• Check if all characters are alphabetic.
"HelloWorld".isalpha() # True
• Check if all characters are digits.
"12345".isdigit() # True
• Check if all characters are alphanumeric.
"Python3".isalnum() # True
• Check if all characters are whitespace.
" \t\n".isspace() # True
V. Regular Expressions (
re module)• Find the first match of a pattern.
import re
match = re.search(r'\d+', 'There are 10 apples.')
• Find all matches of a pattern.
numbers = re.findall(r'\d+', '10 apples and 20 oranges')
• Substitute a pattern with a replacement string.
no_digits = re.sub(r'\d', '#', 'My pin is 1234')
• Split a string by a regex pattern.
items = re.split(r'[,;]', 'apple,banana;cherry')
VI. Basic NLP - Tokenization & Cleaning
(Requires
pip install nltk)• Sentence Tokenization.
from nltk.tokenize import sent_tokenize
# nltk.download('punkt') # Run once
text = "Hello Mr. Smith. How are you?"
sentences = sent_tokenize(text)
• Word Tokenization.
from nltk.tokenize import word_tokenize
words = word_tokenize("Hello, how are you?")
• Remove punctuation.
import string
text = "A string with... punctuation!"
clean = text.translate(str.maketrans('', '', string.punctuation))
• Remove stop words.
from nltk.corpus import stopwords
# nltk.download('stopwords') # Run once
stop_words = set(stopwords.words('english'))
filtered = [w for w in words if not w.lower() in stop_words]
VII. Word Normalization (Stemming & Lemmatization)
• Stemming (reduce words to their root form).
from nltk.stem import PorterStemmer
ps = PorterStemmer()
stemmed = ps.stem("running") # 'run'
• Lemmatization (reduce words to their dictionary form).
from nltk.stem import WordNetLemmatizer
# nltk.download('wordnet') # Run once
lemmatizer = WordNetLemmatizer()
lemma = lemmatizer.lemmatize("better", pos="a") # 'good'
VIII. Advanced NLP Analysis
(Requires
pip install spacy and python -m spacy download en_core_web_sm)• Part-of-Speech (POS) Tagging.
import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("Apple is looking at buying a U.K. startup.")
for token in doc: print(token.text, token.pos_)
• Named Entity Recognition (NER).
for ent in doc.ents:
print(ent.text, ent.label_) # Apple ORG, U.K. GPE
• Get word frequency distribution.
from nltk.probability import FreqDist
fdist = FreqDist(word_tokenize("this is a test this is only a test"))
IX. Text Formatting & Encoding
• Format strings with f-strings.
name = "Alice"
age = 30
message = f"Name: {name}, Age: {age}"
• Pad a string with leading zeros.
number = "42".zfill(5) # '00042'
• Encode a string to bytes.
byte_string = "hello".encode('utf-8')• Decode bytes to a string.
original_string = byte_string.decode('utf-8')X. Text Vectorization
(Requires
pip install scikit-learn)• Create a Bag-of-Words (BoW) model.
from sklearn.feature_extraction.text import CountVectorizer
corpus = ["This is the first document.", "This is the second document."]
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(corpus)
• Get feature names (the vocabulary).
print(vectorizer.get_feature_names_out())
• Create a TF-IDF model.
from sklearn.feature_extraction.text import TfidfVectorizer
tfidf_vectorizer = TfidfVectorizer()
tfidf_matrix = tfidf_vectorizer.fit_transform(corpus)
XI. More String Utilities
• Center a string within a width.
centered = "Hello".center(20, '-') # '-------Hello--------'
• Check if a string is in title case.
"This Is A Title".istitle() # True
• Find the highest index of a substring.
"test test".rfind("test") # Returns 5• Split from the right.
"path/to/file.txt".rsplit('/', 1) # ['path/to', 'file.txt']• Create a character translation table.
table = str.maketrans('aeiou', '12345')
vowels_to_num = "hello".translate(table) # 'h2ll4'• Remove a specific prefix.
"TestCase".removeprefix("Test") # 'Case'• Remove a specific suffix.
"filename.txt".removesuffix(".txt") # 'filename'• Check for unicode decimal characters.
"½".isdecimal() # False
"123".isdecimal() # True
• Check for unicode numeric characters.
"½".isnumeric() # True
"²".isnumeric() # True
#Python #TextProcessing #NLP #RegEx #NLTK
━━━━━━━━━━━━━━━
By: @DataScience4 ✨
✨ LlamaIndex | AI Coding Tools ✨
📖 A high-level framework for building RAG and agentic applications.
🏷️ #Python
📖 A high-level framework for building RAG and agentic applications.
🏷️ #Python
✨ embedding | AI Coding Glossary ✨
📖 A learned vector representation that maps discrete items, such as words, sentences, documents, images, or users, into a continuous space.
🏷️ #Python
📖 A learned vector representation that maps discrete items, such as words, sentences, documents, images, or users, into a continuous space.
🏷️ #Python
✨ vector database | AI Coding Glossary ✨
📖 A data system optimized for storing and retrieving embedding vectors.
🏷️ #Python
📖 A data system optimized for storing and retrieving embedding vectors.
🏷️ #Python
✨ Quiz: A Close Look at a FastAPI Example Application ✨
📖 Practice FastAPI basics with path parameters, request bodies, async endpoints, and CORS. Build confidence to design and test simple Python web APIs.
🏷️ #intermediate #api #web-dev
📖 Practice FastAPI basics with path parameters, request bodies, async endpoints, and CORS. Build confidence to design and test simple Python web APIs.
🏷️ #intermediate #api #web-dev
✨ A Close Look at a FastAPI Example Application ✨
📖 Set up an example FastAPI app, add path and query parameters, and handle CRUD operations with Pydantic for clean, validated endpoints.
🏷️ #intermediate #api #web-dev
📖 Set up an example FastAPI app, add path and query parameters, and handle CRUD operations with Pydantic for clean, validated endpoints.
🏷️ #intermediate #api #web-dev
Please open Telegram to view this post
VIEW IN TELEGRAM
💡 Top 50 FastAPI Operations in Python
I. Basic App & Routing
• Create a FastAPI instance.
• Define a GET endpoint.
• Define a POST endpoint.
• Define a path parameter.
• Define a query parameter.
• Define an optional query parameter.
II. Request Body & Pydantic Models
• Create a Pydantic model for request body.
• Use a Pydantic model in a POST request.
• Use a Pydantic model with a path parameter.
• Define a nested Pydantic model.
III. Data Validation & Metadata
• Add validation to a query parameter.
• Add validation to a path parameter.
• Add metadata (title, description) to a parameter.
• Provide an example for a
• Use an alias for a model field.
IV. Response Models & Status Codes
• Set a response status code.
• Use
• Exclude fields from
• Return a direct
V. Dependencies
I. Basic App & Routing
• Create a FastAPI instance.
from fastapi import FastAPI
app = FastAPI()
• Define a GET endpoint.
@app.get("/")
def read_root():
return {"Hello": "World"}• Define a POST endpoint.
@app.post("/items/")
def create_item(item: dict):
return item• Define a path parameter.
@app.get("/items/{item_id}")
def read_item(item_id: int):
return {"item_id": item_id}• Define a query parameter.
@app.get("/search/")
def search_items(q: str):
return {"query": q}• Define an optional query parameter.
from typing import Optional
@app.get("/list/")
def list_items(skip: int = 0, limit: Optional[int] = None):
return {"skip": skip, "limit": limit}
II. Request Body & Pydantic Models
• Create a Pydantic model for request body.
from pydantic import BaseModel
class Item(BaseModel):
name: str
price: float
• Use a Pydantic model in a POST request.
@app.post("/items/")
def create_item(item: Item):
return item• Use a Pydantic model with a path parameter.
@app.put("/items/{item_id}")
def update_item(item_id: int, item: Item):
return {"item_id": item_id, **item.dict()}• Define a nested Pydantic model.
class User(BaseModel):
username: str
class FullItem(Item):
owner: User
III. Data Validation & Metadata
• Add validation to a query parameter.
from fastapi import Query
@app.get("/items/")
def read_items(q: str = Query(..., min_length=3, max_length=50)):
return {"q": q}
• Add validation to a path parameter.
from fastapi import Path
@app.get("/users/{user_id}")
def read_user(user_id: int = Path(..., gt=0, le=1000)):
return {"user_id": user_id}
• Add metadata (title, description) to a parameter.
q: str = Query(None, title="Search Query", description="Query string")
• Provide an example for a
Body field.from fastapi import Body
item: Item = Body(..., example={"name": "Foo", "price": 35.4})
• Use an alias for a model field.
from pydantic import Field
class Item(BaseModel):
item_name: str = Field(..., alias="itemName")
IV. Response Models & Status Codes
• Set a response status code.
from fastapi import status
@app.post("/items/", status_code=status.HTTP_201_CREATED)
def create_item(item: Item):
return item
• Use
response_model to filter output.class ItemOut(BaseModel):
name: str
@app.post("/items/", response_model=ItemOut)
def create_item(item: Item):
return item
• Exclude fields from
response_model.# Returns all fields from Item model except 'price'
@app.get("/items/{item_id}", response_model=Item, response_model_exclude={"price"})
• Return a direct
Response.from fastapi import Response
@app.get("/legacy/")
def get_legacy_data():
return Response(content="<data>some legacy xml</data>", media_type="application/xml")
V. Dependencies
• Define a simple function dependency.
• Inject a dependency into an endpoint.
• Create a dependency with
• Use a class as a dependency.
VI. Security
• Setup OAuth2 password flow.
• Protect an endpoint with a security dependency.
• Get the current authenticated user.
VII. Advanced Routing
• Create an
• Include a router in the main app.
• Add tags to endpoints for documentation.
• Add a summary and description to an endpoint.
• Deprecate an endpoint.
VIII. Middleware, Events & Background Tasks
• Create an app startup event.
• Create an app shutdown event.
• Add custom middleware.
• Define a background task.
• Add a background task to an endpoint.
IX. Handling Forms, Files & Cookies
• Handle form data.
• Handle file uploads.
• Handle
from fastapi import Depends
async def common_parameters(q: Optional[str] = None):
return {"q": q}
• Inject a dependency into an endpoint.
@app.get("/users/")
async def read_users(commons: dict = Depends(common_parameters)):
return commons• Create a dependency with
yield (for setup/teardown).async def get_db():
db = DBSession()
try:
yield db
finally:
db.close()
• Use a class as a dependency.
class CommonQueryParams:
def __init__(self, q: Optional[str] = None):
self.q = q
@app.get("/search/")
async def search(commons: CommonQueryParams = Depends()):
return commons
VI. Security
• Setup OAuth2 password flow.
from fastapi.security import OAuth2PasswordBearer
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
• Protect an endpoint with a security dependency.
@app.get("/users/me")
async def read_users_me(token: str = Depends(oauth2_scheme)):
return {"token": token}• Get the current authenticated user.
async def get_current_user(token: str = Depends(oauth2_scheme)):
# logic to get user from token
return user
@app.get("/users/me")
async def read_users_me(current_user: User = Depends(get_current_user)):
return current_user
VII. Advanced Routing
• Create an
APIRouter.from fastapi import APIRouter
router = APIRouter()
@router.get("/users/")
def get_users():
return [{"username": "user1"}]
• Include a router in the main app.
app.include_router(router, prefix="/api/v1", tags=["users"])
• Add tags to endpoints for documentation.
@app.get("/items/", tags=["items"])• Add a summary and description to an endpoint.
@app.get("/", summary="Root Endpoint", description="Returns a welcome message.")• Deprecate an endpoint.
@app.get("/old-path", deprecated=True)VIII. Middleware, Events & Background Tasks
• Create an app startup event.
@app.on_event("startup")
async def startup_event():
print("Application startup")• Create an app shutdown event.
@app.on_event("shutdown")
def shutdown_event():
print("Application shutdown")• Add custom middleware.
from fastapi import Request
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
response = await call_next(request)
return response
• Define a background task.
from fastapi import BackgroundTasks
def write_notification(email: str, message=""):
# send email logic
pass
• Add a background task to an endpoint.
@app.post("/send/{email}")
def send_notification(email: str, background_tasks: BackgroundTasks):
background_tasks.add_task(write_notification, email, message="some notification")
return {"message": "Notification sent"}IX. Handling Forms, Files & Cookies
• Handle form data.
from fastapi import Form
@app.post("/login/")
def login(username: str = Form(...), password: str = Form(...)):
return {"username": username}
• Handle file uploads.
from fastapi import File, UploadFile
@app.post("/files/")
async def create_file(file: bytes = File(...)):
return {"file_size": len(file)}
• Handle
UploadFile (better for large files).❤1