Python Programming, (Some imp. Coding ques.
)
BCS 302
1 def file_stats ( filename ):
2 try:
3 with open(filename , 'r') as file:
4 content = [Link] ()
5 print (f" Lines : {len( content . splitlines ())}")
6 print (f" Words : {len( content . split ())}")
7 print (f" Characters : {len( content )}")
8 except FileNotFoundError :
9 print ("File not found .")
10
4. Operators, Precedence, and Associativity
Question: Explain operators, precedence, and associativity.
Answer:
• Operators:
– Arithmetic: +, -, *, /, //, %, **
– Comparison: ==, !=, >, <
– Logical: and, or, not
• Precedence: Determines the order in which operations are evaluated (e.g., * is done be-
fore +).
• Associativity: Determines order for operators with the same precedence. Most are Left-
to-Right, but Exponentiation (**) is Right-to-Left.
5. Remove Duplicates Preserving Order
Question: Write a program to remove duplicates from a list while keeping the original order.
Logic Note: Using set(list) destroys order. Instead, we iterate through the list and add
items to a seen set to track duplicates, only appending new items to our result list.
1 def remove_duplicates ( input_list ):
2 seen = set ()
3 result = []
4 for item in input_list :
5 if item not in seen:
6 [Link](item)
7 result . append (item)
8 return result
9
10 print ( remove_duplicates ([1, 2, 2, 3, 4, 3, 5]))
11
6. Recursion (Factorial)
Question: Explain recursion with a program to compute factorial.
Explanation: Recursion is a technique where a function calls itself. It must have a Base Case
(to stop) and a Recursive Case (to continue).
2
1 def factorial (n):
2 if n == 0 or n == 1: return 1 # Base Case
3 else: return n * factorial (n - 1) # Recursive Case
4
7. Count Vowels, Consonants, Digits
Question: Program to count vowels, consonants, and digits.
1 def count_chars (text):
2 vowels = " aeiouAEIOU "
3 v = c = d = 0
4 for char in text:
5 if char. isalpha ():
6 if char in vowels : v += 1
7 else: c += 1
8 elif char. isdigit (): d += 1
9 print (f" Vowels : {v}, Consonants : {c}, Digits : {d}")
10
8. Palindrome Check
Question: Check if a number is a palindrome using if-elif-else.
Logic Note: A palindrome reads the same backwards. Python string slicing [::-1] reverses
a string efficiently.
1 num = input (" Enter a number : ")
2 if num == num [:: -1]:
3 print (" Palindrome ")
4 else:
5 print ("Not a Palindrome ")
6
9. Python Libraries (Matplotlib, NumPy, Pandas)
Question: Write a short note on Matplotlib, NumPy, and Pandas with example code.
Answer:
A) NumPy (Numerical Python): Used for scientific computing. It provides support for large,
multi-dimensional arrays and matrices.
1 import numpy as np
2 # Creating a 1D array
3 arr = [Link] ([1, 2, 3, 4])
4 # Performing element -wise multiplication
5 print (arr * 2) # Output : [2 4 6 8]
6
B) Pandas: Used for data manipulation and analysis. It provides the DataFrame structure
(like an Excel table).
1 import pandas as pd
2 # Creating a DataFrame from a dictionary
3 data = {'Name ': ['Alice ', 'Bob '], 'Age ': [25, 30]}
4 df = pd. DataFrame (data)
5 print (df)
3
6 # Output :
7 # Name Age
8 # 0 Alice 25
9 # 1 Bob 30
10
C) Matplotlib: Used for creating static, animated, and interactive visualizations.
1 import matplotlib . pyplot as plt
2 x = [1, 2, 3, 4]
3 y = [10, 20, 25, 30]
4 [Link](x, y)
5 [Link](" Simple Line Plot")
6 [Link] ()
7
10. Break vs Continue
Question: How is break different from continue?
Answer:
• break: Exits the loop immediately. The code continues from the first line after the loop.
• continue: Skips the rest of the current iteration and jumps back to the top of the loop for
the next iteration.
11. Uppercase without upper()
Question: Convert string to uppercase without built-in methods.
Logic Note: ASCII value of ’a’ is 97, ’A’ is 65. The difference is 32. To convert lowercase to
upper, subtract 32 from its ASCII value.
1 def to_upper (text):
2 res = ""
3 for char in text:
4 if 'a' <= char <= 'z':
5 res += chr(ord(char) - 32)
6 else:
7 res += char
8 return res
9
12. Mutable vs Immutable
Question: Explain mutable vs immutable data types.
Answer:
• Immutable: Cannot be changed after creation. Any ”change” creates a new object. Exam-
ples: int, float, str, tuple.
• Mutable: Can be modified in place. Examples: list, dict, set.
4
2 Control Flow & Data Structures
13. Calculator
Question: Design a simple calculator.
1 op = input (" Operator (+, -, *, /): ")
2 n1 = float ( input ("First : "))
3 n2 = float ( input (" Second : "))
4
5 if op == '+': print (n1 + n2)
6 elif op == '-': print (n1 - n2)
7 elif op == '*': print (n1 * n2)
8 elif op == '/': print (n1 / n2 if n2 != 0 else " Error ")
9
14. Prime Number
Question: Check if a number is prime.
1 n = int( input ("Enter number : "))
2 if n > 1:
3 for i in range (2, int(n **0.5) + 1):
4 if n % i == 0:
5 print ("Not Prime ")
6 break
7 else:
8 print ("Prime ")
9
15. For Loop
Question: Explain for loop. Note: Python for-loops are ”for-each” loops that iterate over se-
quences.
1 for x in [" apple ", " banana "]:
2 print (x)
3
16. Quotient and Remainder
Question: Print quotient and remainder.
1 # // is floor division , % is modulus
2 q = 10 // 3 # Result : 3
3 r = 10 % 3 # Result : 1
4
17. __init__.py
Question: Role of __init__.py? Answer: It marks a directory as a Python package, allowing
modules to be imported from it. It can also hold initialization code.
5
18. Character Frequency
Question: Dictionary of character frequencies.
1 text = " hello "
2 freq = {}
3 for char in text:
4 freq[char] = [Link](char , 0) + 1
5 print (freq) # {'h ':1, 'e ':1, 'l ':2, 'o ':1}
6
19. Interpreted Language
Question: Why is Python interpreted? Answer: Python code is executed line-by-line by the
Python Virtual Machine (PVM) rather than being compiled to machine code beforehand. This
makes it portable and easy to debug, though slightly slower.
20. Multiplication Table
Question: Display multiplication table.
1 n = 5
2 for i in range (1, 11):
3 print (f"{n} x {i} = {n*i}")
4
21. List Comprehension
Question: Explain list comprehension. Answer: Concise syntax to create lists. [expr for item
in list if condition].
1 squares = [x**2 for x in range (5)]
2 evens = [x for x in range (10) if x % 2 == 0]
3
22. Min/Max without built-ins
Question: Find min and max manually.
1 lst = [5, 1, 8, 3]
2 min_v = max_v = lst [0]
3 for x in lst:
4 if x < min_v: min_v = x
5 if x > max_v: max_v = x
6
23. Built-in Modules
Question: Explain math, random, datetime.
• [Link](x), [Link]
• [Link](a,b), [Link](list)
• [Link]()
6
24. Lambda Functions
Question: Describe lambda functions. Answer: Anonymous one-line functions. Syntax: lambda
args: expression.
1 add = lambda x, y: x + y
2 print (add (2, 3))
3
25. List Slicing
Question: Slicing L = [10...100]
• L[2:7]: Elements from index 2 to 6.
• L[-5:]: Last 5 elements.
• L[1::2]: Every 2nd element (odd positions).
• L[::-1]: Reverse the list.
3 Advanced Topics (Detailed Explanations)
26. Word Frequency in Paragraph
Question: Write a Python program to count word frequency in a paragraph.
Logic Note: We use split() to break the paragraph into words. Then, we use a dictionary
to store the count. get(w, 0) is crucial here: it gets the current count of the word, or returns 0
if the word isn’t in the dictionary yet.
1 para = "this is a test this is only a test"
2 words = [Link] ()
3 counts = {}
4
5 for w in words:
6 counts [w] = counts .get(w, 0) + 1
7
8 print ( counts )
9
27. read() vs readline()
Question: Difference between read() and readline()?
Detailed Answer:
• read([size]): This method reads the entire file content into a single string variable. If
the file is very large, this can crash the program by using up all memory.
• readline(): This method reads just one line at a time (up to the newline character \n). It
is memory efficient for looping through large files.
7
28. Exception Handling
Question: Explain exception handling (try, except, finally).
Logic Note: Exception handling prevents programs from crashing due to runtime errors
(like dividing by zero).
• try: Contains the code that might cause an error.
• except: Contains the code that runs if an error happens.
• finally: Contains code that runs no matter what (e.g., closing a file).
1 try:
2 print (10 / 0)
3 except ZeroDivisionError :
4 print (" Cannot divide by zero!")
5 finally :
6 print (" Execution complete .")
7
29. Second Largest Number
Question: Find the second largest number in a list.
Logic Note: The simplest logic is: 1. Remove duplicates using set() so that two 99s don’t
count as largest and second largest. 2. Convert back to a list. 3. Sort the list using sorted().
4. Pick the second last element using index [-2].
1 lst = [10, 20, 20, 5, 99, 99]
2 unique_sorted = sorted (list(set(lst)))
3 print (" Second Largest :", unique_sorted [ -2])
4 # Output : 20
5
30. Reverse Integer
Question: Write a Python program to reverse a given integer number.
Logic Note: We cannot simply index an integer like a string. 1. Extract the last digit using
modulus 10 (n % 10). 2. Add this digit to rev, but shift rev to the left first (rev * 10). 3. Remove
the last digit from n using floor division (n // 10).
1 n = 1234
2 rev = 0
3 while n > 0:
4 last_digit = n % 10
5 rev = (rev * 10) + last_digit
6 n = n // 10
7 print (rev) # Output : 4321
8
31. Separate Even and Odd Lists
Question: Put even and odd elements of a list into two different lists.
Logic Note: Iterate through the source list. Check if x % 2 == 0. If yes, append to evens,
else append to odds.
8
1 nums = [1, 2, 3, 4, 5, 6]
2 evens = []
3 odds = []
4
5 for x in nums:
6 if x % 2 == 0:
7 evens. append (x)
8 else:
9 odds. append (x)
10
11 print ("Evens :", evens)
12 print ("Odds:", odds)
13
32. List vs Tuple & Dictionary Functions
Question: Distinguish between List and Tuple. Explain 4 dictionary functions.
A. List vs Tuple:
• List []: Mutable (changeable), slower, consumes more memory. Used for datasets that
change.
• Tuple (): Immutable (unchangeable), faster. Used for fixed constants (e.g., coordinates).
B. Dictionary Functions:
1. keys(): Returns list of keys.
2. values(): Returns list of values.
3. items(): Returns (key, value) pairs.
4. get(key): Returns value safely (no error if missing).
33. File Processing
Question: Read a file, write uppercase version to new file, append ”Total lines processed”.
Logic Note: We use with open() to safely handle files. We keep a counter count and incre-
ment it inside the loop.
1 count = 0
2 try:
3 with open('input .txt ', 'r') as f_in , open('[Link] ', 'w') as f_out:
4 for line in f_in:
5 f_out.write([Link] ())
6 count += 1
7 f_out.write(f"\ nTotal lines processed : { count }")
8 except :
9 print ("Error handling files ")
10
9
34. Decorators
Question: What are Python decorators? Demonstrate with a simple example.
Logic Note: A decorator allows you to wrap a function to extend its behavior without mod-
ifying the function itself. In the example below, @my_decorator automatically runs code before
and after say_hello().
1 def my_decorator (func):
2 def wrapper ():
3 print (" Before the function .")
4 func ()
5 print ("After the function .")
6 return wrapper
7
8 @my_decorator
9 def say_hello ():
10 print ("Hello !")
11
12 say_hello ()
13
35. Steps in File Handling
Question: Explain steps: opening, reading/writing, seek, checking properties, closing.
Answer:
1. Opening: f = open("[Link]", "r") creates a file object.
2. Read/Write: [Link]() gets data; [Link]("txt") saves data.
3. Seek: [Link](0) moves the file cursor to the beginning (byte 0).
4. Properties: [Link] checks if read/write; [Link] checks if open.
5. Closing: [Link]() saves changes and releases memory.
36. Type Conversion
Question: Explain type conversion with examples.
Answer:
• Implicit: Python does it automatically. E.g., 3 + 4.5 becomes 7.5 (int → float).
• Explicit (Casting): User forces conversion.
1 num_str = "100"
2 num_int = int( num_str ) # Converts string "100" to integer 100
3 num_float = float (10) # Converts int 10 to float 10.0
4
10
37. Merge Two Dictionaries
Question: Write a Python program to merge two dictionaries.
Logic Note: We can use the update operator | (in Python 3.9+) or dictionary unpacking **.
1 d1 = {'a': 1, 'b': 2}
2 d2 = {'c': 3, 'd': 4}
3
4 # Method 1 ( Python 3.9+)
5 merged = d1 | d2
6
7 # Method 2 ( Compatible with older versions )
8 merged_old = {**d1 , **d2}
9
10 print ( merged )
11
38. Module Creation
Question: Create a module area with functions circle() and rectangle(), then import it.
Answer: Step 1: Create [Link]
1 import math
2 def circle (r):
3 return [Link] * r * r
4 def rectangle (l, b):
5 return l * b
6
Step 2: Create [Link]
1 import area
2 print (" Circle Area:", area. circle (5))
3 print ("Rect Area:", area. rectangle (10, 20))
4
39. List Methods
Question: Explain any five list methods with examples.
Answer:
1. append(x): Adds x to end. [Link](10)
2. insert(i, x): Inserts x at index i. [Link](0, 99)
3. pop(): Removes last element. [Link]()
4. remove(x): Removes first occurrence of x. [Link](10)
5. sort(): Sorts list in ascending order. [Link]()
40. Extract Largest 3 Elements (No Sorting)
Question: Write a Python program to extract the largest 3 elements from a list (without sorting).
Logic Note: Sorting is ”expensive” (slow) for large lists. Instead, we can do one pass through
the list. We keep track of the top 3 numbers seen so far (m1, m2, m3) and shift them down as
we find larger numbers.
11
1 def max_three (lst):
2 m1 = m2 = m3 = float ('-inf ') # Start with very small numbers
3
4 for x in lst:
5 if x > m1:
6 m3 , m2 , m1 = m2 , m1 , x
7 elif x > m2:
8 m3 , m2 = m2 , x
9 elif x > m3:
10 m3 = x
11 return [m1 , m2 , m3]
12
13 print ( max_three ([10 , 50, 5, 100, 2]))
14 # Output : [100 , 50, 10]
15
Motivation for Students
“Success is not final, failure is not fatal:
It is the courage to continue that counts.”
– Winston Churchill
12