Essential Python Coding Questions for All Interview Stages

Tech AcademyTech Academy
40 min read

1. Reverse a String

Problem:
Write a function to reverse a string.

Function Signature:

def reverse_string(s: str) -> str:
    return s[::-1]  # Uses slicing to reverse the string

# Example usage
print(reverse_string("hello"))  # Output: "olleh"

The function reverse_string(s: str) -> str is a Python function that takes a string s as input and returns its reversed version.

Explanation:

  • s: str → This specifies that the function takes a string as an argument.

  • -> str → This indicates that the function returns a string.

How It Works:

  • s[::-1] is a slicing technique where:

    • [::-1] means "take the string from start to end with a step of -1," effectively reversing it.

This method is efficient and concise for reversing strings in Python.

2. Find the Second Largest Number

Problem:
Given a list of numbers, find the second largest number.

Function Signature:

from typing import List

def second_largest(nums: List[int]) -> int:
    if len(nums) < 2:
        raise ValueError("List must contain at least two distinct elements")

    first, second = float('-inf'), float('-inf')

    for num in nums:
        if num > first:
            second, first = first, num  # Update both first and second
        elif first > num > second:
            second = num  # Update second if it's smaller than first but greater than current second

    if second == float('-inf'):
        raise ValueError("List must contain at least two distinct elements")

    return second

# Example usage
print(second_largest([10, 20, 4, 45, 99]))  # Output: 45

The function second_largest(nums: List[int]) -> int is intended to find and return the second-largest number in a given list of integers.

Explanation:

  • nums: List[int] → The function takes a list of integers as input.

  • -> int → The function returns an integer, which is the second-largest number in the list.

How It Works:

  1. Initialize first and second with negative infinity (-inf) to track the largest and second-largest numbers.

  2. Iterate through the list:

    • If a number is greater than first, update second with first and first with the current number.

    • If a number is smaller than first but greater than second, update second.

  3. If second remains -inf, it means there was no valid second-largest number, so raise an exception.

Key Points:

  • num is declared implicitly inside the loop.

  • Python automatically assigns num the value of each element in nums as it loops.

  • The scope of num is within the loop unless used outside.

If you try to access num before the loop starts, it won’t exist. But after the loop, it will retain the last value assigned.


3. Check if a String is a Palindrome

Problem:
Check if the given string is a palindrome (reads the same forward and backward).

Function Signature:

def is_palindrome(s: str) -> bool:
    return s == s[::-1]  # Compare the string with its reverse

# Example usage
print(is_palindrome("racecar"))  # Output: True
print(is_palindrome("hello"))    # Output: False

Explanation:

  • s[::-1] reverses the string.

  • The function returns True if the original string is equal to its reversed version; otherwise, it returns False.

Edge Cases:

  1. Empty string ("") → Considered a palindrome (True).

  2. Single character ("a") → Always a palindrome (True).

  3. Case sensitivity"Racecar" is different from "racecar", so may need .lower().

  4. Ignoring non-alphanumeric characters → Use filter(str.isalnum, s) if needed.

Here's an enhanced version of the is_palindrome function that:

  • Ignores spaces

  • Ignores case sensitivity

  • Ignores non-alphanumeric characters (like punctuation)

Updated Function:

import re

def is_palindrome(s: str) -> bool:
    # Remove non-alphanumeric characters and convert to lowercase
    cleaned_s = ''.join(filter(str.isalnum, s)).lower()

    # Check if the cleaned string is a palindrome
    return cleaned_s == cleaned_s[::-1]

# Example usage
print(is_palindrome("A man, a plan, a canal: Panama"))  # Output: True
print(is_palindrome("No lemon, no melon!"))            # Output: True
print(is_palindrome("Hello, World!"))                  # Output: False

Explanation:

  1. filter(str.isalnum, s):

    • The filter() function iterates through s, keeping only characters that pass the str.isalnum check.

    • str.isalnum() returns True for letters and digits, filtering out spaces, punctuation, and symbols.

Example:

    s = "A man, a plan, a canal: Panama"
    print(''.join(filter(str.isalnum, s)))  # Output: "AmanaplanacanalPanama"
  1. .lower():

    • Converts the string to lowercase to ensure case insensitivity.

    • "Racecar" and "racecar" should be treated as the same word.

  2. [::-1]:

    • This reverses the string and checks for equality.

Key Points ::

1. filter(str.isalnum, s)

  • filter(str.isalnum, s) keeps only alphanumeric characters from s, removing spaces and punctuation.

2. ''.join(...)

  • ''.join(...) combines the filtered characters into a single string without any separator.

  • The '' (empty string) is the separator.

    Example:

      s = "Hello, World!"
      cleaned_s = ''.join(filter(str.isalnum, s))
      print(cleaned_s)  # Output: "HelloWorld"
    

    If we used '-'.join(...), the output would be "H-e-l-l-o-W-o-r-l-d".

3. .lower()

  • Converts the cleaned string to lowercase.

4. Count the Occurrences of Each Character

Problem:
Given a string, count the occurrence of each character.

Function Signature:

from collections import Counter

def char_count(s: str) -> Dict[str, int]:
    return dict(Counter(s))

print(char_count("hello"))  # Output: {'h': 1, 'e': 1, 'l': 2, 'o': 1}

Counter(s) automatically creates a dictionary of character counts.


5. Find the Missing Number in a List

Problem:
Given a list containing numbers from 1 to N, with one missing number, find the missing number.

Function Signature:

from typing import List

def missing_number(arr: List[int], n: int) -> int:
    total_sum = n * (n + 1) // 2  # Sum of first n natural numbers
    arr_sum = sum(arr)  # Sum of elements in the given array
    return total_sum - arr_sum  # The missing number

# Example usage
print(missing_number([1, 2, 3, 5], 5))  # Output: 4
print(missing_number([1, 2, 4, 5, 6], 6))  # Output: 3

Explanation

  1. Formula for the sum of first n natural numbers:

    {total_sum} = {n (n + 1)}/{2}

    • Example: If n = 5, sum should be 1 + 2 + 3 + 4 + 5 = 15.
  2. Find the sum of given elements (sum(arr))

    • Example: If arr = [1, 2, 3, 5], sum is 1 + 2 + 3 + 5 = 11.
  3. Compute the missing number

    • total_sum - sum(arr) gives the missing number.

    • 15 - 11 = 4, so 4 is the missing number.


6. Check if Two Strings are Anagrams

Problem:
Check if two given strings are anagrams (contain the same characters in a different order).

Function Signature:

def is_anagram(s1: str, s2: str) -> bool:
    return sorted(s1) == sorted(s2)  # Sort both strings and compare

# Example usage
print(is_anagram("listen", "silent"))  # Output: True
print(is_anagram("hello", "world"))    # Output: False

7. Find the Longest Substring Without Repeating Characters

Problem:
Given a string, find the length of the longest substring without repeating characters.

Function Signature:

def longest_unique_substring(s: str) -> int:
    char_index = {}  # Stores the last seen index of characters
    max_length = 0
    start = 0  # Left boundary of the window

    for end, char in enumerate(s):
        if char in char_index and char_index[char] >= start:
            start = char_index[char] + 1  # Move the start to avoid repetition

        char_index[char] = end  # Update last seen index of character
        max_length = max(max_length, end - start + 1)  # Update max length

    return max_length

# Example usage
print(longest_unique_substring("abcabcbb"))  # Output: 3 ("abc")
print(longest_unique_substring("bbbbb"))    # Output: 1 ("b")
print(longest_unique_substring("pwwkew"))   # Output: 3 ("wke")

Explanation (Sliding Window + HashMap)

  1. Use a dictionary (char_index) to track the last seen index of each character.

  2. Expand the window (end pointer moves right):

    • If the character is already in the dictionary and inside the window, move start to char_index[char] + 1 (avoiding repetition).
  3. Update max length at each step.

8.Merge two Sorted Lists

Problem:
Given two sorted lists, merge them into one sorted list.

Function Signature:

from typing import List

def merge_sorted_lists(lst1: List[int], lst2: List[int]) -> List[int]:
    merged = []
    i, j = 0, 0  # Pointers for both lists

    # Merge both lists while elements remain in both
    while i < len(lst1) and j < len(lst2):
        if lst1[i] < lst2[j]:
            merged.append(lst1[i])
            i += 1
        else:
            merged.append(lst2[j])
            j += 1

    # Add remaining elements from lst1
    while i < len(lst1):
        merged.append(lst1[i])
        i += 1

    # Add remaining elements from lst2
    while j < len(lst2):
        merged.append(lst2[j])
        j += 1

    return merged

# Example usage
print(merge_sorted_lists([1, 3, 5], [2, 4, 6]))  # Output: [1, 2, 3, 4, 5, 6]
print(merge_sorted_lists([1, 2, 7], [3, 5, 6]))  # Output: [1, 2, 3, 5, 6, 7]

Explanation

  1. Use two pointers (i, j) to traverse both lists.

  2. Compare elements from both lists:

    • Append the smaller element to merged[].

    • Move the pointer in the list where the element was taken from.

  3. Append remaining elements from lst1 or lst2 after the loop.


Alternative Using heapq.merge() (Python Built-in)

import heapq

def merge_sorted_lists(lst1: List[int], lst2: List[int]) -> List[int]:
    return list(heapq.merge(lst1, lst2))  # Efficient merging of sorted lists

print(merge_sorted_lists([1, 3, 5], [2, 4, 6]))  # Output: [1, 2, 3, 4, 5, 6]
  • Uses a heap-based approach for merging efficiently.

9. Sum of Digits of a Number

Problem:
Write a function that takes an integer and returns the sum of its digits.

def sum_of_digits(n: int) -> int:
    return sum(int(digit) for digit in str(n))

# Example usage:
print(sum_of_digits(1234))  # Output: 10

10. Check if a Number is Prime

Problem:
Write a function that checks if a given number is prime.

def is_prime(n: int) -> bool:
    if n < 2:
        return False
    for i in range(2, int(n ** 0.5) + 1):
        if n % i == 0:
            return False
    return True

# Example usage:
print(is_prime(11))  # Output: True
print(is_prime(10))  # Output: False

11. Find Factorial of a Number

Problem:
Write a function that calculates the factorial of a given number.

def factorial(n: int) -> int:
    if n == 0 or n == 1:
        return 1
    result = 1
    for i in range(2, n + 1):
        result *= i
    return result

# Example usage:
print(factorial(5))  # Output: 120

12. Check if a Year is a Leap Year

Problem:
Write a function that checks if a given year is a leap year.

def is_leap_year(year: int) -> bool:
    return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)

# Example usage:
print(is_leap_year(2024))  # Output: True
print(is_leap_year(1900))  # Output: False

13. Find the Largest Element in a List

Problem:
Write a function to find the largest element in a list.

def find_max(lst: list) -> int:
    return max(lst)

# Example usage:
print(find_max([10, 20, 30, 40, 50]))  # Output: 50

14. Remove Duplicates from a List

Problem:
Write a function to remove duplicates from a list while maintaining the order.

def remove_duplicates(lst: list) -> list:
    seen = set()
    return [x for x in lst if not (x in seen or seen.add(x))]

# Example usage:
print(remove_duplicates([1, 2, 2, 3, 4, 4, 5]))  # Output: [1, 2, 3, 4, 5]

15. Find Common Elements in Two Lists

Problem:
Write a function to find the common elements in two lists.

def common_elements(lst1: list, lst2: list) -> list:
    return list(set(lst1) & set(lst2))

# Example usage:
print(common_elements([1, 2, 3, 4], [3, 4, 5, 6]))  # Output: [3, 4]

16. Rotate an Array to the Right by K Places

Problem:
Write a function to rotate a list to the right by k places.

def rotate_right(lst: list, k: int) -> list:
    k = k % len(lst)  # Ensure k is within bounds
    return lst[-k:] + lst[:-k]

# Example usage:
print(rotate_right([1, 2, 3, 4, 5], 2))  # Output: [4, 5, 1, 2, 3]

17. Check if a Sentence is a Pangram

Problem:
Write a function to check if a sentence contains all letters of the English alphabet.

import string

def is_pangram(s: str) -> bool:
    return set(string.ascii_lowercase).issubset(set(s.lower()))

# Example usage:
print(is_pangram("The quick brown fox jumps over the lazy dog"))  # Output: True
print(is_pangram("Hello World"))  # Output: False

18. Count the Number of Words in a Sentence

Problem:
Write a function to count the number of words in a given sentence.

def word_count(s: str) -> int:
    return len(s.split())

# Example usage:
print(word_count("Python is a great programming language"))  # Output: 6

19. Check if a List is Sorted

Problem:
Write a function to check if a list is sorted in ascending order.

def is_sorted(lst: list) -> bool:
    return lst == sorted(lst)

# Example usage:
print(is_sorted([1, 2, 3, 4, 5]))  # Output: True
print(is_sorted([1, 3, 2, 4, 5]))  # Output: False

20. Find the Missing Number in an Array

Problem:
Given a list of numbers from 1 to N with one number missing, find the missing number.

def missing_number(arr: list, n: int) -> int:
    expected_sum = n * (n + 1) // 2
    actual_sum = sum(arr)
    return expected_sum - actual_sum

# Example usage:
print(missing_number([1, 2, 4, 5, 6], 6))  # Output: 3

21. Find the Intersection of Two Sorted Arrays

Problem:
Find the common elements between two sorted arrays.

def intersect_sorted(arr1: list, arr2: list) -> list:
    i, j = 0, 0
    result = []
    while i < len(arr1) and j < len(arr2):
        if arr1[i] == arr2[j]:
            result.append(arr1[i])
            i += 1
            j += 1
        elif arr1[i] < arr2[j]:
            i += 1
        else:
            j += 1
    return result

# Example usage:
print(intersect_sorted([1, 2, 3, 5], [2, 3, 4, 5]))  # Output: [2, 3, 5]

22. Find the First Non-Repeating Character in a String

Problem:
Given a string, find the first character that appears only once.

from collections import Counter

def first_unique_char(s: str) -> str:
    char_count = Counter(s)
    for char in s:
        if char_count[char] == 1:
            return char
    return None  # If no unique character found

# Example usage:
print(first_unique_char("swiss"))  # Output: "w"

23. Find the Maximum Subarray Sum (Kadane's Algorithm)

Problem:
Find the contiguous subarray with the maximum sum.

def max_subarray_sum(arr: list) -> int:
    max_sum = float('-inf')
    current_sum = 0
    for num in arr:
        current_sum = max(num, current_sum + num)
        max_sum = max(max_sum, current_sum)
    return max_sum

# Example usage:
print(max_subarray_sum([-2,1,-3,4,-1,2,1,-5,4]))  # Output: 6

24. Reverse the Words in a String

Problem:
Given a sentence, reverse the order of words.

def reverse_words(sentence: str) -> str:
    return ' '.join(sentence.split()[::-1])

# Example usage:
print(reverse_words("Hello World Python"))  # Output: "Python World Hello"

25. Find All Pairs in an Array that Sum to a Given Number

Problem:
Find all pairs in an array whose sum equals a given target.

def find_pairs(arr: list, target: int) -> list:
    seen = set()
    result = []
    for num in arr:
        diff = target - num
        if diff in seen:
            result.append((diff, num))
        seen.add(num)
    return result

# Example usage:
print(find_pairs([1, 2, 3, 4, 5], 6))  # Output: [(2, 4), (1, 5)]

26. Count Vowels and Consonants in a String

Problem:
Write a function to count vowels and consonants in a given string.

def count_vowels_consonants(s: str) -> dict:
    vowels = "aeiouAEIOU"
    v_count = sum(1 for char in s if char in vowels)
    c_count = sum(1 for char in s if char.isalpha() and char not in vowels)
    return {"vowels": v_count, "consonants": c_count}

# Example usage:
print(count_vowels_consonants("hello world"))  # Output: {'vowels': 3, 'consonants': 7}

27. Convert Roman Numerals to Integer

Problem:
Convert a given Roman numeral to an integer.

def roman_to_integer(s: str) -> int:
    roman_dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
    total = 0
    prev_value = 0

    for char in s[::-1]:  # Reverse iterate
        value = roman_dict[char]
        if value < prev_value:
            total -= value
        else:
            total += value
        prev_value = value

    return total

# Example usage:
print(roman_to_integer("IX"))  # Output: 9
print(roman_to_integer("MCMXCIV"))  # Output: 1994

28. Find the Longest Common Prefix in a List of Strings

Problem:
Find the longest common prefix in a list of words.

def longest_common_prefix(words: list) -> str:
    if not words:
        return ""

    prefix = words[0]
    for word in words[1:]:
        while not word.startswith(prefix):
            prefix = prefix[:-1]
            if not prefix:
                return ""

    return prefix

# Example usage:
print(longest_common_prefix(["flower", "flow", "flight"]))  # Output: "fl"
print(longest_common_prefix(["dog", "racecar", "car"]))  # Output: ""

29. Find the Kth Largest Element in an Array

Problem:
Find the kth largest element in an unsorted array.

import heapq

def kth_largest(arr: list, k: int) -> int:
    return heapq.nlargest(k, arr)[-1]

# Example usage:
print(kth_largest([3, 2, 1, 5, 6, 4], 2))  # Output: 5

30. Find the Sum of All Elements in a List

Problem:
Write a function that takes a list of numbers and returns the sum of all elements.

def sum_of_list(lst: list) -> int:
    return sum(lst)

# Example usage:
print(sum_of_list([1, 2, 3, 4, 5]))  # Output: 15

31. Find the Smallest Element in a List

Problem:
Write a function to find the smallest element in a list.

def find_min(lst: list) -> int:
    return min(lst)

# Example usage:
print(find_min([10, 20, 30, 5, 50]))  # Output: 5

32. Find the Fibonacci Sequence Up to N Terms

Problem:
Write a function to generate the Fibonacci sequence up to n terms.

def fibonacci(n: int) -> list:
    fib_seq = [0, 1]
    for _ in range(n - 2):
        fib_seq.append(fib_seq[-1] + fib_seq[-2])
    return fib_seq[:n]

# Example usage:
print(fibonacci(7))  # Output: [0, 1, 1, 2, 3, 5, 8]

33. Convert Celsius to Fahrenheit

Problem:
Write a function that converts a temperature from Celsius to Fahrenheit.

def celsius_to_fahrenheit(celsius: float) -> float:
    return (celsius * 9/5) + 32

# Example usage:
print(celsius_to_fahrenheit(25))  # Output: 77.0

34. Reverse a List

Problem:
Write a function that takes a list and returns it reversed.

def reverse_list(lst: list) -> list:
    return lst[::-1]

# Example usage:
print(reverse_list([1, 2, 3, 4, 5]))  # Output: [5, 4, 3, 2, 1]

35. Count Vowels in a String

Problem:
Write a function to count the number of vowels (a, e, i, o, u) in a string.

def count_vowels(s: str) -> int:
    return sum(1 for char in s.lower() if char in "aeiou")

# Example usage:
print(count_vowels("Hello World"))  # Output: 3

36. Find the Intersection of Two Lists

Problem:
Write a function that finds the common elements between two lists.

def list_intersection(lst1: list, lst2: list) -> list:
    return list(set(lst1) & set(lst2))

# Example usage:
print(list_intersection([1, 2, 3, 4], [3, 4, 5, 6]))  # Output: [3, 4]

37. Find the Union of Two Lists

Problem:
Write a function that returns the union of two lists (without duplicates).

def list_union(lst1: list, lst2: list) -> list:
    return list(set(lst1) | set(lst2))

# Example usage:
print(list_union([1, 2, 3], [3, 4, 5]))  # Output: [1, 2, 3, 4, 5]

38. Find the GCD (Greatest Common Divisor) of Two Numbers

Problem:
Write a function to compute the greatest common divisor (GCD) of two numbers.

import math

def find_gcd(a: int, b: int) -> int:
    return math.gcd(a, b)

# Example usage:
print(find_gcd(48, 18))  # Output: 6

39. Check if a String is an Isogram

Problem:
An isogram is a word where no letter appears more than once. Write a function to check if a word is an isogram.

def is_isogram(s: str) -> bool:
    return len(s) == len(set(s.lower()))

# Example usage:
print(is_isogram("machine"))  # Output: True
print(is_isogram("programming"))  # Output: False

40. Find the Frequency of Each Element in a List

Problem:
Given a list of numbers, count the frequency of each unique element.

from collections import Counter

def frequency_count(lst: list) -> dict:
    return dict(Counter(lst))

# Example usage:
print(frequency_count([1, 2, 2, 3, 3, 3, 4, 4, 4, 4]))  
# Output: {1: 1, 2: 2, 3: 3, 4: 4}

41. Reverse a Linked List

Problem:
Reverse a singly linked list.

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def reverse_linked_list(head: ListNode) -> ListNode:
    prev, current = None, head
    while current:
        next_node = current.next
        current.next = prev
        prev = current
        current = next_node
    return prev

# Example usage:
head = ListNode(1, ListNode(2, ListNode(3, ListNode(4))))
new_head = reverse_linked_list(head)
while new_head:
    print(new_head.val, end=" ")  # Output: 4 3 2 1
    new_head = new_head.next

42. Implement a Stack using a List

Problem:
Implement a stack with push, pop, and peek operations.

class Stack:
    def __init__(self):
        self.stack = []

    def push(self, value):
        self.stack.append(value)

    def pop(self):
        return self.stack.pop() if self.stack else None

    def peek(self):
        return self.stack[-1] if self.stack else None

# Example usage:
s = Stack()
s.push(10)
s.push(20)
print(s.pop())  # Output: 20
print(s.peek())  # Output: 10

43. Implement a Queue using a List

Problem:
Implement a queue with enqueue, dequeue, and front operations.

class Queue:
    def __init__(self):
        self.queue = []

    def enqueue(self, value):
        self.queue.append(value)

    def dequeue(self):
        return self.queue.pop(0) if self.queue else None

    def front(self):
        return self.queue[0] if self.queue else None

# Example usage:
q = Queue()
q.enqueue(5)
q.enqueue(10)
print(q.dequeue())  # Output: 5
print(q.front())  # Output: 10

44. Find the GCD of Two Numbers

Problem:
Find the Greatest Common Divisor (GCD) of two numbers.

import math

def gcd(a: int, b: int) -> int:
    return math.gcd(a, b)

# Example usage:
print(gcd(54, 24))  # Output: 6

45. Find the LCM of Two Numbers

Problem:
Find the Least Common Multiple (LCM) of two numbers.

def lcm(a: int, b: int) -> int:
    return abs(a * b) // math.gcd(a, b)

# Example usage:
print(lcm(12, 18))  # Output: 36

46. Implement a Binary Search Algorithm

Problem:
Implement binary search to find a target in a sorted list.

def binary_search(arr: list, target: int) -> int:
    left, right = 0, len(arr) - 1
    while left <= right:
        mid = (left + right) // 2
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    return -1  # Not found

# Example usage:
print(binary_search([1, 2, 3, 4, 5, 6], 4))  # Output: 3

47. Check if Two Strings are Rotations of Each Other

Problem:
Check if one string is a rotation of another.

def are_rotations(s1: str, s2: str) -> bool:
    return len(s1) == len(s2) and s1 in s2 + s2

# Example usage:
print(are_rotations("abcde", "cdeab"))  # Output: True
print(are_rotations("abc", "bca"))  # Output: True
print(are_rotations("abc", "bac"))  # Output: False

48. Check if a String has Balanced Parentheses

Problem:
Check if a string containing parentheses is balanced.

def is_balanced(s: str) -> bool:
    stack = []
    pairs = {')': '(', '}': '{', ']': '['}

    for char in s:
        if char in "({[":
            stack.append(char)
        elif char in ")}]":
            if not stack or stack.pop() != pairs[char]:
                return False
    return not stack

# Example usage:
print(is_balanced("{[()]}"))  # Output: True
print(is_balanced("{[(])}"))  # Output: False

49. Find the Most Frequent Element in a List

Problem:
Find the element that occurs most frequently in a list.

from collections import Counter

def most_frequent(lst: list) -> int:
    return Counter(lst).most_common(1)[0][0]

# Example usage:
print(most_frequent([1, 3, 2, 3, 4, 3, 5, 3]))  # Output: 3

50. Generate Fibonacci Sequence up to N Terms

Problem:
Generate the first N Fibonacci numbers.

def fibonacci(n: int) -> list:
    fib = [0, 1]
    for _ in range(n - 2):
        fib.append(fib[-1] + fib[-2])
    return fib[:n]

# Example usage:
print(fibonacci(10))  # Output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

51. Extract Emails from a Text File

Problem:
Write a function that reads a text file and extracts all email addresses.

import re

def extract_emails(filename: str) -> list:
    with open(filename, "r") as file:
        content = file.read()
    return re.findall(r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}", content)

# Example usage:
# Create a file `sample.txt` with emails inside before running
print(extract_emails("sample.txt"))

52. Replace Words in a File

Problem:
Write a function that replaces a given word in a text file with another word.

def replace_word(filename: str, old_word: str, new_word: str):
    with open(filename, "r") as file:
        content = file.read()

    content = content.replace(old_word, new_word)

    with open(filename, "w") as file:
        file.write(content)

# Example usage:
# Before running, create a `text.txt` file with content
replace_word("text.txt", "oldword", "newword")

53. Count Word Frequency in a String

Problem:
Write a function that counts the occurrence of each word in a given text.

from collections import Counter

def word_frequency(text: str) -> dict:
    words = text.lower().split()
    return dict(Counter(words))

# Example usage:
print(word_frequency("Python is easy. Python is powerful."))
# Output: {'python': 2, 'is': 2, 'easy.': 1, 'powerful.': 1}

54. Convert a CSV File to JSON

Problem:
Write a function that converts a CSV file into a JSON file.

import csv
import json

def csv_to_json(csv_filename: str, json_filename: str):
    with open(csv_filename, mode="r") as csv_file:
        data = list(csv.DictReader(csv_file))

    with open(json_filename, mode="w") as json_file:
        json.dump(data, json_file, indent=4)

# Example usage:
csv_to_json("data.csv", "data.json")

55. Send an Email using Python

Problem:
Write a function to send an email using Python’s smtplib.

import smtplib

def send_email(sender_email: str, sender_password: str, recipient_email: str, subject: str, message: str):
    server = smtplib.SMTP("smtp.gmail.com", 587)
    server.starttls()
    server.login(sender_email, sender_password)
    email_body = f"Subject: {subject}\n\n{message}"
    server.sendmail(sender_email, recipient_email, email_body)
    server.quit()
    print("Email sent successfully!")

# Example usage:
# Ensure to enable "Less Secure Apps" on your Gmail account before running
# send_email("your_email@gmail.com", "your_password", "receiver_email@gmail.com", "Test", "Hello!")

56. Web Scraping: Extract Titles from a Webpage

Problem:
Write a function that scrapes a webpage and extracts all titles (h1, h2, h3).

import requests
from bs4 import BeautifulSoup

def extract_titles(url: str):
    response = requests.get(url)
    soup = BeautifulSoup(response.text, "html.parser")
    titles = [tag.text.strip() for tag in soup.find_all(["h1", "h2", "h3"])]
    return titles

# Example usage:
print(extract_titles("https://example.com"))

57. Find and Replace Text in a PDF

Problem:
Write a function that reads a PDF file, replaces a word, and saves a new PDF.

from PyPDF2 import PdfReader, PdfWriter

def replace_text_in_pdf(input_pdf: str, output_pdf: str, old_text: str, new_text: str):
    reader = PdfReader(input_pdf)
    writer = PdfWriter()

    for page in reader.pages:
        text = page.extract_text()
        modified_text = text.replace(old_text, new_text)
        writer.add_page(page)
        writer.pages[-1].text = modified_text

    with open(output_pdf, "wb") as output_file:
        writer.write(output_file)

# Example usage:
# replace_text_in_pdf("input.pdf", "output.pdf", "old_word", "new_word")

58. Automate File Organization in a Folder

Problem:
Write a script that automatically organizes files in a folder into subfolders by file type.

import os
import shutil

def organize_files(directory: str):
    if not os.path.exists(directory):
        print("Directory not found!")
        return

    for file in os.listdir(directory):
        file_path = os.path.join(directory, file)
        if os.path.isfile(file_path):
            ext = file.split(".")[-1]
            ext_folder = os.path.join(directory, ext)
            os.makedirs(ext_folder, exist_ok=True)
            shutil.move(file_path, os.path.join(ext_folder, file))

# Example usage:
# organize_files("/path/to/your/folder")

59. Convert Text to Speech

Problem:
Write a Python script that converts text to speech using the pyttsx3 library.

import pyttsx3

def text_to_speech(text: str):
    engine = pyttsx3.init()
    engine.say(text)
    engine.runAndWait()

# Example usage:
text_to_speech("Hello, this is Python speaking!")

60. Automate Screenshot Capture

Problem:
Write a script that captures a screenshot and saves it.

import pyautogui

def take_screenshot(filename: str):
    screenshot = pyautogui.screenshot()
    screenshot.save(filename)

# Example usage:
take_screenshot("screenshot.png")

61. What is a Generator in Python?

👉 Layman Explanation:
A generator is a special type of function in Python.
Instead of giving all results at once, it gives one result at a time — whenever you ask for it.

✅ It saves memory and is faster for large tasks.


62. What is the use of the yield keyword?

👉 Layman Explanation:
Normally, we use return to give back a value and end the function.
But if you use yield, the function pauses and remembers where it left off.
Next time you call it, it continues from there!

yield makes the function a generator.


63. How is a Generator different from a normal function?

👉 Layman Explanation:

Normal FunctionGenerator
Runs once and finishes with returnCan pause and continue using yield
Returns all values togetherGives one value at a time
Consumes more memory if data is largeVery memory efficient

64. Create a Generator that yields even numbers up to 100.

👉 Layman Explanation:
Even numbers are numbers like 0, 2, 4, 6, 8, ... — numbers divisible by 2.

We will:

  • Loop from 0 to 100

  • Check if the number is even

  • Yield the number one-by-one

✅ Here’s the code:

pythonCopyEditdef even_numbers():
    for num in range(0, 101):
        if num % 2 == 0:
            yield num

# Example usage
for number in even_numbers():
    print(number, end=" ")

✅ This prints all even numbers from 0 to 100.


65. Why should we use Generators instead of Lists?

👉 Layman Explanation:

Imagine if you wanted to create a list of 1 million numbers:

  • A list would eat a lot of memory because it stores everything at once.

  • A generator creates one number at a time — so memory stays small, even with big data!

✅ Generators are like water taps — giving you water only when needed, not flooding the house!

66. What is a Decorator in Python?

👉 Layman Explanation:
A decorator is like a special wrapper for a function.
It adds extra features to a function without changing the original function's code.

✅ Imagine putting a cake into a beautiful gift box — the cake stays the same, but looks better!


67. What is the @decorator syntax?

👉 Layman Explanation:
Normally, you apply a decorator by calling it manually.
But Python gives a shortcut using @ — so you can attach a decorator directly on top of a function.

✅ Example:

pythonCopyEdit@my_decorator
def say_hello():
    print("Hello!")

This is the same as: say_hello = my_decorator(say_hello)


68. Write a Decorator to Measure Execution Time of Any Function.

👉 Layman Explanation:
We can create a decorator that:

  • Starts a clock before the function runs,

  • Stops the clock after it finishes,

  • Then prints how much time was taken.

✅ Code:

pythonCopyEditimport time

def timer_decorator(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print(f"Execution time: {end - start:.4f} seconds")
        return result
    return wrapper

@timer_decorator
def sample_task():
    for _ in range(1000000):
        pass

sample_task()

✅ This will tell you how fast or slow your function is!


69. What is a Context Manager in Python?

👉 Layman Explanation:
A Context Manager is something you use inside a with statement.
It automatically:

  • Starts something for you (example: opens a file),

  • Ends it nicely (example: closes the file) even if errors happen.

✅ No need to manually close files or connections — it's safe!


70. What are the __enter__ and __exit__ methods?

👉 Layman Explanation:
When you create your own Context Manager:

  • __enter__ is called at the start (like opening a door),

  • __exit__ is called at the end (like closing the door).

✅ They control what happens when you enter and exit a with block.


71. Create a Custom Context Manager to Open and Close a File.

👉 Layman Explanation:
We can write a class that:

  • Opens a file in __enter__,

  • Closes it properly in __exit__.

✅ Code:

class FileOpener:
    def __init__(self, filename, mode):
        self.filename = filename
        self.mode = mode

    def __enter__(self):
        self.file = open(self.filename, self.mode)
        return self.file

    def __exit__(self, exc_type, exc_value, traceback):
        self.file.close()

# Example usage
with FileOpener('example.txt', 'w') as f:
    f.write('Hello, World!')

✅ The file is automatically closed safely, even if an error happens inside with block.

72. What is the lambda keyword in Python?

👉 Layman Explanation:
A lambda is like a tiny one-line function without a name.
You use it when you don't want to create a full function with def.

✅ It's like quickly giving instructions on the spot.

✅ Example:

add = lambda a, b: a + b
print(add(2, 3))  # Output: 5

73. Sort a List of Tuples by Second Element Using lambda.

👉 Layman Explanation:
Imagine you have a list like:

items = [('apple', 2), ('banana', 5), ('mango', 1)]

You want to sort by the second number in each tuple.

✅ Code:

sorted_items = sorted(items, key=lambda x: x[1])
print(sorted_items)

✅ Output:

[('mango', 1), ('apple', 2), ('banana', 5)]

✅ Here, lambda x: x[1] means:
"Take the second thing inside each item and use it for sorting."


74. What is List Comprehension [x for x in list if condition]?

👉 Layman Explanation:
List comprehension is a short way to create new lists in one line.

✅ Instead of writing long for loops, you write compact expressions.

✅ Example:

pythonCopyEditsquares = [x*x for x in range(10) if x % 2 == 0]
print(squares)

(Only even numbers will be squared.)


75. One-Line List Creation: Squares of Odd Numbers.

👉 Layman Explanation:
Create a list that:

  • Picks only odd numbers (numbers like 1, 3, 5, 7…),

  • Squares them.

✅ Code:

odd_squares = [x**2 for x in range(1, 11) if x % 2 != 0]
print(odd_squares)

✅ Output:

[1, 9, 25, 49, 81]

76. What is threading.Thread in Python?

👉 Layman Explanation:
threading.Thread lets you run many things at the same time — like having many workers doing different jobs without waiting.

✅ Think of it like opening multiple browser tabs — all loading together!


77. Write Code to Print 5 Tasks Simultaneously Using Threads.

👉 Layman Explanation:
Create 5 different tasks and run them at the same time.

✅ Code:

pythonCopyEditimport threading
import time

def print_task(name):
    print(f"Task {name} started")
    time.sleep(2)
    print(f"Task {name} finished")

# Create 5 threads
threads = []
for i in range(5):
    t = threading.Thread(target=print_task, args=(i,))
    threads.append(t)
    t.start()

# Wait for all threads to complete
for t in threads:
    t.join()

✅ Output (order may change because they run together):

Task 0 started
Task 1 started
Task 2 started
Task 3 started
Task 4 started
Task 0 finished
Task 1 finished
Task 2 finished
Task 3 finished
Task 4 finished

78. What is multiprocessing.Pool in Python?

👉 Layman Explanation:
If you have many big tasks (like processing huge files),
multiprocessing.Pool lets you split work into multiple processors
so all the cores of your CPU can work together and finish faster.

✅ It's like asking 5 workers to clean 5 rooms at the same time, instead of one worker doing it alone.


79. Process 5 Large Files Faster Using multiprocessing.Pool.

👉 Layman Explanation:
We will:

  • Create a function to process one file,

  • Use a Pool to run 5 files in parallel.

✅ Code:

import multiprocessing
import time

def process_file(file_name):
    print(f"Processing {file_name}")
    time.sleep(2)  # Simulate heavy work
    return f"{file_name} done"

if __name__ == "__main__":
    files = ['file1', 'file2', 'file3', 'file4', 'file5']
    with multiprocessing.Pool() as pool:
        results = pool.map(process_file, files)
    print(results)

✅ This way, all files are processed together, not one-by-one!


80. What is re.search() and re.findall() in Python?

👉 Layman Explanation:
re stands for Regular Expression — a tool to search patterns inside text.

re.search() ➔ Finds first match only.
re.findall() ➔ Finds all matches.

✅ Example: Searching for all emails inside a paragraph!


81. Find All Email Addresses in a Text Using re.findall().

👉 Layman Explanation:
We will:

  • Write a pattern that matches emails,

  • Use re.findall() to collect all matches.

✅ Code:

import re

text = "Contact us at info@example.com or support@mydomain.org"
emails = re.findall(r'\b[\w.-]+@[\w.-]+\.\w+\b', text)
print(emails)

✅ Output:

cssCopyEdit['info@example.com', 'support@mydomain.org']

✅ Easy way to pull all emails from messy text!


82. How to Read a Large File Line-by-Line Safely in Python?

👉 Layman Explanation:
If you read a huge file at once, your program may crash.
Instead, read it line-by-line inside a with open() — it is safe and efficient.


83. Code to Read a Large File Line-by-Line Safely.

👉 Layman Explanation:
Use with open() which automatically closes the file when you're done.

✅ Code:

pythonCopyEditwith open('large_file.txt', 'r') as f:
    for line in f:
        print(line.strip())

✅ Memory stays low even for big files!


84. What is try-except-finally in Python?

👉 Layman Explanation:
It’s a safe guard:

  • try: ➔ Try running the code.

  • except: ➔ Catch if something goes wrong.

  • finally: ➔ Always do this step (example: close connection) — even if error happens.

✅ Like wearing a helmet while driving — safe even if accident happens!


85. Catch Division by Zero Exception Using try-except-finally.

👉 Layman Explanation:
We will:

  • Try to divide,

  • Catch if someone divides by zero,

  • Print something finally.

✅ Code:

try:
    a = 5
    b = 0
    result = a / b
except ZeroDivisionError:
    print("Cannot divide by zero!")
finally:
    print("Division attempt finished.")

✅ Output:

Cannot divide by zero!
Division attempt finished.

✅ No crash — handled safely!

6. How do you connect to an Amazon S3 bucket using Python?

👉 Layman Explanation:
Amazon S3 is like a big storage hard disk in the cloud.
To talk to it from Python, we use a library called boto3.

✅ Code:

pythonCopyEditimport boto3

s3 = boto3.client('s3')

✅ You must configure AWS credentials first (either by AWS CLI or IAM roles).


87. How do you upload a file to an S3 bucket using Python?

👉 Layman Explanation:
We will:

  • Use upload_file() method,

  • Provide the filename, bucket name, and key (path inside S3).

✅ Code:

pythonCopyEdits3.upload_file('local_file.txt', 'my-bucket-name', 'folder1/remote_file.txt')

✅ Meaning:

  • Upload local_file.txt

  • Into bucket my-bucket-name

  • Inside folder folder1 as remote_file.txt


88. How do you download a file from an S3 bucket using Python?

👉 Layman Explanation:
The opposite of upload — bring a file down to your machine.

✅ Code:

pythonCopyEdits3.download_file('my-bucket-name', 'folder1/remote_file.txt', 'downloaded_file.txt')

✅ Meaning:

  • Take remote_file.txt from S3,

  • Save it locally as downloaded_file.txt.


89. How do you list all files inside an S3 bucket folder?

👉 Layman Explanation:
We ask S3:
"Hey, show me everything inside folder1!"

✅ Code:

pythonCopyEditresponse = s3.list_objects_v2(Bucket='my-bucket-name', Prefix='folder1/')
for obj in response.get('Contents', []):
    print(obj['Key'])

✅ Output:
It will print all file paths under folder1/.


90. How do you delete a file from an S3 bucket?

👉 Layman Explanation:
Simple — tell S3:
"Please delete this file."

✅ Code:

pythonCopyEdits3.delete_object(Bucket='my-bucket-name', Key='folder1/remote_file.txt')

✅ The file will be removed from S3.


📋 Quick Summary Table

TaskPython Code
Connect to S3boto3.client('s3')
Upload fileupload_file(local, bucket, key)
Download filedownload_file(bucket, key, local)
List fileslist_objects_v2()
Delete filedelete_object()

91. How do you upload a large file (>100MB) efficiently to S3?

👉 Layman Explanation:
Normal upload_file() may fail or be too slow for big files.
For large files, you should use Multipart Upload — break the file into small parts and upload in chunks.

boto3 handles this automatically if you use TransferConfig.

✅ Example:

pythonCopyEditfrom boto3.s3.transfer import TransferConfig

config = TransferConfig(multipart_threshold=100*1024*1024)  # 100MB
s3.upload_file('largefile.zip', 'my-bucket', 'large/largefile.zip', Config=config)

Result: Uploads are faster, safer, and resumable.


92. How do you make an S3 object publicly readable after upload?

👉 Layman Explanation:
After uploading, if you want anyone on the internet to view/download it without login,
you must set the object’s ACL (Access Control List) to public-read.

✅ Code:

pythonCopyEdits3.upload_file('image.png', 'my-bucket', 'images/image.png', ExtraArgs={'ACL': 'public-read'})

✅ Now the file will be publicly accessible with a URL.


93. How do you generate a Pre-Signed URL for downloading a private S3 file?

👉 Layman Explanation:
A pre-signed URL is a temporary link you give to users to download a private file without logging into AWS.

✅ Code:

pythonCopyEditurl = s3.generate_presigned_url('get_object',
    Params={'Bucket': 'my-bucket', 'Key': 'private/file.txt'},
    ExpiresIn=3600)  # 1 hour validity

print(url)

✅ Super useful for secure downloads.


94. How do you check if a file exists in an S3 bucket (without downloading)?

👉 Layman Explanation:
You can head (peek) the object instead of downloading it fully.

✅ Code:

pythonCopyEdittry:
    s3.head_object(Bucket='my-bucket', Key='path/to/file.txt')
    print("File exists!")
except s3.exceptions.ClientError as e:
    if e.response['Error']['Code'] == '404':
        print("File does not exist!")
    else:
        raise

✅ No download needed — just checks metadata.


95. How do you copy a file from one S3 bucket to another?

👉 Layman Explanation:
S3 allows you to copy objects inside AWS without downloading them to your computer.

✅ Code:

pythonCopyEditcopy_source = {'Bucket': 'source-bucket', 'Key': 'source_folder/file.txt'}
s3.copy(copy_source, 'destination-bucket', 'destination_folder/file.txt')

Fast internal AWS transfer!


96. How do you list all files in an S3 bucket recursively (handle folders inside folders)?

👉 Layman Explanation:
Sometimes S3 folders have nested folders.
You should keep fetching until all objects are listed.

✅ Code:

pythonCopyEditpaginator = s3.get_paginator('list_objects_v2')
for page in paginator.paginate(Bucket='my-bucket'):
    for obj in page.get('Contents', []):
        print(obj['Key'])

Paginator keeps loading files batch by batch.


97. How do you delete multiple files from S3 at once?

👉 Layman Explanation:
Instead of deleting files one-by-one (slow!),
you can bulk delete using delete_objects().

✅ Code:

pythonCopyEdits3.delete_objects(Bucket='my-bucket', Delete={
    'Objects': [
        {'Key': 'file1.txt'},
        {'Key': 'file2.txt'}
    ]
})

Faster and cheaper way when cleaning up.


📋 Quick Recap Table

TaskImportant Keyword
Large File UploadTransferConfig (Multipart Upload)
Public FileExtraArgs={'ACL': 'public-read'}
Pre-Signed URLgenerate_presigned_url()
File Exists Checkhead_object()
Copy Filecopy()
List All Filespaginator.paginate()
Bulk Deletedelete_objects()

98. What is a CI/CD pipeline? How can Python be used in it?

👉 Layman Explanation:

  • CI (Continuous Integration): Developers frequently push code to Git (every day).

  • CD (Continuous Deployment): New code automatically goes to testing or production server.

✅ Python can:

  • Write scripts to automate build/test/deploy.

  • Create custom jobs inside CI tools (like Jenkins, GitLab CI, GitHub Actions).

  • Run test suites (pytest, unittest) automatically after every commit.


99. How can you automate testing in a CI pipeline using Python?

👉 Layman Explanation:
Whenever code changes happen,
Python can run all tests automatically without manual effort.

✅ Typical Python code step:

bashCopyEditpip install -r requirements.txt
pytest tests/

✅ You can put this inside:

  • .gitlab-ci.yml

  • Jenkinsfile

  • GitHub Actions .yaml files

✅ Result:
Bad code is caught early — no broken deployments!


100. How can you write a Python script to deploy code to a server (Dev/QA/Prod)?

👉 Layman Explanation:
Instead of manual copy-paste,
write a Python script to SSH into a server and upload files automatically.

✅ Example with paramiko (SSH library):

pythonCopyEditimport paramiko

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('server_ip', username='user', password='password')

stdin, stdout, stderr = ssh.exec_command('git pull origin main')
print(stdout.read().decode())

ssh.close()

✅ This connects to server and pulls latest code automatically.


101. How can you automate Docker image builds using Python?

👉 Layman Explanation:
Instead of typing docker commands manually,
use Python’s subprocess module to build and push Docker images.

✅ Example:

pythonCopyEditimport subprocess

# Build Docker image
subprocess.run(["docker", "build", "-t", "myapp:latest", "."])

# Push Docker image
subprocess.run(["docker", "push", "myrepo/myapp:latest"])

✅ Useful in Python-based build pipelines!


102. How can you create a GitHub Action to run a Python script?

👉 Layman Explanation:
GitHub Actions is a free way to run automation when someone pushes to GitHub.

✅ Minimal .github/workflows/python-script.yml:

yamlCopyEditname: Run Python Script

on: [push]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v2
    - name: Set up Python
      uses: actions/setup-python@v2
      with:
        python-version: '3.10'
    - name: Run script
      run: |
        pip install -r requirements.txt
        python main.py

✅ It will automatically run your main.py whenever you push new code!


103. How would you integrate Python tests into Jenkins?

👉 Layman Explanation:

  • Install Python in Jenkins agent machine.

  • In Jenkinsfile (or freestyle job), add build steps:

✅ Jenkins pipeline snippet:

groovyCopyEditpipeline {
    agent any
    stages {
        stage('Install dependencies') {
            steps {
                sh 'pip install -r requirements.txt'
            }
        }
        stage('Run tests') {
            steps {
                sh 'pytest tests/'
            }
        }
    }
}

✅ Jenkins will install, test, and report results automatically.


📋 Quick Recap Table

TaskHow Python Helps
Automate testsRun pytest, fail early
Automate deploymentSSH + Git pull or Docker push
GitHub ActionRun Python scripts on push
Jenkins pipelinePython install, build, test steps
Docker buildsubprocess run docker commands

104. How would you automate S3 uploads as part of your CI/CD pipeline?

👉 Layman Explanation:

  • After code build finishes successfully,

  • Use a Python script to upload build artifacts (like zip files, binaries) to Amazon S3.

✅ Example:

  • After building a Python app, zip it and upload to S3 for backup or deployment.

✅ Tools: boto3, subprocess for zip, etc.


105. How can you trigger a Lambda function automatically after uploading a file to S3 using Python?

👉 Layman Explanation:

  • Set up an S3 event notification that triggers AWS Lambda when new files come.

  • Use Python Lambda handler to process the file immediately.

✅ Example use case:

  • After uploading a CSV, auto-process it via Python Lambda.

✅ (Knowledge of event, context, boto3 inside Lambda)


106. How would you send Slack notifications after deployment success or failure using Python?

👉 Layman Explanation:
Python can send a message to Slack using a Webhook URL.

✅ Code Sketch:

pythonCopyEditimport requests

def send_slack_message(message):
    webhook_url = 'https://hooks.slack.com/services/your/slack/webhook'
    payload = {'text': message}
    requests.post(webhook_url, json=payload)

send_slack_message("Deployment successful! 🚀")

✅ Very useful for real-time deployment monitoring.


107. How would you safely store AWS credentials in a CI/CD pipeline?

👉 Layman Explanation:
Never hardcode keys in code!
Instead:

  • Use environment variables (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)

  • Or use Secrets Manager if using GitHub Actions or GitLab CI.

  • In Python, pick them up using os.environ.

✅ Example:

pythonCopyEditimport os
aws_key = os.environ['AWS_ACCESS_KEY_ID']
aws_secret = os.environ['AWS_SECRET_ACCESS_KEY']

Security best practice!


108. How can you parallelize multiple Python test cases in a CI/CD pipeline?

👉 Layman Explanation:
If you have lots of slow tests, run them parallelly to save time.

✅ In Python:

bashCopyEditpytest -n auto

(using pytest-xdist plugin)

✅ In GitHub Actions or Jenkins, you can also split jobs into parallel runners.

✅ Result: Tests that took 30 mins can finish in 5 mins!


109. How would you automatically version your build using Python before deploying?

👉 Layman Explanation:
Each build should have a version number or timestamp
Python can auto-generate it!

✅ Code Sketch:

pythonCopyEditfrom datetime import datetime

version = datetime.now().strftime("%Y%m%d%H%M%S")
print(f"Deploying version: {version}")

✅ Attach this to S3 filenames, docker tags, or deployment metadata.


110. How would you rollback a failed Python deployment automatically?

👉 Layman Explanation:

  • Keep previous stable version stored (in S3, Git, or local server).

  • If new deployment fails (error, health check fail),

  • Python script triggers restore of old version.

✅ Real-world example:

  • Use S3 versioning + Python copy_object() to recover old deployment.

📋 Fresh Summary Table

TaskAdvanced Real-World Usage
S3 uploads in CI/CDPost-build backup to S3
Lambda trigger from S3Auto-process uploaded files
Slack notificationsReal-time deployment updates
AWS secret managementEnvironment variables / Secrets
Test parallelizationFaster CI pipelines
Build versioningAutomatic tagging
Deployment rollbackRestore safe version

Python Interview Questions on Pandas, NumPy, Requests, Flask, Testing


📄 Pandas and NumPy

111. What is Pandas and why do we use it?

👉 Layman Explanation:
Pandas is like Excel inside Python — you can create tables, filter rows, calculate totals, etc.

✅ Use for:

  • Reading CSVs

  • Cleaning messy data

  • Making reports


112. How do you create a DataFrame from a dictionary using Pandas?

✅ Code:

pythonCopyEditimport pandas as pd

data = {'Name': ['Alice', 'Bob'], 'Age': [25, 30]}
df = pd.DataFrame(data)
print(df)

✅ Output: a table with columns Name and Age.


113. What is NumPy and when should you use it?

👉 Layman Explanation:
NumPy is for fast number crunching — super powerful when you have lots of numbers (arrays, matrices).

✅ Use when:

  • Doing scientific calculations

  • Working with large datasets (faster than regular lists)


📄 Requests and BeautifulSoup

114. What is the purpose of the requests library in Python?

👉 Layman Explanation:
requests helps your Python program talk to websites.
You can send GET, POST, PUT, DELETE requests easily.

✅ Example:

pythonCopyEditimport requests
response = requests.get('https://example.com')
print(response.text)

115. How does BeautifulSoup help in web scraping?

👉 Layman Explanation:
BeautifulSoup helps you read messy HTML pages and pick out the data you need — like a smart magnifying glass for websites.

✅ Example:

pythonCopyEditfrom bs4 import BeautifulSoup

soup = BeautifulSoup('<html><title>Test</title></html>', 'html.parser')
print(soup.title.text)  # Output: Test

📄 Flask and FastAPI

👉 Layman Explanation:
Flask is a very lightweight web server framework.
If you want to build small websites or APIs quickly, Flask is easy and flexible.

✅ Example:

pythonCopyEditfrom flask import Flask
app = Flask(__name__)

@app.route('/')
def hello():
    return "Hello, World!"

117. How is FastAPI different from Flask?

👉 Layman Explanation:
FastAPI is like Flask but faster and ready for modern APIs:

  • Built-in data validation using pydantic

  • Async ready (better performance)

✅ Very useful when building large or high-performance backend APIs.


📄 Pytest and Unittest

118. What is Pytest used for?

👉 Layman Explanation:
Pytest is a tool that helps you test your Python code automatically.

✅ Example:

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

def test_add():
    assert add(2, 3) == 5

✅ Run pytest in the terminal — it tells you if your function is working or broken!


119. How is Unittest different from Pytest?

👉 Layman Explanation:
Both do testing, but:

  • unittest is older and part of Python already (built-in)

  • pytest is newer, easier, and more powerful for writing tests quickly

✅ Pytest = Less code, more features ✅


📋 Quick Summary Table

LibraryBasic Purpose
PandasTables, data cleaning
NumPyFast math with arrays
RequestsTalk to websites
BeautifulSoupPick data from HTML
FlaskBuild small web servers
FastAPIFast, async-ready APIs
PytestQuick and powerful testing
UnittestStandard Python testing

120. How would you scrape 100 pages automatically?

👉 Layman Explanation:

  • You need a for loop that goes through pages 1 to 100.

  • For each page, use requests to get HTML, and BeautifulSoup to scrape data.

✅ Example Code:

pythonCopyEditimport requests
from bs4 import BeautifulSoup

for page in range(1, 101):
    url = f"https://example.com/page/{page}"
    response = requests.get(url)
    soup = BeautifulSoup(response.text, 'html.parser')

    # Example: Get all headings
    headings = soup.find_all('h2')
    for h in headings:
        print(h.text.strip())

✅ Good candidate will:

  • Use loops

  • Handle page numbers dynamically

  • Use BeautifulSoup properly


121. How would you design a simple Flask app for uploading files?

👉 Layman Explanation:

  • Flask has built-in support for file uploads.

  • You create a POST endpoint, use request.files to get the file, and save it locally.

✅ Example Code:

pythonCopyEditfrom flask import Flask, request, redirect

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads/'

@app.route('/upload', methods=['POST'])
def upload_file():
    file = request.files['file']
    file.save(app.config['UPLOAD_FOLDER'] + file.filename)
    return 'File uploaded successfully!'

if __name__ == '__main__':
    app.run(debug=True)

✅ Good candidate will:

  • Know about request.files

  • Save file properly

  • Set upload folder


122. How would you validate API request inputs in FastAPI?

👉 Layman Explanation:

  • FastAPI uses pydantic models to automatically validate input data.

  • If data is missing or wrong type, FastAPI returns error automatically.

✅ Example Code:

pythonCopyEditfrom fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    price: float
    quantity: int

@app.post("/items/")
async def create_item(item: Item):
    return item

✅ Good candidate will:

  • Use BaseModel

  • Define fields with types

  • Understand automatic 422 error on bad input


123. Can you write a Pytest test that checks if API returns status 200?

👉 Layman Explanation:

  • Pytest can call the API, and check if response is successful (HTTP 200).

✅ Example Code:

pythonCopyEditimport requests

def test_homepage_status():
    response = requests.get('http://localhost:5000/')
    assert response.status_code == 200

✅ Good candidate will:

  • Know how to use requests inside tests

  • Understand status_code checking

  • Use assert properly

0
Subscribe to my newsletter

Read articles from Tech Academy directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Tech Academy
Tech Academy

Data & AI Transformation Lead • 15+ years of experience in AI-driven Quality Engineering, Data Analytics, and Test Automation. • Expertise in AI/ML, Data Testing, Cloud Automation, ETL Pipelines, and Observability tools. • Hands-on leader in AI-driven automation, predictive analytics, and cloud data validation. • Strong technical proficiency in Snowflake, DBT, Power BI, Python, AWS, SQL, and MLOps pipelines. • Proven success in reducing defects, optimizing performance, and streamlining data workflows. • Expertise in integrating security into CI/CD pipelines, automated security scanning, vulnerability assessment, and compliance-driven quality engineering. • Expertise in JMeter, BlazeMeter, Snowflake SQL Profiler, optimizing application & data performance testing for high-scale environments. • Strong expertise in SAFe, Scrum, and Kanban methodologies, ensuring seamless collaboration between development, testing, and operations teams.