0% found this document useful (0 votes)
3 views70 pages

Python Ans

The document is a solved question bank for a Computer Programming course, specifically for B.Tech 4th Semester Electrical Engineering at the University of Calcutta. It covers fundamental concepts of Python programming, including definitions, data types, flow control, functions, and various operations with detailed explanations and examples. Each section is referenced to specific lecture notes, providing comprehensive solutions to very short questions related to the subject matter.

Uploaded by

Byom Bhola
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views70 pages

Python Ans

The document is a solved question bank for a Computer Programming course, specifically for B.Tech 4th Semester Electrical Engineering at the University of Calcutta. It covers fundamental concepts of Python programming, including definitions, data types, flow control, functions, and various operations with detailed explanations and examples. Each section is referenced to specific lecture notes, providing comprehensive solutions to very short questions related to the subject matter.

Uploaded by

Byom Bhola
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PCC-EE 405: Computer Programming — Solved Question Bank

[Link] 4th Semester, Electrical Engineering (University of Calcutta) Comprehensive solutions


mapped to Lecture Notes (Slides 1 to 530+)

SECTION A: VERY SHORT QUESTIONS (CO1, CO2, CO3)

CO1: Fundamentals, Data Types, Flow Control and Functions

1. Define Python.

Answer: Python is a high-level, interpreted, interactive, and object-oriented programming language.


It is known for its high readability, clean syntax, and dynamic typing.

Reference: Lec 1. Introduction to [Link] — Slide 4

2. Explain important features of Python.

Answer: Key features include:

• Simple & Easy to Learn: Clean syntax resembles plain English.

• Interpreted: Executed line-by-line by an interpreter.

• Free & Open Source: Freely distributable and customizable.

• Platform Independent/Portable: Runs on Windows, macOS, Linux, etc.

• Extensible & Embeddable: Can easily interface with C/C++ code.

• Rich Library Support: Vast standard library for scientific and system computing.

Reference: Lec 1. Introduction to [Link] — Slides 5–20

3. What is an interpreter?

Answer: An interpreter is a translation program that converts high-level source code into machine
code line-by-line and executes it immediately, rather than compiling the entire program at once.

Reference: Lec 1. Introduction to [Link] — Slide 22

4. Differentiate between compiler and interpreter.

Answer:

• Compiler: Translates the entire source program into machine code (object file) at once.
Execution occurs afterward. (e.g., C, C++).

• Interpreter: Translates and executes the source code line-by-line. No intermediate object
code is saved. (e.g., Python, Ruby).

Reference: Lec 1. Introduction to [Link] — Slides 23–25

5. Define variable in Python.

Answer: A variable in Python is a named reference or label pointing to an object stored in system
memory. Unlike other languages, variables do not have types; only the objects they reference have
types.
Reference: Lec 1. Introduction to [Link] — Slide 32

6. Define identifier with example.

Answer: An identifier is a name used to identify a variable, function, class, module, or other object.

Example: student_name, calculate_sum, x1

Reference: Lec 1. Introduction to [Link] — Slide 35

7. What are keywords in Python?

Answer: Keywords are reserved words in Python that have predefined meanings to the interpreter.
They cannot be used as identifier names (e.g., if, while, def, class, import).

Reference: Lec 1. Introduction to [Link] — Slide 38

8. Explain rules for naming identifiers.

Answer:

1. Must begin with a letter (A-Z, a-z) or an underscore (_).

2. Cannot begin with a digit.

3. Can contain letters, digits, and underscores.

4. Case-sensitive (total and Total are different).

5. Cannot be a reserved keyword.

Reference: Lec 1. Introduction to [Link] — Slide 36

9. What is type conversion?

Answer: Type conversion (or type casting) is the process of converting the value of one data type into
another (e.g., converting an integer to a float).

Reference: Lec 1. Introduction to [Link] — Slide 46

10. Differentiate between implicit and explicit type conversion.

Answer:

• Implicit Type Conversion: Done automatically by the Python interpreter to avoid data loss
(e.g., adding an int and float automatically yields a float).

• Explicit Type Conversion: Manually triggered by the programmer using built-in functions like
int(), float(), str(), etc.

Reference: Lec 1. Introduction to [Link] — Slides 47–50

11. What is a data type?

Answer: A data type represents the classification of a data item. It defines what value a variable can
hold and what operations can be performed on it.

Reference: Lec 1. Introduction to [Link] — Slide 56

12. Explain integer and floating-point data types.


Answer:

• Integer (int): Represents positive or negative whole numbers of arbitrary precision (e.g., 42, -
10).

• Floating-point (float): Represents real numbers with a decimal point or exponential notation
(e.g., 3.14, -0.001, 1e-3).

Reference: Lec 1. Introduction to [Link] — Slide 58

13. What is a string?

Answer: A string (str) is an ordered sequence of Unicode characters enclosed within single quotes
('...'), double quotes ("..."), or triple quotes ('''...''' or """...""").

Reference: Lec 1. Introduction to [Link] — Slide 71

14. Explain string indexing.

Answer: String indexing allows accessing individual characters in a string. Python supports:

• Positive Indexing: Left-to-right, starting at 0.

• Negative Indexing: Right-to-left, starting at -1.

Reference: Lec 1. Introduction to [Link] — Slide 74

15. Explain string slicing.

Answer: Slicing extracts a substring by specifying a range of indices using the syntax
string[start:stop:step]. It returns a new string containing characters from index start up to (but not
including) stop.

Reference: Lec 1. Introduction to [Link] — Slide 77

16. Explain escape sequences in Python.

Answer: Escape sequences are special character combinations preceded by a backslash (\) used to
represent non-printable or special characters in strings (e.g., \n for newline, \t for tab, \\ for
backslash).

Reference: Lec 1. Introduction to [Link] — Slide 82

17. What is raw string?

Answer: A raw string is created by prefixing a string literal with r or R (e.g., r"C:\test\new"). It treats
backslashes as literal characters and disables escape sequence translation.

Reference: Lec 1. Introduction to [Link] — Slide 85

18. What is string concatenation?

Answer: String concatenation is the process of joining two or more strings together to form a new
string using the + operator (e.g., 'Py' + 'thon' yields 'Python').

Reference: Lec 1. Introduction to [Link] — Slide 88

19. Explain mutable and immutable objects.


Answer:

• Mutable Objects: Objects whose internal state or contents can be modified in-place after
creation (e.g., lists, dictionaries, sets).

• Immutable Objects: Objects whose value cannot be modified after creation. Modifying them
creates a new object in memory (e.g., integers, floats, strings, tuples).

Reference: Lec 1. Introduction to [Link] — Slides 91–95

20. Differentiate between list and tuple.

Answer:

• List: Defined with square brackets []. It is mutable (elements can be added/changed) and
slower.

• Tuple: Defined with parentheses (). It is immutable (cannot be changed once created) and
faster due to fixed memory allocation.

Reference: Lec 1. Introduction to [Link] — Slide 100

21. What is a list in Python?

Answer: A list is an ordered, mutable sequence of arbitrary elements (heterogeneous data types are
supported). It is written as a comma-separated list of values inside square brackets [...].

Reference: Lec 1. Introduction to [Link] — Slide 102

22. What is a tuple in Python?

Answer: A tuple is an ordered, immutable sequence of elements. It is written as a comma-separated


sequence inside parentheses (...) or even without parentheses.

Reference: Lec 1. Introduction to [Link] — Slide 105

23. Explain list operations with examples.

Answer: Common list operations include:

• Appending: [Link](val) (adds val at the end).

• Popping: [Link](index) (removes and returns item at index).

• Sorting: [Link]() (sorts list in-place).

• Example: L = [2, 1]; [Link](3); [Link](); # L becomes [1, 2, 3]

Reference: Lec 1. Introduction to [Link] — Slides 111–112

24. Explain tuple operations with examples.

Answer: Since tuples are immutable, support is restricted to non-modifying operations:

• Indexing & Slicing: t = (10, 20, 30); t[1] # returns 20

• Length: len(t) # returns 3

• Concatenation: t1 + t2 # returns new combined tuple


Reference: Lec 2, Print, Data Types [Link] — Slides 175–180

25. What is indexing?

Answer: Indexing is the technique of accessing a specific single element of a sequence (like a string,
list, or tuple) by utilizing its numerical position.

Reference: Lec 1. Introduction to [Link] — Slide 74

26. What is slicing?

Answer: Slicing is the technique of extracting a continuous subset (slice) of elements from a
sequence using index boundaries ([start:stop:step]).

Reference: Lec 1. Introduction to [Link] — Slide 77

27. Explain arithmetic operators.

Answer: Arithmetic operators perform standard mathematical calculations:

• + (Addition), - (Subtraction), * (Multiplication), / (Floating division), // (Floor/Integer


division), % (Modulus), (Exponentiation).

Reference: Lec 3, Array, If_else.pdf — Slides 185–189

28. Explain relational operators.

Answer: Relational (comparison) operators compare values and return a boolean value (True or
False):

• == (Equal to), != (Not equal to), > (Greater than), < (Less than), >= (Greater than or equal to),
<= (Less than or equal to).

Reference: Lec 3, Array, If_else.pdf — Slides 190–194

29. Explain logical operators.

Answer: Logical operators combine conditional statements:

• and: Returns True if both conditions are true.

• or: Returns True if at least one condition is true.

• not: Inverts the boolean value of the condition.

Reference: Lec 3, Array, If_else.pdf — Slides 195–198

30. Explain assignment operators.

Answer: Assignment operators assign values to variables. They include simple assignment (=) and
compound assignments that combine operation and assignment (e.g., +=, -=, *=, /=, %=).

Reference: Lec 3, Array, If_else.pdf — Slides 199–203

31. What is the use of input() function?

Answer: The input() function prompts the user for keyboard input and returns it as a string. To use it
for calculations, it must be cast (typecast) to another numerical type.
Reference: Lec 3, Array, If_else.pdf — Slides 211–212

32. Explain print() formatting.

Answer: The print() function formats output using:

1. Separators and End values: print("A", "B", sep="-", end="!")

2. F-Strings: print(f"Value is {val:.2f}")

3. format() method: print("Hello {} {}".format(f_name, l_name))

Reference: Lec 2, Print, Data Types [Link] — Slides 118–125

33. Explain comments in Python.

Answer: Comments are non-executable explanatory texts written to make code readable. Python
uses # for single-line comments.

Reference: Lec 2, Print, Data Types [Link] — Slide 126

34. What is docstring?

Answer: A docstring (documentation string) is a multi-line string literal enclosed in triple quotes
("""...""") placed as the first statement in a class, function, or module to document its purpose.

Reference: Lec 2, Print, Data Types [Link] — Slide 128

35. Explain indentation in Python.

Answer: Unlike languages that use curly braces, Python uses whitespaces (indentation) to define
block scopes (e.g., bodies of loops, functions, conditionals). All lines within the same block must have
identical indentation levels (typically 4 spaces).

Reference: Lec 2, Print, Data Types [Link] — Slides 131–134

36. Define syntax error.

Answer: A syntax error occurs when the code violates the grammatical rules of the Python language.
It is detected by the interpreter during parsing before the program runs.

Reference: Lec 2, Print, Data Types [Link] — Slide 152

37. Define runtime error.

Answer: A runtime error (or Exception) is an error that occurs during program execution despite
having correct syntax (e.g., dividing by zero ZeroDivisionError or referencing a non-existent file).

Reference: Lec 2, Print, Data Types [Link] — Slide 154

38. Define logical error.

Answer: A logical error occurs when the program runs without crashing but produces incorrect,
unintended outputs due to flawed logic in the algorithm.

Reference: Lec 2, Print, Data Types [Link] — Slide 156

39. Explain Python memory model.


Answer: Python stores values as objects in a private heap. Variables are pointers/references pointing
to these memory locations. Python's built-in garbage collector automatically manages allocation and
reclaims memory when an object's reference count drops to zero.

Reference: Lec 2, Print, Data Types [Link] — Slides 140–145

40. Explain local and global variables.

Answer:

• Local Variables: Defined inside a function and accessible only within that function's scope.

• Global Variables: Defined outside any function body and accessible from anywhere within
the module.

Reference: Lec 5, [Link] — Slides 340–345

41. Explain if statement.

Answer: The basic if statement evaluates a condition. If the condition is True, its indented block of
code is executed; otherwise, it is skipped.

Reference: Lec 3, Array, If_else.pdf — Slides 218–220

42. Explain if-else statement.

Answer: An if-else statement provides an alternative path. If the condition evaluates to True, the if
block executes; otherwise, the else block executes.

Reference: Lec 3, Array, If_else.pdf — Slides 221–224

43. Explain nested if statement.

Answer: A nested if is an if or if-else statement placed inside another if or else block to test
secondary conditions.

Reference: Lec 3, Array, If_else.pdf — Slides 225–228

44. Explain for loop with example.

Answer: A for loop is used to iterate over elements of any sequence (like a list, string, or range of
integers).

Example:

for i in range(3):

print(i) # Prints 0, 1, 2

Reference: Lec 4, while, [Link] — Slides 255–262

45. Explain while loop with example.

Answer: A while loop repeatedly executes its block of code as long as a specified condition remains
True.

Example:

i=1
while i < 3:

print(i)

i += 1 # Prints 1, 2

Reference: Lec 4, while, [Link] — Slides 245–252

46. Differentiate between while and for loops.

Answer:

• while loop: Condition-controlled; executes an indefinite number of times until its condition
evaluates to False. Requires manual step increments.

• for loop: Collection/Sequence-controlled; iterates a definite, predetermined number of


times over a specified sequence.

Reference: Lec 4, while, [Link] — Slide 265

47. Explain break statement.

Answer: The break statement immediately terminates the loop execution in which it is contained,
transfering execution flow to the statement immediately following the loop.

Reference: Lec 4, while, [Link] — Slides 280–282

48. Explain continue statement.

Answer: The continue statement skips the remaining statements in the current iteration of the loop
and jumps directly to the evaluation of the next iteration's condition.

Reference: Lec 4, while, [Link] — Slides 283–285

49. Explain pass statement.

Answer: The pass statement is a null statement used as a placeholder in Python blocks (like empty
functions, classes, or loops) where syntactic requirements demand code but no action is needed.

Reference: Lec 4, while, [Link] — Slide 288

50. What is recursion?

Answer: Recursion is a programming technique where a function calls itself, directly or indirectly, to
break a problem down into smaller self-similar sub-problems. It requires a base case to prevent
infinite loops.

Reference: Lec 5, [Link] — Slide 360

51. Explain recursive function with example.

Answer: A function that implements recursion. For example, computing factorial:

def fact(n):

if n == 1 or n == 0: # Base case

return 1
return n * fact(n - 1) # Recursive call

Reference: Lec 5, [Link] — Slides 361–365

52. Explain function definition.

Answer: A function definition declares a reusable block of code using the def keyword, followed by
the function name, parameters in parentheses, a colon (:), and an indented block of code.

Reference: Lec 5, [Link] — Slides 305–308

53. Explain function calling.

Answer: To invoke (execute) a defined function, you write its name followed by parentheses
containing any arguments required by the function (e.g., greet_student("Amit")).

Reference: Lec 5, [Link] — Slide 309

54. Explain return statement.

Answer: The return statement exits a function and optionally passes back a computed value or
values to the caller. If omitted, the function implicitly returns None.

Reference: Lec 5, [Link] — Slides 312–315

55. Explain positional arguments.

Answer: Positional arguments are passed to a function based on their order in the function call. The
first argument maps to the first parameter, the second to the second, etc.

Reference: Lec 5, [Link] — Slide 325

56. Explain keyword arguments.

Answer: Keyword arguments are passed to a function using the parameter names explicitly in the
call (parameter=value). This allows passing arguments in any order.

Reference: Lec 5, [Link] — Slide 328

57. Explain default arguments.

Answer: Default arguments are parameters that take predefined fallback values if no arguments are
passed for them during the function call (e.g., def greet(name="User")).

Reference: Lec 5, [Link] — Slide 332

58. Differentiate between *args and kwargs.

Answer:

• *args: Collects extra positional arguments as an immutable tuple.

• kwargs: Collects extra keyword (named) arguments as a mutable dictionary.

Reference: Lec 5, [Link] — Slides 425–426

59. Explain lambda function.


Answer: A lambda function is an anonymous, single-line function defined without the def keyword
using the lambda syntax: lambda arguments: expression. It is often used for short, throwaway
operations.

Reference: Lec 5, [Link] — Slides 380–385

60. Explain range() function.

Answer: The range() function returns an immutable sequence of numbers, commonly used for
looping a specific number of times. Syntax: range(start, stop, step).

Reference: Lec 4, while, [Link] — Slides 270–273

61. Explain len() function.

Answer: len() is a built-in function that returns the total count of items in an object, such as
characters in a string, or elements in a list, tuple, or dictionary.

Reference: Lec 1. Introduction to [Link] — Slide 104

62. Explain type() function.

Answer: type() is a built-in function that returns the class type of an object (e.g., <class 'int'> for
integers, <class 'list'> for lists).

Reference: Lec 1. Introduction to [Link] — Slide 60

63. Explain round() function.

Answer: round(number, ndigits) rounds a floating-point number to its nearest integer value, or to a
specified number of decimal digits (ndigits).

Reference: Lec 3, Array, If_else.pdf — Slide 241

64. Explain enumerate() function.

Answer: enumerate(iterable) returns an iterator yielding pairs containing an index counter (starting
at 0) and the values obtained from iterating over the sequence.

Reference: Lec 5, [Link] — Slide 350

65. Explain zip() function.

Answer: zip(*iterables) aggregates elements from each of the iterables into tuples and returns an
iterator of tuples (e.g., pairing keys with values).

Reference: Lec 5, [Link] — Slide 352

66. Write Python syntax for factorial calculation.

Answer: ```python import math fact = [Link](n)

**Reference:** `Lec 5, [Link]` — Slide 362

#### 67. Write Python syntax for Fibonacci series.

**Answer:** ```python
a, b = 0, 1

for _ in range(n):

print(a, end=" ")

a, b = b, a + b

Reference: Lec 5, [Link] — Slide 366

68. Write Python syntax for palindrome checking.

Answer: ```python is_palindrome = (string == string[::-1])

**Reference:** `Lec 2, Print, Data Types [Link]` — Slide 170

#### 69. Write Python syntax for prime number checking.

**Answer:** ```python

is_prime = n > 1 and all(n % i != 0 for i in range(2, int(n**0.5) + 1))

Reference: Lec 4, while, [Link] — Slide 299

70. Write Python syntax for swapping two variables.

Answer: ```python x, y = y, x

**Reference:** `Lec 1. Introduction to [Link]` — Slide 34

#### 71. Write Python syntax for list traversal.

**Answer:** ```python

for item in my_list:

print(item)

Reference: Lec 1. Introduction to [Link] — Slide 111

72. Write Python syntax for tuple creation.

Answer: ```python my_tuple = (1, 2, 3)

**Reference:** `Lec 1. Introduction to [Link]` — Slide 105

#### 73. Write Python syntax for taking user input.

**Answer:** ```python

user_input = input("Enter prompt: ")

Reference: Lec 3, Array, If_else.pdf — Slide 211

74. Write Python syntax for nested loop.


Answer: ```python for i in range(3): for j in range(2): print(i, j)

**Reference:** `Lec 4, while, [Link]` — Slide 263

#### 75. Predict the output:

```python

print(type('5'))

print(type(5))

Answer:

<class 'str'>

<class 'int'>

Reference: Lec 1. Introduction to [Link] — Slide 60

76. Predict the output:

x = [1, 2, 3]

[Link](4)

print(x)

Answer:

[1, 2, 3, 4]

Reference: Lec 1. Introduction to [Link] — Slide 111

77. Predict the output:

for i in range(3):

print(i)

Answer:

Reference: Lec 4, while, [Link] — Slide 270

78. Predict the output:

print('Hello' + 'World')

Answer:

HelloWorld

Reference: Lec 1. Introduction to [Link] — Slide 88


79. Identify the error:

if x = 5:

print(x)

Answer: SyntaxError: invalid syntax. The assignment operator = is used inside the conditional
evaluation statement instead of the equality comparison operator ==.

Reference: Lec 3, Array, If_else.pdf — Slide 190

80. Identify the error:

for i in range(5)

print(i)

Answer: SyntaxError: expected ':'. The for loop definition statement lacks the closing block colon (:).

Reference: Lec 4, while, [Link] — Slide 255

81. Identify the error:

print('Hello)

Answer: SyntaxError: unterminated string literal. The single-quoted string literal is never closed.

Reference: Lec 1. Introduction to [Link] — Slide 71

82. Differentiate between syntax error and logical error.

Answer:

• Syntax Error: Grammatical code mistake that stops parsing and halts compilation (e.g.,
missing parenthesis).

• Logical Error: Algorithm flow mistake that yields incorrect outputs but allows program
execution without crash.

Reference: Lec 2, Print, Data Types [Link] — Slides 152–157

83. Differentiate between runtime error and syntax error.

Answer:

• Syntax Error: Discovered before execution during compilation/parsing.

• Runtime Error: Discovered during execution when an illegal operation is triggered (e.g.,
division by zero).

Reference: Lec 2, Print, Data Types [Link] — Slides 152–155

84. Explain advantages of Python.

Answer: High readability, extensive third-party integration, cross-platform support, dynamic speed of
development, and built-in advanced standard modules.

Reference: Lec 1. Introduction to [Link] — Slides 10–15

85. Explain applications of Python.


Answer: Web scraping, Automation scripting, Artificial Intelligence and Machine Learning, Web
application development, GUI design, Scientific Engineering calculations, and Data Analysis.

Reference: Lec 1. Introduction to [Link] — Slide 18

86. Explain Python development environment.

Answer: An environment equipped to write, debug, compile, and execute Python code. It includes
the Python interpreter, pip package manager, virtual environment support, and text-editor/IDE
interfaces.

Reference: Lec 1. Introduction to [Link] — Slide 3

87. Explain Jupyter Notebook.

Answer: An open-source interactive web application that allows you to create and share documents
containing live code, mathematical equations, visualizations, and narrative text.

Reference: Lec 1. Introduction to [Link] — Slide 3

88. Explain Python IDEs.

Answer: Integrated Development Environments (IDEs) are software applications that provide
comprehensive software development facilities, typically consisting of a source code editor, build
automation tools, and a debugger (e.g., PyCharm, VS Code, Spyder).

Reference: Lec 1. Introduction to [Link] — Slide 3

89. Explain pip installation command.

Answer: pip (Preferred Installer Program) is Python's package manager. The standard terminal syntax
to download and install a library from PyPI is: pip install package_name.

Reference: Lec 1. Introduction to [Link] — Slide 3

90. Explain Python bytecode.

Answer: Python compiles source code (.py) into intermediate, platform-independent bytecode
instructions (.pyc). This code is executed by the virtual machine.

Reference: Lec 1. Introduction to [Link] — Slide 26

91. Explain Python Virtual Machine (PVM).

Answer: The PVM is the runtime engine of the Python interpreter that reads and executes compiled
Python bytecode instruction streams on the target machine host.

Reference: Lec 1. Introduction to [Link] — Slide 27

CO2: OOP, GUI and Exception Handling

1. Define class and object.

Answer:

• Class: A user-defined blueprint, structural template, or layout containing methods and


attributes.
• Object: A concrete instance of a class with specific allocated states and behaviors.

Reference: Lec 7, [Link] — Slide 474

2. Explain attributes and methods.

Answer:

• Attributes: Variables representing the properties or state data associated with a class or
object instance.

• Methods: Functions defined inside a class scope that operate on the objects' attributes.

Reference: Lec 7, [Link] — Slide 476

3. Explain constructor.

Answer: A constructor is a special class method automatically called when a new instance object is
instantiated. In Python, it is represented by the __init__(self, ...) magic method.

Reference: Lec 7, [Link] — Slide 480

4. Explain self keyword.

Answer: In class definitions, the self parameter represents the specific runtime instance of the object
being modified or queried. It allows instance methods to access attributes and other methods.

Reference: Lec 7, [Link] — Slide 482

5. Explain encapsulation.

Answer: Encapsulation is the principle of wrapping attributes and methods within a single class and
restricting direct external access to secure internal states (using private prefixes like __).

Reference: Lec 7, [Link] — Slide 490

6. Explain inheritance.

Answer: Inheritance allows a child (derived) class to inherit attributes and methods from a parent
(base) class, promoting code reusability.

Reference: Lec 7, [Link] — Slide 495

7. Explain polymorphism.

Answer: Polymorphism allows different classes to define methods with the same name, or operators
to perform different behaviors depending on their operand classes (method overriding/operator
overloading).

Reference: Lec 7, [Link] — Slide 505

8. Explain abstraction.

Answer: Abstraction hides complex internal implementation details and shows only essential, clean
interface controls to the external caller.

Reference: Lec 7, [Link] — Slide 512

9. Explain data hiding.


Answer: Data hiding is an implementation detail of encapsulation where variables are made private
by prefixing their identifiers with double underscores __. This activates name mangling, which
prevents external access.

Reference: Lec 7, [Link] — Slide 492

10. Differentiate procedural and OOP.

Answer:

• Procedural: Structure is based on modular functional routines/procedures operating on


global or passed data structures.

• OOP: Structure is organized around self-contained objects containing both data (attributes)
and behavior (methods).

Reference: Lec 7, [Link] — Slide 475

11. Explain method overloading.

Answer: Method overloading refers to defining multiple methods with the same name but different
signatures. Python does not support traditional compile-time method overloading directly; instead, it
is implemented using default/keyword arguments or variable arguments (*args).

Reference: Lec 7, [Link] — Slide 508

12. Explain method overriding.

Answer: Method overriding occurs when a child class provides a specialized implementation of a
method that is already defined in its parent class.

Reference: Lec 7, [Link] — Slide 506

13. Explain single inheritance.

Answer: A child class inherits attributes and methods from a single parent base class.

Reference: Lec 7, [Link] — Slide 496

14. Explain multilevel inheritance.

Answer: A subclass inherits from a child class, creating a multi-tiered parent-child ancestry chain
(e.g., Class C inherits from Class B, which inherits from Class A).

Reference: Lec 7, [Link] — Slide 497

15. Explain hierarchical inheritance.

Answer: Multiple independent child classes inherit from a single common parent base class.

Reference: Lec 7, [Link] — Slide 498

16. Explain operator overloading.

Answer: Operator overloading defines special behaviors for standard operators (like +, -, *) when
they are used with custom objects, by implementing special magic methods (like __add__, __sub__).

Reference: Lec 7, [Link] — Slide 510


17. Explain dynamic binding.

Answer: Dynamic binding (or late binding) is the mechanism where the resolution of a polymorphic
method call is deferred to runtime based on the actual type of the object, not the reference type.

Reference: Lec 7, [Link] — Slide 511

18. Explain class variables.

Answer: Class variables are variables defined directly inside the class block but outside any methods.
They are shared across all instances of that class.

Reference: Lec 7, [Link] — Slide 485

19. Explain instance variables.

Answer: Instance variables are variables bound to a specific class instance object (typically defined
inside __init__ with self.). Their values are unique to each object.

Reference: Lec 7, [Link] — Slide 486

20. Explain static methods.

Answer: Static methods are methods bound to a class rather than its objects. They cannot modify
class or instance state and are defined using the @staticmethod decorator.

Reference: Lec 7, [Link] — Slide 515

21. Explain class methods.

Answer: Class methods are bound to the class itself and receive the class as their first argument (cls).
They can modify class-wide state and are marked with @classmethod.

Reference: Lec 7, [Link] — Slide 516

22. Explain destructor.

Answer: A destructor is a special method called automatically when an object's reference count
drops to zero and it is about to be garbage collected. In Python, it is defined using __del__(self).

Reference: Lec 7, [Link] — Slide 488

23. Explain exception handling.

Answer: Exception handling is a mechanism that catches and resolves runtime errors without
crashing the program, using structured blocks.

Reference: Lec 5, [Link] — Slide 428 (and general concept)

24. Explain try-except block.

Answer: Code that might raise a runtime exception is placed inside a try block. If an exception
occurs, execution immediately jumps to the matching except block to handle the error.

Reference: Lec 5, [Link] — Slide 428

25. Explain finally block.


Answer: The finally block is placed after try-except and is guaranteed to execute regardless of
whether an exception occurred or was handled. It is typically used for clean-up tasks like closing
database connections or files.

Reference: Lec 6, [Link] — Slide 435

26. Explain raise statement.

Answer: The raise statement allows a programmer to manually trigger a specific exception (built-in
or user-defined) when custom validation rules are broken.

Reference: Lec 7, [Link] — Slide 530 (e.g., raise ValueError('Negative radius'))

27. Explain user-defined exceptions.

Answer: Programmers can create custom, domain-specific exception types by defining a class that
inherits from the built-in Exception base class.

Reference: General Python Concept (Outside provided slide content)

28. Write divide-by-zero exception program.

Answer:

try:

num = int(input("Enter numerator: "))

den = int(input("Enter denominator: "))

result = num / den

print("Result:", result)

except ZeroDivisionError:

print("Error: Denominator cannot be zero!")

Reference: Lec 5, [Link] — Slide 428

29. Explain event-driven programming.

Answer: Event-driven programming is a paradigm where the program's execution flow is determined
by external events, such as mouse clicks, keypresses, sensor signals, or messages from other threads.

Reference: General Python Concept (Syllabus Module 3 topic, outside detailed lecture slides 1–7)

30. Explain GUI programming.

Answer: Graphical User Interface (GUI) programming is the process of creating visual window
interfaces with buttons, textboxes, and menus to allow intuitive user interaction with the application.

Reference: General Python Concept (Syllabus Module 3 topic, outside detailed lecture slides 1–7)

31. Explain Tkinter widgets.

Answer: Tkinter is Python's standard GUI library. Widgets are visual component objects used to build
interfaces (e.g., Button, Label, Entry for inputs, Text for multi-line inputs, Frame for layout
organization).
Reference: General Python Concept (Syllabus Module 3 topic)

32. Explain event handling.

Answer: Event handling is the mechanism that binds a specific user action (like a button click) to an
executable Python function (often called an event handler or callback).

Reference: General Python Concept (Syllabus Module 3 topic)

33. Explain timer operations.

Answer: Timer operations allow scheduling a function to run after a specific delay, or executing a
task repeatedly at fixed time intervals (using Python's [Link] or Tkinter's .after() method).

Reference: General Python Concept (Syllabus Module 3 topic)

34. Explain multithreading.

Answer: Multithreading allows a program to run multiple threads of execution concurrently within a
single process share-space. It is useful for overlapping I/O operations (like network requests or disk
reads) to keep user interfaces responsive.

Reference: General Python Concept (Syllabus Module 3 topic)

35. Explain thread synchronization.

Answer: Thread synchronization is the coordination of concurrent threads to ensure they do not
access shared resources (critical sections) simultaneously, using mechanisms like locks, semaphores,
or events to prevent data corruption.

Reference: General Python Concept (Syllabus Module 3 topic)

36. Explain concurrent programming.

Answer: Concurrent programming is a design technique where multiple computational tasks execute
during overlapping time intervals, either on a single core (via task-switching) or across multiple
processor cores.

Reference: General Python Concept (Syllabus Module 3 topic)

37. Explain daemon thread.

Answer: A daemon thread is a background service thread that does not block the main program
from exiting. When all non-daemon threads finish executing, Python automatically terminates any
remaining daemon threads and exits the program.

Reference: General Python Concept (Syllabus Module 3 topic)

38. Explain race condition.

Answer: A race condition occurs in concurrent programs when multiple threads simultaneously read
and write to a shared variable, and the final state depends on the unpredictable execution order of
the threads.

Reference: General Python Concept (Syllabus Module 3 topic)

39. Explain deadlock.


Answer: A deadlock is a state where two or more concurrent threads are unable to proceed because
each is waiting for a resource that is currently held locked by another thread, creating a cycle of
infinite waiting.

Reference: General Python Concept (Syllabus Module 3 topic)

40. Explain callback function.

Answer: A callback is a reference to an executable function passed as an argument to another


function, which is designed to be executed ("called back") when a specific event occurs or a task
completes.

Reference: General Python Concept (Syllabus Module 3 topic)

41. Explain GUI event loop.

Answer: The event loop is an infinite monitoring loop (e.g., [Link]()) that continuously listens
for system event signals (like keyboard presses or clicks) and dispatches them to their corresponding
registered callback functions.

Reference: General Python Concept (Syllabus Module 3 topic)

42. Explain modular programming.

Answer: Modular programming is a design technique that splits a large program into separate,
independent, self-contained sub-units (modules) to simplify development, debugging, and code
reusability.

Reference: Lec 5, [Link] — Slide 302

43. Explain package and module.

Answer:

• Module: A single Python file (.py) containing runnable code, functions, variables, or class
definitions.

• Package: A directory folder containing multiple modules and an initialization file


(__init__.py).

Reference: Lec 6, [Link] — Slide 429 (and general concept)

44. Explain import statement.

Answer: The import statement loads external modules or specific functions into your current file's
namespace (e.g., import math or from math import pi).

Reference: Lec 6, [Link] — Slide 430

45. Explain debugging techniques.

Answer: Debugging is the process of locating and resolving code errors. Common techniques include
dry-running code, inserting diagnostic print() statements to track variable states, using assert
statements, and utilizing interactive debuggers (like Python's built-in pdb module or IDE debuggers).

Reference: Lec 1. Introduction to [Link] — Slide 113

CO3: File Handling, Libraries and Applications


1. Explain file handling.

Answer: File handling refers to the operations performed to store, retrieve, or update data inside
external physical files on a non-volatile storage disk (like a hard drive or SSD), providing data
persistence.

Reference: Lec 6, [Link] — Slide 430

2. Explain file opening and closing.

Answer:

• Opening: Done using the built-in open(filename, mode) function, which returns a file object
to interact with.

• Closing: Done by calling the .close() method on the file object to free up system resources.

Reference: Lec 6, [Link] — Slide 431

3. Explain file modes.

Answer: File modes specify the operations allowed on an opened file:

• 'r': Read-only (default).

• 'w': Write-only (creates a new file or overwrites an existing one).

• 'a': Append (writes new data to the end of an existing file).

• 'b': Binary mode (for images, executables, etc.).

• 't': Text mode (default).

Reference: Lec 6, [Link] — Slide 432

4. Explain read() function.

Answer: The read(size) method reads and returns a specified number of bytes/characters from a file.
If the size parameter is omitted, it reads the entire contents of the file as a single string.

Reference: Lec 6, [Link] — Slide 436

5. Explain readline() function.

Answer: readline() reads and returns a single line from the file, up to and including the newline
character (\n). Calling it again reads the next line.

Reference: Lec 6, [Link] — Slide 438

6. Explain readlines() function.

Answer: readlines() reads all remaining lines in a file and returns them as a Python list of strings,
where each string represents a single line.

Reference: Lec 6, [Link] — Slide 440

7. Explain write() function.


Answer: The write(string) method writes a string of characters directly to the target file. It does not
automatically append a newline character (\n).

Reference: Lec 6, [Link] — Slide 442

8. Explain writelines() function.

Answer: writelines(list_of_strings) takes an iterable (like a list) containing strings and writes them to
the file in sequence. It does not automatically add newline separators.

Reference: Lec 6, [Link] — Slide 444

9. Explain append mode.

Answer: Append mode ('a') opens a file for writing, but places the file pointer at the very end. This
ensures that any new data written is added to the end of the existing content, preserving what was
already there.

Reference: Lec 6, [Link] — Slide 433

10. Explain with statement.

Answer: The with statement acts as a context manager. It automatically closes files or releases
resources once execution leaves its code block, even if an exception occurs inside.

with open("[Link]", "r") as file:

data = [Link]()

# file is closed automatically here

Reference: Lec 6, [Link] — Slide 446

11. Explain binary files.

Answer: Binary files contain data in raw bytes without character encodings (like UTF-8). They
represent non-text objects such as images, audio files, compiled code, or PDF documents, and are
opened with the 'b' flag (e.g., 'rb', 'wb').

Reference: Lec 6, [Link] — Slide 448

12. Explain text files.

Answer: Text files store data as a sequence of characters encoded in a standard system format (like
ASCII or UTF-8). Lines are separated by standard end-of-line termination characters.

Reference: Lec 6, [Link] — Slide 448

13. Explain CSV file handling.

Answer: CSV (Comma-Separated Values) files store tabular data in plain text. Python handles them
using the built-in csv module, which provides helper classes like [Link] and [Link] to read and
write rows of data.

Reference: Lec 6, [Link] — Slides 455–460

14. Explain JSON file handling.


Answer: JSON (JavaScript Object Notation) is a lightweight, text-based data interchange format.
Python processes JSON using the built-in json module, which translates between Python types (like
dictionaries/lists) and JSON text strings.

Reference: Lec 6, [Link] — Slides 461–465

15. Explain serialization.

Answer: Serialization is the process of converting complex in-memory runtime objects (such as
dictionaries, objects, or arrays) into a byte stream or text string format (like JSON, CSV, or Pickle
bytes) so they can be saved to a file or sent over a network.

Reference: Lec 6, [Link] — Slide 466

16. Explain deserialization.

Answer: Deserialization is the reverse process of serialization. It reads a serialized text string or byte
stream from a file or network and converts it back into active in-memory Python objects.

Reference: Lec 6, [Link] — Slide 467

17. Explain NumPy library.

Answer: NumPy (Numerical Python) is a fundamental library for scientific computing in Python. It
provides high-performance, multi-dimensional array objects and a collection of mathematical
routines to operate on them efficiently.

Reference: General Python Concept (Syllabus Module 3 topic, outside detailed lecture slides 1–7)

18. Explain NumPy arrays.

Answer: NumPy arrays (ndarray) are homogeneous, multi-dimensional arrays. Unlike Python's
standard lists, all elements in a NumPy array must be of the same data type, allowing operations to
be executed in compiled C code for maximum performance.

Reference: General Python Concept (Syllabus Module 3 topic)

19. Explain matrix operations using NumPy.

Answer: NumPy supports vectorized matrix operations (like element-wise arithmetic, dot products,
transpositions, and matrix inversions) without requiring manual loops, using optimized linear algebra
libraries behind the scenes.

Reference: General Python Concept (Syllabus Module 3 topic)

20. Explain Pandas library.

Answer: Pandas is an open-source library built on top of NumPy that provides high-performance,
easy-to-use data structures and data analysis tools, designed specifically for working with structured
or tabular datasets.

Reference: General Python Concept (Syllabus Module 3 topic)

21. Explain DataFrame.

Answer: A DataFrame is a two-dimensional, heterogeneous, size-mutable tabular data structure with


labeled axes (rows and columns), similar to a spreadsheet or SQL database table.
Reference: General Python Concept (Syllabus Module 3 topic)

22. Explain Series in Pandas.

Answer: A Series is a one-dimensional array-like object capable of holding any data type,
accompanied by a labeled index that identifies each item in the array.

Reference: General Python Concept (Syllabus Module 3 topic)

23. Explain Matplotlib.

Answer: Matplotlib is a comprehensive data visualization library in Python used for creating static,
animated, and interactive plots, charts, and figures.

Reference: General Python Concept (Syllabus Module 3 topic)

24. Explain plotting graphs.

Answer: Graph plotting is done using the [Link] module. It allows you to customize and
render scientific plots (like line graphs, scatter plots, bar charts, and histograms) using simple
function calls.

Reference: General Python Concept (Syllabus Module 3 topic)

25. Explain OpenCV.

Answer: OpenCV (Open Source Computer Vision Library) is a powerful, real-time computer vision
and image processing library with interfaces for Python, C++, and Java.

Reference: General Python Concept (Syllabus Module 3 topic)

26. Explain camera interfacing.

Answer: Camera interfacing is the process of establishing a data connection to a video camera or
webcam to capture live video frames, typically achieved using OpenCV's [Link]() class.

Reference: General Python Concept (Syllabus Module 3 topic)

27. Explain image acquisition.

Answer: Image acquisition is the process of capturing digital frames from an active video feed, or
reading static image files (such as JPEG, PNG) into standard in-memory arrays (OpenCV represents
images as standard NumPy arrays).

Reference: General Python Concept (Syllabus Module 3 topic)

28. Explain image processing basics.

Answer: Basic image processing includes modifying image arrays to perform operations such as color
conversion (e.g., RGB to Grayscale), resizing, cropping, smoothing/filtering noise, and detecting
edges.

Reference: General Python Concept (Syllabus Module 3 topic)

29. Explain machine learning libraries.

Answer: These are dedicated toolkits providing pre-built, optimized algorithms and training
frameworks for building predictive models from data (e.g., Scikit-learn, TensorFlow, PyTorch).
Reference: General Python Concept (Syllabus Module 3 topic)

30. Explain Scikit-learn.

Answer: Scikit-learn is a popular machine learning library in Python. It provides simple and efficient
tools for data mining and predictive data analysis, including algorithms for classification, regression,
clustering, and dimensional reduction.

Reference: General Python Concept (Syllabus Module 3 topic)

31. Explain TensorFlow.

Answer: TensorFlow is an open-source, end-to-end platform developed by Google for deep learning
and machine neural network computations, designed to scale across multiple CPUs, GPUs, or TPUs.

Reference: General Python Concept (Syllabus Module 3 topic)

32. Explain Jupyter Notebook.

Answer: Jupyter Notebook is an interactive, browser-based environment that allows you to combine
runnable code, markdown annotations, mathematical equations, and inline data visualizations in a
single document.

Reference: Lec 1. Introduction to [Link] — Slide 3

33. Explain PyCharm IDE.

Answer: PyCharm is a dedicated, professional-grade Python IDE developed by JetBrains. It features


smart code completion, on-the-fly error highlighting, built-in debugging tools, and git version control
integration.

Reference: Lec 1. Introduction to [Link] — Slide 3

34. Explain package installation using pip.

Answer: pip downloads packages from the Python Package Index (PyPI). Run pip install library_name
in your terminal to download and install a package, making it available to import into your Python
scripts.

Reference: Lec 1. Introduction to [Link] — Slide 3

35. Explain virtual environment.

Answer: A virtual environment is an isolated runtime environment that allows you to install specific
packages and dependencies for a particular project without interfering with other projects or the
global system-wide Python installation.

Reference: General Python Concept (Syllabus Module 3 topic)

36. Write program to create text file.

Answer:

with open("[Link]", "w") as file:

[Link]("Amit, Roll: 12, Marks: 85\n")

Reference: Lec 6, [Link] — Slide 472


37. Write program to append data into file.

Answer:

with open("[Link]", "a") as file:

[Link]("Sujata, Roll: 14, Marks: 92\n")

Reference: Lec 6, [Link] — Slide 472

38. Write program to count lines in file.

Answer:

with open("[Link]", "r") as file:

line_count = len([Link]())

print("Total Lines:", line_count)

Reference: Lec 6, [Link] — Slide 472

39. Write CSV handling program.

Answer:

import csv

# Writing to CSV

with open("[Link]", "w", newline="") as file:

writer = [Link](file)

[Link](["Name", "Roll"])

[Link](["Amit", "12"])

# Reading from CSV

with open("[Link]", "r") as file:

reader = [Link](file)

for row in reader:

print(row)

Reference: Lec 6, [Link] — Slide 472

40. Write JSON handling program.

Answer:

import json

data = {"Name": "Amit", "Roll": 12}


# Writing to JSON

with open("[Link]", "w") as file:

[Link](data, file)

# Reading from JSON

with open("[Link]", "r") as file:

loaded_data = [Link](file)

print(loaded_data)

Reference: Lec 6, [Link] — Slide 472

41. Write NumPy matrix addition program.

Answer:

import numpy as np

matrixA = [Link]([[1, 2], [3, 4]])

matrixB = [Link]([[5, 6], [7, 8]])

result = matrixA + matrixB

print(result)

Reference: General Python Concept (Syllabus Module 3 topic)

42. Write Matplotlib plotting program.

Answer:

import [Link] as plt

x = [1, 2, 3, 4]

y = [10, 20, 25, 30]

[Link](x, y)

[Link]("X-Axis")

[Link]("Y-Axis")

[Link]()

Reference: General Python Concept (Syllabus Module 3 topic)

43. Write OpenCV webcam capture program.

Answer:

import cv2

cap = [Link](0)
while True:

ret, frame = [Link]()

if not ret:

break

[Link]("Webcam Live Feed", frame)

if [Link](1) & 0xFF == ord('q'):

break

[Link]()

[Link]()

Reference: General Python Concept (Syllabus Module 3 topic)

44. Explain role of Python in AI and ML.

Answer: Python's clean syntax allows developers to focus on building AI algorithms rather than
language complexities. It is backed by a mature ecosystem of highly optimized, low-level libraries
(like TensorFlow, PyTorch, NumPy, and Scikit-learn) for high-performance machine learning.

Reference: General Python Concept (Syllabus Module 3 topic)

45. Explain scientific computing applications.

Answer: In electrical engineering, Python is used for solving complex differential equations,
processing signals, analyzing power system load flow, running numerical optimizations, and
processing sensor data streams.

Reference: General Python Concept (Syllabus Module 3 topic)

SECTION B: SHORT / APPLICATION QUESTIONS (CO4, CO5)

CO4: Comparison, Evaluation and Programming Approaches

1. Compare procedural programming and object-oriented programming in Python.

Answer:

Feature Procedural Programming Object-Oriented Programming (OOP)

Functions, steps, and execution Self-contained objects containing data and


Focus
sequence. behavior.

Data Data moves freely around the program; Data is hidden (encapsulated) inside classes;
Security low security. high security.

Approach Top-down design methodology. Bottom-up design methodology.

Limited; relies heavily on copy-pasting or


Reusability Highly reusable through class inheritance.
modules.
Syllabus Used for modeling complex engineering
Common in basic scripting.
Link systems.

Reference: Lec 7, [Link] — Slide 475

2. Explain the principles of OOP with suitable examples.

Answer: The four core pillars of OOP are:

1. Encapsulation: Wrapping data and functions into a single class.

o Example: Class Circle wraps instance variables center, radius and methods get_area(),
grow().

2. Inheritance: Deriving new classes from existing ones.

o Example: A Subclass inheriting basic properties from a parent class.

3. Polymorphism: Having multiple classes implement methods with the same name.

o Example: Calling a common .draw() method on instances of both Circle and Square
classes.

4. Abstraction: Exposing only clean, essential interfaces to user inputs.

o Example: Calling [Link](pt) hides the mathematical transformation coordinate


calculations.

Reference: Lec 7, [Link] — Slides 490–512

3. Explain abstraction and encapsulation with suitable examples.

Answer:

• Encapsulation: Restricts direct access to an object's state to prevent corruption. In Python,


this is implemented by prefixing attributes with double underscores to make them private.

o Example:

o class BankAccount:

o def __init__(self, owner, balance):

o [Link] = owner

o self.__balance = balance # Encapsulated private attribute

• Abstraction: Hides the underlying complexity by defining a simple, clean interface.

o Example: An abstract class Vehicle can declare an abstract method start_engine().


The user calls start_engine() without needing to know the complex mechanics of
how the engine starts.

Reference: Lec 7, [Link] — Slide 490, 512

4. Explain inheritance and polymorphism with examples.

Answer:
• Inheritance: Reuses a parent class's attributes and methods in a child class.

• class Parent:

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

• class Child(Parent):

• pass

• c = Child()

• [Link]() # Inherited method

• Polymorphism: The ability of different objects to respond to the same method call in their
own specialized way.

• class Animal:

• def speak(self): pass

• class Dog(Animal):

• def speak(self): return "Woof!"

• class Cat(Animal):

• def speak(self): return "Meow!"

Reference: Lec 7, [Link] — Slide 495, 505

5. Compare compiler and interpreter.

Answer:

Dimension Compiler Interpreter

Translates the entire source code into binary Translates and executes the source code
Execution
machine code before execution. line-by-line at runtime.

Slower execution due to line-by-line


Speed Faster execution once compiled.
translation.

Difficult; reports all errors at the end of Easier; execution stops immediately on
Debugging
compilation. the line containing the error.

Does not produce separate executable


Output Generates an executable file (e.g., .exe).
files.

Reference: Lec 1. Introduction to [Link] — Slides 23–25

6. Explain advantages and disadvantages of interpreted languages.

Answer:

• Advantages:
o Easier Debugging: Execution stops immediately at the line with an error, making it
easy to identify.

o Rapid Prototyping: No compilation wait times; changes can be tested instantly.

o Dynamic Typing: Highly flexible development without rigid type declarations.

• Disadvantages:

o Slower Execution Speed: Running code line-by-line introduces interpreter runtime


overhead.

o No Static Type Validation: Type-related errors can go unnoticed until they are
triggered at runtime.

Reference: Lec 1. Introduction to [Link] — Slides 21–22

7. Compare mutable and immutable objects.

Answer:

Property Mutable Objects Immutable Objects

State can be changed in-place after


Definition State cannot be modified after creation.
creation.

Reuses the same memory address for Creating or modifying a value allocates a new
Memory
modifications. object in memory.

Examples list, dict, set int, float, str, tuple

Side Susceptible to unintended side effects Thread-safe and safe from unintended
Effects when shared. modifications.

Reference: Lec 1. Introduction to [Link] — Slides 91–95

8. Compare list and tuple in Python.

Answer:

Feature List Tuple

Syntax Enclosed in square brackets [1, 2]. Enclosed in parentheses (1, 2).

Mutable (elements can be modified, added, Immutable (cannot be changed after


Mutability
or removed). creation).

Size &
Dynamic; has higher memory overhead. Fixed size; memory efficient.
Memory

Supports operations like append(), insert(), Limited to read-only methods like


Methods
pop(). count(), index().

Reference: Lec 1. Introduction to [Link] — Slide 100

9. Compare while loop and for loop.


Answer:

• while loop:

o Type: Condition-controlled loop.

o Execution: Runs as long as a specified boolean condition evaluates to True.

o Use Case: Best when the exact number of iterations is unknown beforehand.

• for loop:

o Type: Collection/Sequence-controlled loop.

o Execution: Automatically iterates over elements of a sequence (like a list, tuple, or


range).

o Use Case: Best when iterating over a known, fixed sequence or range of elements.

Reference: Lec 4, while, [Link] — Slide 265

10. Compare append() and extend() functions.

Answer:

• append(element): Appends the passed argument as a single element to the end of the list. If
you pass a list, it adds the nested list itself as a single element.

• extend(iterable): Iterates over the passed iterable and appends each of its elements
individually to the end of the list, increasing the list's length accordingly.

Reference: Lec 2, Print, Data Types [Link] — Slide 181

11. Compare read(), readline() and readlines().

Answer:

• read(n): Reads and returns up to n characters (or the entire file contents if n is omitted) as a
single string.

• readline(): Reads and returns the next single line from the file as a string.

• readlines(): Reads all remaining lines in the file and returns them as a list of strings, with
each line being a separate item in the list.

Reference: Lec 6, [Link] — Slides 436–441

12. Compare local and global variables.

Answer:

Feature Local Variable Global Variable

Restricted to the function inside which it is Accessible throughout the entire module
Scope
defined. file.

Created when the function is called, and Persists from its definition until the
Lifetime
destroyed when it returns. program exits.
Requires the global keyword to modify
Modification Can be modified directly within its function.
from inside a function.

Reference: Lec 5, [Link] — Slides 340–345

13. Compare Python and C programming languages.

Answer:

Dimension Python C

High-level, Multi-paradigm (Procedural,


Paradigms Middle-level, Procedural only.
OOP, Functional).

Dynamically typed (variable types are Statically typed (types must be declared
Typing
resolved at runtime). explicitly).

Interpreted (compiled to bytecode, run by Statically compiled directly to machine


Execution
PVM). binary executables.

Manual memory management (using


Memory Automatic garbage collection.
malloc(), free()).

Reference: Lec 1. Introduction to [Link] — Slides 21–25

14. Compare Python and C++ in terms of OOP support.

Answer:

• Type Resolution: Python resolves types dynamically at runtime, whereas C++ uses static
compilation to resolve types at compile time.

• Access Control: Python relies on naming conventions (like a _ or __ prefix) for privacy rather
than enforcing strict access control. C++ strictly enforces access boundaries using keyword
access modifiers (private, public, protected).

• Multiple Inheritance: Both languages support multiple inheritance, but Python uses a
Method Resolution Order (MRO) algorithm to systematically resolve the diamond problem.

Reference: Lec 7, [Link] — Slide 475 (and general comparison)

15. Explain Python memory model with examples.

Answer: In Python, variables do not store data values directly; they are pointers or references to
objects created in a private system heap.

x = [1, 2]

y=x

# x and y both reference the same list object in memory

[Link](3)

print(x) # [1, 2, 3] (the change is reflected in both)

Reference: Lec 2, Print, Data Types [Link] — Slides 140–145


16. Explain Python Virtual Machine (PVM).

Answer: The PVM is the runtime engine of the Python interpreter. It is a virtual machine that runs a
continuous loop, reading compiled Python bytecode instructions, translating them into native
machine instructions, and executing them on the host processor.

Reference: Lec 1. Introduction to [Link] — Slide 27

17. Explain Python bytecode execution process.

Answer:

1. The developer writes high-level Python source code in a .py file.

2. The compiler parses the code and translates it into intermediate bytecode instructions,
saving them in a .pyc file (usually inside a __pycache__ folder).

3. The Python Virtual Machine (PVM) loads this bytecode, translates it line-by-line into native
machine instructions, and executes them on the host system.

Reference: Lec 1. Introduction to [Link] — Slide 26

18. Explain dynamic typing in Python.

Answer: In Python, variables do not have a fixed data type; only the objects they reference do. A
variable can be reassigned to reference objects of different types during execution.

x=5 # x references an integer object

x = "Five" # x now references a string object (perfectly valid)

Reference: Lec 1. Introduction to [Link] — Slide 32

19. Explain advantages of Python over other programming languages.

Answer: Python requires fewer lines of code to express concepts compared to languages like C or
Java. It features built-in high-level data structures (like lists and dictionaries) and has a vast
ecosystem of third-party libraries for domains like data science and machine learning, which
dramatically accelerates development speed.

Reference: Lec 1. Introduction to [Link] — Slides 10–15

20. Explain applications of Python in engineering.

Answer: In electrical and computer engineering, Python is used to analyze sensor data streams, run
power system simulations, automate instruments (via USB/serial protocols), run computer vision
systems on edge devices, and build graphical dashboards to monitor hardware systems in real time.

Reference: Lec 1. Introduction to [Link] — Slide 18

21. Explain object-oriented programming methodology.

Answer: OOP is a software design paradigm centered around modeling systems as collections of self-
contained, cooperating objects. Each object maintains its own internal state (attributes) and exposes
a clean interface (methods) to interact with other objects, promoting modularity, security, and
reusability.

Reference: Lec 7, [Link] — Slide 474


22. Explain modular programming with examples.

Answer: Modular programming splits a large codebase into smaller, independent, and reusable files
(modules).

• Example: Save custom mathematical operations in [Link]:

• # [Link]

• def solve_quadratic(a, b, c): ...

Import and use it in your main application:

# [Link]

from solver import solve_quadratic

Reference: Lec 5, [Link] — Slide 302

23. Explain event-driven programming.

Answer: Unlike traditional programs that follow a rigid execution flow, event-driven applications
remain in a waiting state inside an event loop. When an event occurs (such as a hardware signal,
timer tick, or user interaction), the event loop triggers the appropriate registered callback function to
handle it.

Reference: General Python Concept (Syllabus Module 3 topic)

24. Explain GUI programming using Tkinter.

Answer: GUI programming with Tkinter involves setting up a root window, placing visual widgets (like
buttons, labels, and text fields) inside it using a layout manager (like .pack(), .grid(), or .place()),
binding user events to Python functions, and running the .mainloop() event loop to start the
interface.

Reference: General Python Concept (Syllabus Module 3 topic)

25. Explain timer operations in Python.

Answer: Timer operations allow scheduling a function to run after a specific delay, or executing a
task repeatedly at fixed time intervals. In Tkinter, this is typically done using the non-blocking
[Link](milliseconds, callback) method, while standard programs use the [Link] class.

Reference: General Python Concept (Syllabus Module 3 topic)

26. Explain multithreading and concurrent execution.

Answer: Multithreading allows a program to split into multiple concurrent paths of execution. In
Python, the Global Interpreter Lock (GIL) limits execution to one thread at a time on a single CPU
core for CPU-bound tasks. However, multithreading remains highly effective for I/O-bound tasks (like
waiting for sensor data, file operations, or network requests), as it allows other tasks to run while
one is waiting.

Reference: General Python Concept (Syllabus Module 3 topic)

27. Explain thread synchronization with examples.


Answer: Thread synchronization coordinates concurrent threads to ensure they do not access or
modify shared resources (like variables or hardware registers) at the same time, preventing data
corruption.

from threading import Thread, Lock

lock = Lock()

shared_counter = 0

def increment():

global shared_counter

with lock: # Thread safely acquires the lock

shared_counter += 1

Reference: General Python Concept (Syllabus Module 3 topic)

28. Explain race condition and deadlock.

Answer:

• Race Condition: Occurs when multiple concurrent threads attempt to read and write to a
shared variable at the same time, resulting in an unpredictable and incorrect final state.

• Deadlock: Occurs when two or more threads are blocked indefinitely, each waiting for a lock
or resource held by the other, preventing either thread from proceeding.

Reference: General Python Concept (Syllabus Module 3 topic)

29. Explain debugging techniques in Python.

Answer: 1. Interactive Debuggers (pdb): Allows you to pause execution, step through code line-by-
line, and inspect variables at runtime. 2. Diagnostic Printing: Inserting strategic print() statements or
using Python's logging module to track program execution. 3. IDE Integration: Using visual debugging
tools in IDEs like PyCharm or VS Code to set breakpoints and monitor variables in real time.

Reference: Lec 1. Introduction to [Link] — Slide 113

30. Explain exception handling mechanism in Python.

Answer: Exception handling uses structured blocks to intercept and handle runtime errors,
preventing the program from crashing.

• try: Contains the block of code that might raise an exception.

• except: Catches and handles specific exceptions if they occur.

• else: Executes if the code in the try block runs successfully without raising any exceptions.

• finally: Always executes, regardless of whether an exception occurred, making it ideal for
clean-up tasks.

Reference: Lec 5, [Link] — Slide 428 (and general concept)


31. Explain syntax errors, logical errors and runtime errors.

Answer:

• Syntax Error: Grammatical code mistakes detected by the parser before the program runs
(e.g., missing colons).

• Runtime Error: An error that occurs while the program is running, typically due to invalid
data operations (e.g., dividing by zero or accessing a list index that doesn't exist).

• Logical Error: Flaws in the program's algorithm. The code runs without crashing, but
produces incorrect results (e.g., using + instead of *).

Reference: Lec 2, Print, Data Types [Link] — Slides 151–157

32. Explain Python IDEs and compare PyCharm, IDLE and Jupyter Notebook.

Answer:

• IDLE: Python's built-in, lightweight development environment. It is great for beginners and
simple scripting, but lacks advanced development features.

• PyCharm: A full-featured, professional IDE designed for large codebases. It features smart
code completion, visual debugging tools, refactoring capabilities, and integrated version
control.

• Jupyter Notebook: A web-based interactive environment that lets you run code in discrete
"cells". It is ideal for data analysis, scientific visualization, and sharing documented
experiments.

Reference: Lec 1. Introduction to [Link] — Slide 3

33. Explain package management using pip.

Answer: pip connects to the Python Package Index (PyPI) to automate downloading, installing,
updating, and removing third-party libraries. It also supports package configuration files, allowing
you to install all project dependencies at once using pip install -r [Link].

Reference: Lec 1. Introduction to [Link] — Slide 3

34. Explain modules and packages in Python.

Answer:

• Module: A single .py file containing reusable code, functions, classes, and variables.

• Package: A directory folder that groups related modules together. To be recognized as a


package, it must contain an initialization file (typically named __init__.py).

Reference: Lec 6, [Link] — Slide 429 (and general concept)

35. Explain scientific computing using Python libraries.

Answer: Standard Python list operations can be slow for large-scale mathematical computations.
Libraries like NumPy and SciPy solve this by implementing multi-dimensional array operations in
compiled C code, making scientific computing fast and efficient.

Reference: General Python Concept (Syllabus Module 3 topic)


36. Explain NumPy library and its applications.

Answer: NumPy is built around the ndarray object, a high-performance, multi-dimensional array
structure. It is widely used for linear algebra operations, Fourier transforms, random number
generation, and as the underlying data structure for most modern data science and machine learning
libraries.

Reference: General Python Concept (Syllabus Module 3 topic)

37. Explain Pandas library and data handling applications.

Answer: Pandas simplifies working with structured, tabular data by providing powerful data
structures like the DataFrame (a 2D table with labeled rows and columns) and the Series (1D labeled
array). It includes built-in tools for reading and writing data, handling missing values, merging
datasets, and grouping data for analysis.

Reference: General Python Concept (Syllabus Module 3 topic)

38. Explain Matplotlib library and data visualization.

Answer: Matplotlib is Python's standard data visualization library. Its pyplot module provides a
simple interface for generating high-quality scientific plots (such as line plots, scatter plots, bar
charts, and error bars) to help analyze and present data.

Reference: General Python Concept (Syllabus Module 3 topic)

39. Explain OpenCV and image processing applications.

Answer: OpenCV is an open-source computer vision library. It represents digital images as multi-
dimensional NumPy arrays of pixel intensity values. It is widely used for real-time video processing,
edge detection, color filtering, image resizing, and object detection.

Reference: General Python Concept (Syllabus Module 3 topic)

40. Explain machine learning applications using Python.

Answer: Python is the industry standard for machine learning. It is used to preprocess large datasets,
extract relevant features, train predictive models (for classification, regression, or clustering),
evaluate their accuracy, and deploy them to make predictions on new data.

Reference: General Python Concept (Syllabus Module 3 topic)

41. Explain TensorFlow and Scikit-learn libraries.

Answer:

• Scikit-learn: A library focused on traditional machine learning algorithms, providing simple


and efficient tools for tasks like regression, classification, clustering, and preprocessing.

• TensorFlow: A comprehensive deep learning framework developed by Google, designed for


building, training, and deploying large-scale neural networks across multiple CPUs or GPUs.

Reference: General Python Concept (Syllabus Module 3 topic)

42. Explain role of Python in Artificial Intelligence applications.


Answer: Python's clean and readable syntax allows developers to write complex AI logic without
getting bogged down by language complexities. It is supported by a massive ecosystem of libraries,
has a highly active community, and integrates easily with low-level languages like C/C++ to run
computationally intensive AI operations efficiently.

Reference: General Python Concept (Syllabus Module 3 topic)

43. Explain Python in client/server based applications.

Answer: Python is widely used to develop both back-end servers and APIs using frameworks like
Django or Flask, and client-side scripts using its built-in socket library. This makes it easy to build
network-based systems to transmit data between clients and servers.

Reference: General Python Concept (Syllabus Module 3 topic)

44. Explain USB/COM port interfacing using Python.

Answer: In electrical engineering, Python is often used to communicate with hardware instruments
(like microcontrollers or sensors) over a serial or USB connection. This is typically done using the
pyserial library, which allows Python to read and write bytes to active COM ports.

Reference: General Python Concept (Syllabus Module 3 topic)

45. Explain camera interfacing and image acquisition using OpenCV.

Answer: OpenCV interfaces with cameras using the [Link](index) class, which connects to
the camera's system driver. It captures video frames in a continuous loop, reading each frame as a 3D
NumPy array containing the Blue, Green, and Red (BGR) pixel values.

Reference: General Python Concept (Syllabus Module 3 topic)

46. Explain advantages of multithreading in Python.

Answer: While Python's GIL restricts CPU-bound tasks to a single thread, multithreading is highly
beneficial for I/O-bound tasks. It allows your program to remain responsive by running background
tasks (like downloading files or reading sensor data) while the main thread handles the user interface
or other operations.

Reference: General Python Concept (Syllabus Module 3 topic)

47. Explain callback functions and GUI event loop.

Answer: An event loop (like Tkinter's [Link]()) runs continuously in a non-blocking loop,
listening for user interactions or system events. When an event occurs, the loop dispatches it to its
registered callback function—a function reference passed to the widget to handle that specific
event.

Reference: General Python Concept (Syllabus Module 3 topic)

48. Explain serialization and deserialization.

Answer:

• Serialization: Converts active, in-memory Python objects (like dictionaries or lists) into a
standardized, transportable format (like a JSON string, CSV row, or binary byte stream) to
save to a file or send over a network.
• Deserialization: The reverse process, reading serialized data from a file or network and
converting it back into active in-memory Python objects.

Reference: Lec 6, [Link] — Slides 466–467

49. Explain CSV and JSON file handling.

Answer:

• CSV Handling: Python's built-in csv module reads and writes tabular data. It treats each line
as a row, converting comma-separated values into lists of strings.

• JSON Handling: Python's json module translates between JSON text and Python dictionaries
or lists, making it easy to store nested, hierarchical data structures.

Reference: Lec 6, [Link] — Slides 455–465

50. Explain Python development environment.

Answer: A Python development environment consists of the Python interpreter, package managers
(like pip), and virtual environments to manage dependencies. This is typically accessed through an
IDE or text editor equipped with debugging and run controls.

Reference: Lec 1. Introduction to [Link] — Slide 3

51. Explain integrated development environment (IDE).

Answer: An IDE is a comprehensive software application that groups together all the tools needed to
write and test software. This typically includes a smart code editor with syntax highlighting, build
automation tools, a debugger, and often version control integration.

Reference: Lec 1. Introduction to [Link] — Slide 3

52. Explain source code, bytecode and executable code.

Answer:

• Source Code: The high-level, human-readable Python code written by a developer (.py).

• Bytecode: The intermediate, platform-independent instructions generated by the compiler


(.pyc).

• Executable Code: The low-level, binary instructions that are native to the host computer's
processor and can be executed directly by the CPU.

Reference: Lec 1. Introduction to [Link] — Slides 26–27

53. Explain portability and extensibility features of Python.

Answer:

• Portability: Python bytecode can run on any system with a compatible Python Virtual
Machine (PVM) installed, allowing you to run the same code on Windows, macOS, or Linux
without modifications.

• Extensibility: Allows you to integrate modules written in low-level languages like C or C++
into your Python programs to speed up performance-critical operations.
Reference: Lec 1. Introduction to [Link] — Slide 12, 14

54. Explain embedded and extensible features of Python.

Answer:

• Extensible: You can call C or C++ code from within your Python programs, allowing you to
use existing low-level libraries or optimize performance-critical bottlenecks.

• Embeddable: You can embed the Python interpreter inside applications written in other
languages (like C or C++), allowing users to write scripts to customize or extend your
application.

Reference: Lec 1. Introduction to [Link] — Slide 14, 15

55. Explain object, method and event concepts in GUI programming.

Answer:

• Object: A visual component or widget in the user interface (e.g., a button, label, or text
field).

• Method: A function defined on a widget object used to query or modify its state (e.g.,
changing a label's text or disabling a button).

• Event: Any action triggered by the user or the system (such as a mouse click, keypress, or
timer tick) that can be bound to execute a specific function.

Reference: General Python Concept (Syllabus Module 3 topic)

56. Explain Python scripting and automation applications.

Answer: Python scripting automates repetitive tasks by writing short programs to perform
operations like batch-renaming files, parsing logs, scraping data from websites, or automatically
sending email notifications based on specific triggers.

Reference: Lec 1. Introduction to [Link] — Slide 18

57. Explain data abstraction and information hiding.

Answer:

• Data Abstraction: Exposes only the necessary, high-level interface of an object while hiding
its internal implementation details.

• Information Hiding: Prevents direct external access to an object's internal variables (typically
by prefixing them with double underscores __), protecting the object's state from
unintended modifications.

Reference: Lec 7, [Link] — Slide 492, 512

58. Explain operator overloading with examples.

Answer: Operator overloading allows you to define custom behaviors for standard Python operators
(like +, -, or *) when they are used with your own custom classes. This is done by implementing
special "magic" methods.

class Point:
def __init__(self, x, y):

self.x = x

self.y = y

def __add__(self, other): # Overloads the + operator

return Point(self.x + other.x, self.y + other.y)

Reference: Lec 7, [Link] — Slide 510

59. Explain method overriding with examples.

Answer: Method overriding allows a child class to provide a specialized implementation of a method
that is already defined in its parent class.

class Parent:

def greet(self):

print("Hello from Parent")

class Child(Parent):

def greet(self): # Overrides the parent method

print("Hello from Child")

Reference: Lec 7, [Link] — Slide 506

60. Explain class variables and instance variables.

Answer:

• Class Variables: Shared across all instances of a class. They are defined directly inside the
class block but outside any methods.

• Instance Variables: Unique to each individual object. They are defined inside methods
(typically the constructor) using self..

Reference: Lec 7, [Link] — Slides 485–486

61. Explain static methods and class methods.

Answer:

• Static Methods: Marked with the @staticmethod decorator. They do not receive an implicit
first argument (like self or cls) and behave like regular functions defined inside a class's
namespace.

• Class Methods: Marked with the @classmethod decorator. They receive the class itself (cls)
as their first argument, allowing them to access and modify class-wide state.

Reference: Lec 7, [Link] — Slides 515–516

62. Explain recursive programming and its advantages.


Answer: Recursive programming is an algorithmic technique where a function solves a problem by
calling itself with smaller instances of the same problem.

• Advantages: It can significantly simplify the code for problems that are naturally recursive,
such as traversing tree structures or calculating mathematical sequences like factorials and
Fibonacci numbers.

Reference: Lec 5, [Link] — Slide 360

63. Explain lambda functions and anonymous functions.

Answer: Lambda functions are small, anonymous (unnamed) functions defined in a single line using
the lambda keyword: lambda arguments: expression. They are commonly used as quick, temporary
arguments for higher-order functions like map(), filter(), or sorted().

Reference: Lec 5, [Link] — Slides 380–385

64. Explain Python scientific/statistical libraries.

Answer:

• NumPy: Provides efficient multi-dimensional array operations.

• SciPy: Adds advanced algorithms for scientific integrations, differential equations, and signal
processing.

• Pandas: Simplifies data manipulation and statistical analysis on tabular data.

• Statsmodels: Provides tools for statistical modeling and hypothesis testing.

Reference: General Python Concept (Syllabus Module 3 topic)

65. Explain machine learning workflow using Python.

Answer:

1. Data Acquisition: Loading raw datasets using Pandas.

2. Preprocessing: Cleaning data, handling missing values, and scaling features using Scikit-learn.

3. Model Selection: Choosing an algorithm (like a decision tree or neural network).

4. Training: Fitting the model to your training data.

5. Evaluation: Testing the model's accuracy on unseen data.

6. Deployment: Saving the trained model using serialization to make predictions in real-world
applications.

Reference: General Python Concept (Syllabus Module 3 topic)

66. Explain real-time applications of Python in engineering.

Answer: Python is used in engineering to build real-time monitoring dashboards for SCADA systems,
stream and analyze sensor data from industrial equipment, run computer vision models on assembly
lines for quality control, and automate hardware testing processes.

Reference: Lec 1. Introduction to [Link] — Slide 18 (and general concept)


CO5: Application Development, Optimization and Problem Solving

1. Write a Python program to calculate factorial using recursion.

def factorial(n):

if n == 0 or n == 1:

return 1

return n * factorial(n - 1)

num = int(input("Enter number: "))

print("Factorial is:", factorial(num))

Reference: Lec 5, [Link] — Slide 362

2. Write a Python program to generate Fibonacci series.

def generate_fibonacci(n):

series = []

a, b = 0, 1

for _ in range(n):

[Link](a)

a, b = b, a + b

return series

terms = int(input("Enter terms: "))

print("Fibonacci Series:", generate_fibonacci(terms))

Reference: Lec 5, [Link] — Slide 366

3. Write a Python program to check prime number.

def is_prime(n):

if n <= 1:

return False

for i in range(2, int(n**0.5) + 1):

if n % i == 0:

return False

return True
num = int(input("Enter number: "))

print("Is Prime:", is_prime(num))

Reference: Lec 4, while, [Link] — Slide 299

4. Write a Python program to check palindrome string.

def is_palindrome(s):

clean_s = [Link](" ", "").lower()

return clean_s == clean_s[::-1]

user_str = input("Enter string: ")

print("Is Palindrome:", is_palindrome(user_str))

Reference: Lec 2, Print, Data Types [Link] — Slide 170

5. Write a Python program to sort a list.

# In-place sort using built-in method

numbers = [64, 34, 25, 12, 22, 11, 90]

[Link]()

print("Sorted List:", numbers)

Reference: Lec 1. Introduction to [Link] — Slide 112

6. Write a Python program for matrix addition.

# Standard nested list method

A = [[1, 2], [3, 4]]

B = [[5, 6], [7, 8]]

result = [[0, 0], [0, 0]]

for i in range(len(A)):

for j in range(len(A[0])):

result[i][j] = A[i][j] + B[i][j]

print("Result Matrix:")

for row in result:

print(row)

Reference: Lec 4, while, [Link] — Slide 263


7. Write a Python program for matrix multiplication.

A = [[1, 2], [3, 4]]

B = [[5, 6], [7, 8]]

result = [[0, 0], [0, 0]]

for i in range(len(A)):

for j in range(len(B[0])):

for k in range(len(B)):

result[i][j] += A[i][k] * B[k][j]

print("Multiplied Matrix:")

for row in result:

print(row)

Reference: Lec 4, while, [Link] — Slide 263 (and general algorithm)

8. Write a Python program to find largest element in a list.

def find_largest(lst):

if not lst:

return None

largest = lst[0]

for num in lst:

if num > largest:

largest = num

return largest

nums = [10, 85, 20, 5, 42]

print("Largest is:", find_largest(nums))

Reference: Lec 1. Introduction to [Link] — Slide 111

9. Write a Python program to count vowels in a string.

def count_vowels(s):

vowels = "aeiouAEIOU"

count = 0
for char in s:

if char in vowels:

count += 1

return count

user_str = input("Enter text: ")

print("Vowel count:", count_vowels(user_str))

Reference: Lec 1. Introduction to [Link] — Slide 74

10. Write a Python program to reverse a string.

def reverse_string(s):

return s[::-1]

user_str = input("Enter text: ")

print("Reversed:", reverse_string(user_str))

Reference: Lec 1. Introduction to [Link] — Slide 77

11. Write a Python program to perform file read and write operations.

# Writing

with open("[Link]", "w") as file:

[Link]("PCC-EE 405 Computer Programming\n")

# Reading

with open("[Link]", "r") as file:

content = [Link]()

print("File Content:", content)

Reference: Lec 6, [Link] — Slide 472

12. Write a Python program to append data into a file.

with open("[Link]", "a") as file:

[Link]("Appending new line of engineering data.\n")

Reference: Lec 6, [Link] — Slide 472

13. Write a Python program to copy contents from one file to another.

with open("[Link]", "r") as src, open("[Link]", "w") as dest:


[Link]([Link]())

Reference: Lec 6, [Link] — Slide 446

14. Write a Python program to count number of lines in a file.

with open("[Link]", "r") as file:

lines = [Link]()

print("Total line count:", len(lines))

Reference: Lec 6, [Link] — Slide 472

15. Write a Python program for CSV file handling.

import csv

# Writing

with open("[Link]", "w", newline="") as f:

writer = [Link](f)

[Link](["Parameter", "Value"])

[Link](["Voltage", "230V"])

# Reading

with open("[Link]", "r") as f:

reader = [Link](f)

for row in reader:

print(row)

Reference: Lec 6, [Link] — Slide 472

16. Write a Python program for JSON file handling.

import json

config = {"port": "COM3", "baudrate": 9600}

# Writing

with open("[Link]", "w") as f:

[Link](config, f)

# Reading
with open("[Link]", "r") as f:

data = [Link](f)

print("Loaded Config:", data)

Reference: Lec 6, [Link] — Slide 472

17. Write a Python program to handle divide-by-zero exception.

try:

result = 100 / int(input("Enter divisor: "))

print("Result is:", result)

except ZeroDivisionError:

print("Error: Cannot divide by zero!")

Reference: Lec 5, [Link] — Slide 428

18. Write a Python program using try-except-finally block.

try:

file = open("[Link]", "r")

data = [Link]()

print(data)

except FileNotFoundError:

print("Error: Target file not found!")

finally:

print("Execution complete. Cleaning up system resources.")

Reference: Lec 6, [Link] — Slide 435

19. Write a Python program to demonstrate inheritance.

class Machine:

def __init__(self, name):

[Link] = name

def run(self):

print(f"{[Link]} is running.")

class Generator(Machine): # Generator inherits from Machine

def generate(self):

print(f"{[Link]} is generating power.")


g = Generator("Alternator")

[Link]()

[Link]()

Reference: Lec 7, [Link] — Slide 496

20. Write a Python program to demonstrate polymorphism.

class AC_Motor:

def describe(self): return "Uses Alternating Current"

class DC_Motor:

def describe(self): return "Uses Direct Current"

def test_motor(motor_obj):

print(motor_obj.describe())

test_motor(AC_Motor())

test_motor(DC_Motor())

Reference: Lec 7, [Link] — Slide 505

21. Write a Python program to demonstrate encapsulation.

class SecureDevice:

def __init__(self, key):

self.__secret_key = key # Private variable

def get_key(self): # Public getter interface

return self.__secret_key

dev = SecureDevice("ENC_KEY_123")

# print(dev.__secret_key) # Throws AttributeError

print("Accessed via method:", dev.get_key())

Reference: Lec 7, [Link] — Slide 492

22. Write a Python program using class and object.


class Transformer:

def __init__(self, rating):

[Link] = rating

def display(self):

print(f"Transformer Rating: {[Link]} kVA")

tx = Transformer(500)

[Link]()

Reference: Lec 7, [Link] — Slide 476

23. Write a Python program to demonstrate multithreading.

import threading

import time

def task(name):

print(f"Task {name} starting...")

[Link](2)

print(f"Task {name} completed.")

t1 = [Link](target=task, args=("Sensor A",))

t2 = [Link](target=task, args=("Sensor B",))

[Link]()

[Link]()

[Link]()

[Link]()

print("All threads finished.")

Reference: General Python Concept (Syllabus Module 3 topic)

24. Write a Python program using lambda function.

# Lambda to calculate electrical power P = I^2 * R

power = lambda i, r: (i**2) * r

print("Power Dissipated:", power(5, 10), "Watts")


Reference: Lec 5, [Link] — Slide 382

25. Write a Python program using nested loops.

# Multiplicative matrix table

for i in range(1, 4):

for j in range(1, 4):

print(f"{i * j:2d}", end=" ")

print()

Reference: Lec 4, while, [Link] — Slide 263

26. Write a Python program for list traversal.

voltages = [220, 230, 240, 110]

for v in voltages:

print(f"System Voltage: {v}V")

Reference: Lec 1. Introduction to [Link] — Slide 111

27. Write a Python program for tuple operations.

coordinates = (22.5726, 88.3639) # Kolkata Latitude/Longitude

print("Length:", len(coordinates))

print("Latitude:", coordinates[0])

Reference: Lec 2, Print, Data Types [Link] — Slides 175–180

28. Write a Python program for dictionary operations.

device = {"type": "Motor", "HP": 5}

device["brand"] = "Siemens" # Addition

device["HP"] = 7.5 # Modification

print("Device Parameters:", device)

Reference: Lec 2, Print, Data Types [Link] — Slide 181 (and general dictionary operations)

29. Write a Python program to demonstrate mutable and immutable objects.

# Mutable Demonstration

list_a = [1, 2]

list_b = list_a

list_b.append(3)

print("Mutable (shared reference):", list_a) # Output: [1, 2, 3]


# Immutable Demonstration

str_a = "Hello"

str_b = str_a

str_b += " World"

print("Immutable (original unchanged):", str_a) # Output: "Hello"

Reference: Lec 1. Introduction to [Link] — Slides 91–95

30. Write a Python syntax to append data to a CSV file.

import csv

with open("[Link]", "a", newline="") as file:

writer = [Link](file)

[Link](["Timestamp", "Sensor Reading"])

Reference: Lec 6, [Link] — Slide 458

31. Write a Python program for student record management system.

class StudentSystem:

def __init__(self):

[Link] = {}

def add_student(self, roll, name, marks):

[Link][roll] = {"name": name, "marks": marks}

def display_all(self):

for roll, info in [Link]():

print(f"Roll: {roll} | Name: {info['name']} | Marks: {info['marks']}")

sys = StudentSystem()

sys.add_student(12, "Amit", 88)

sys.add_student(15, "Priya", 92)

sys.display_all()

Reference: Lec 7, [Link] — Slide 476 (built into custom class structural design)

32. Write a Python program for library management system.

class Library:
def __init__(self):

[Link] = []

def add_book(self, title):

[Link](title)

def list_books(self):

print("Available Books:", [Link])

lib = Library()

lib.add_book("Python Basics")

lib.add_book("Electrical Machines")

lib.list_books()

Reference: Lec 7, [Link] — Slide 476 (built into custom class structural design)

33. Write a Python GUI program using Tkinter.

import tkinter as tk

def on_click():

[Link](text="Status: Active")

root = [Link]()

[Link]("Control Panel")

[Link]("250x150")

label = [Link](root, text="Status: Idle")

[Link](pady=10)

btn = [Link](root, text="Activate", command=on_click)

[Link](pady=10)

[Link]()
Reference: General Python Concept (Syllabus Module 3 topic)

34. Write a Python program to create calculator using functions.

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

def subtract(a, b): return a - b

def multiply(a, b): return a * b

def divide(a, b): return a / b if b != 0 else "Error"

print("Product of 4 and 5:", multiply(4, 5))

Reference: Lec 5, [Link] — Slide 305

35. Write a Python program to capture image from webcam using OpenCV.

import cv2

cap = [Link](0)

ret, frame = [Link]()

if ret:

[Link]("captured_frame.png", frame)

[Link]()

Reference: General Python Concept (Syllabus Module 3 topic)

36. Write a Python program to plot graph using Matplotlib.

import [Link] as plt

frequencies = [10, 20, 30, 40, 50]

amplitude = [1.2, 2.5, 4.8, 3.1, 0.5]

[Link](frequencies, amplitude, marker='o', color='g')

[Link]("Frequency Response")

[Link]("Frequency (Hz)")

[Link]("Amplitude")

[Link](True)

[Link]()

Reference: General Python Concept (Syllabus Module 3 topic)

37. Write a Python program using NumPy arrays.

import numpy as np
arr = [Link]([1, 2, 3, 4, 5])

print("Array squared:", arr**2)

Reference: General Python Concept (Syllabus Module 3 topic)

38. Write a Python program for statistical calculations using NumPy.

import numpy as np

dataset = [Link]([12, 15, 18, 22, 25, 30])

print("Mean:", [Link](dataset))

print("Standard Deviation:", [Link](dataset))

print("Median:", [Link](dataset))

Reference: General Python Concept (Syllabus Module 3 topic)

39. Write a Python program using Pandas DataFrame.

import pandas as pd

records = {

"Name": ["Amit", "Sujata", "Rohan"],

"Roll": [10, 11, 12],

"Score": [85, 92, 78]

df = [Link](records)

print(df)

Reference: General Python Concept (Syllabus Module 3 topic)

40. Write a Python program to read sensor data from a file.

# Assuming sensor_data.txt contains one reading per line

readings = []

try:

with open("sensor_data.txt", "r") as file:

for line in file:

[Link](float([Link]()))

print("Logged Sensor Data:", readings)

except FileNotFoundError:

print("No data logged yet.")

Reference: Lec 6, [Link] — Slide 446


41. Write a Python program to display timer operation.

import time

def run_timer(seconds):

print("Timer started...")

while seconds > 0:

print(f"Time left: {seconds}s")

[Link](1)

seconds -= 1

print("Timer finished!")

run_timer(3)

Reference: Lec 4, while, [Link] — Slide 245 (using standard control flow loop)

42. Write a Python program using event handling.

import tkinter as tk

def on_keypress(event):

print(f"Key pressed: {[Link]}")

root = [Link]()

[Link]("<Key>", on_keypress)

[Link]()

Reference: General Python Concept (Syllabus Module 3 topic)

43. Write a Python program using threading and synchronization.

import threading

lock = [Link]()

balance = 1000

def withdraw(amount):

global balance

with lock: # Thread-safe execution context


if balance >= amount:

balance -= amount

print(f"Withdrew {amount}. New Balance: {balance}")

t1 = [Link](target=withdraw, args=(200,))

t2 = [Link](target=withdraw, args=(300,))

[Link]()

[Link]()

Reference: General Python Concept (Syllabus Module 3 topic)

44. Write a Python program for file exception handling.

filename = "critical_parameters.txt"

try:

with open(filename, "r") as f:

data = [Link]()

except FileNotFoundError:

print(f"Error: Required file '{filename}' was not found. Initializing fallback setup.")

Reference: Lec 6, [Link] — Slide 435

45. Write a Python program to search element in a list.

def search_element(lst, target):

for i in range(len(lst)):

if lst[i] == target:

return f"Element found at index {i}"

return "Element not found"

items = [10, 20, 30, 40]

print(search_element(items, 30))

Reference: Lec 1. Introduction to [Link] — Slide 111

46. Write a Python program to remove duplicates from list.

def remove_duplicates(lst):

return list(set(lst))
original = [1, 2, 2, 3, 4, 4, 5]

print("Unique list:", remove_duplicates(original))

Reference: Lec 2, Print, Data Types [Link] — Slide 181 (Set conversion properties)

47. Write a Python program for swapping two variables.

x = 10

y = 20

print(f"Before: x={x}, y={y}")

x, y = y, x

print(f"After: x={x}, y={y}")

Reference: Lec 1. Introduction to [Link] — Slide 34

48. Write a Python program to calculate average of numbers.

def find_average(numbers_list):

return sum(numbers_list) / len(numbers_list) if numbers_list else 0

print("Average:", find_average([10, 20, 30, 40]))

Reference: Lec 5, [Link] — Slide 305

49. Write a Python program to generate multiplication table.

num = int(input("Enter number: "))

for i in range(1, 11):

print(f"{num} x {i} = {num * i}")

Reference: Lec 4, while, [Link] — Slide 255

50. Write a Python program using recursive function.

# Cumulative addition calculation up to N using recursion

def cumulative_sum(n):

if n == 1:

return 1

return n + cumulative_sum(n - 1)

print("Cumulative Sum (5):", cumulative_sum(5))

Reference: Lec 5, [Link] — Slide 360

51. Write a Python program using default arguments.


def print_rating(kva=5):

print(f"Transformer rating is {kva} kVA.")

print_rating() # Falls back to 5 kVA

print_rating(500)

Reference: Lec 5, [Link] — Slide 332

52. Write a Python program using keyword arguments.

def create_motor(hz, phase):

print(f"Motor: {hz}Hz frequency, {phase}-phase supply.")

create_motor(phase=3, hz=50) # Passed explicitly out of order

Reference: Lec 5, [Link] — Slide 328

53. Write a Python program using *args and kwargs.

def configure_system(*args, **kwargs):

print("Positional parameters:", args)

print("Keyword parameters:", kwargs)

configure_system("Relay", "Feeder", threshold=0.85, limit=1.2)

Reference: Lec 5, [Link] — Slides 425–426

54. Write a Python program to explain break and continue statements.

print("Using Continue:")

for i in range(1, 5):

if i == 3:

continue # Skips printing 3

print(i, end=" ")

print("\nUsing Break:")

for i in range(1, 5):

if i == 3:

break # Stops execution completely

print(i, end=" ")


Reference: Lec 4, while, [Link] — Slides 280–285

55. Write a Python program to demonstrate pass statement.

# Pass serves as an abstract placeholder in code layouts

class FutureDevelopmentBlock:

pass

def solve_numerical_equations():

pass

Reference: Lec 4, while, [Link] — Slide 288

56. Write a Python program for binary file handling.

import struct

# Writing binary structured parameters

with open("[Link]", "wb") as f:

[Link]([Link]('f', 230.5)) # Writes float value 230.5 as raw bytes

# Reading binary parameters

with open("[Link]", "rb") as f:

val = [Link]('f', [Link]())[0]

print("Unpacked Binary Value:", val)

Reference: Lec 6, [Link] — Slide 448 (and general struct application)

57. Write a Python program for text file handling.

# Write

with open("[Link]", "w") as f:

[Link]("Class session completed.")

# Read

with open("[Link]", "r") as f:

print([Link]())

Reference: Lec 6, [Link] — Slide 472

58. Write a Python program for package import and module usage.
import math # Standard Python mathematical package

import os # Standard system interaction module

print("Square root calculation:", [Link](16))

print("Current Working Directory:", [Link]())

Reference: Lec 6, [Link] — Slide 430

59. Write a Python program to install and use external package.

# Standard process: Run 'pip install requests' in terminal first.

import requests # External package for HTTP communication

try:

response = [Link]("[[Link]

print("API Response Status Code:", response.status_code)

except Exception:

print("Unable to connect to external interface.")

Reference: Lec 1. Introduction to [Link] — Slide 3 (package usage outline)

60. Write a Python application for engineering data analysis.

# Calculate simple voltage drop along a conductor

conductors = {

"Al": {"resistivity": 2.82e-8},

"Cu": {"resistivity": 1.68e-8}

def voltage_drop(current, length, cross_section, conductor_material):

rho = conductors[conductor_material]["resistivity"]

resistance = rho * (length / cross_section)

v_drop = current * resistance

return v_drop

v_loss = voltage_drop(current=15, length=100, cross_section=2.5e-6, conductor_material="Cu")

print(f"Calculated transmission line voltage drop: {v_loss:.3f} Volts")


Reference: Lec 5, [Link] — Slide 305 (and general algorithm)

61. Write a Python application for machine learning workflow.

from [Link] import load_iris

from sklearn.model_selection import train_test_split

from [Link] import KNeighborsClassifier

from [Link] import accuracy_score

# Load iris dataset

iris = load_iris()

X, y = [Link], [Link]

# Split into training and testing datasets

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

# Instantiate and fit classification model

model = KNeighborsClassifier(n_neighbors=3)

[Link](X_train, y_train)

# Evaluate results

predictions = [Link](X_test)

print(f"Classification Model Test Accuracy: {accuracy_score(y_test, predictions)*100:.2f}%")

Reference: General Python Concept (Syllabus Module 3 topic)

62. Write a Python application for image processing.

import cv2

# Read frame

image = [Link]("captured_frame.png")

if image is not None:

# Transform image array color format to Grayscale

gray_image = [Link](image, cv2.COLOR_BGR2GRAY)


# Apply threshold filtering

_, threshold_img = [Link](gray_image, 127, 255, cv2.THRESH_BINARY)

# Save transformed results to disk

[Link]("grayscale_processed.png", threshold_img)

print("Image processed successfully.")

else:

print("Please generate an image frame before run.")

Reference: General Python Concept (Syllabus Module 3 topic)

63. Write a Python application for real-time monitoring system.

import random

import time

def monitor_load():

threshold_limit = 95.0 # Max safe temperature

print("Real-Time Generator Monitoring Active. Press Ctrl+C to terminate.")

try:

while True:

temp = [Link](80.0, 105.0) # Mock sensor readings

print(f"Current core temperature: {temp:.2f}°C")

if temp > threshold_limit:

print(f"ALERT: Core temperature exceeded safe limits ({temp:.2f}°C)!")

[Link](1.5)

except KeyboardInterrupt:

print("Monitoring system terminated.")

monitor_load()

Reference: Lec 4, while, [Link] — Slide 245 (and general algorithm)

64. Write a Python application for automation task.

# Automate archiving log files by renaming and cleaning up whitespace directories


import os

def archive_reports(folder):

if not [Link](folder):

print("Folder not found.")

return

for filename in [Link](folder):

if [Link](".txt"):

old_path = [Link](folder, filename)

new_path = [Link](folder, f"archived_{filename}")

[Link](old_path, new_path)

print("Text documents have been archived successfully.")

Reference: Lec 6, [Link] — Slide 430 (and general automation tools)

65. Write a Python application using GUI and file handling.

import tkinter as tk

from tkinter import messagebox

def save_notes():

text = txt_box.get("1.0", [Link])

with open("saved_notes.txt", "w") as f:

[Link](text)

[Link]("Success", "Notes saved to saved_notes.txt!")

root = [Link]()

[Link]("Quick Notepad")

[Link]("300x200")

txt_box = [Link](root, height=8, width=35)

txt_box.pack(pady=5)

btn = [Link](root, text="Save Notes", command=save_notes)


[Link](pady=5)

[Link]()

Reference: General Python Concept (Syllabus Module 3 topic)

66. Write a Python application using OpenCV and NumPy.

import cv2

import numpy as np

# Generate a synthetic black canvas image using NumPy

canvas = [Link]((400, 400, 3), dtype="uint8")

# Draw a red calibration target box on the canvas using OpenCV

[Link](canvas, (50, 50), (350, 350), (0, 0, 255), 5)

[Link](canvas, "SYSTEM OK", (120, 200), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)

# Save the generated test image to disk

[Link]("calibration_target.png", canvas)

print("Calibration target generated.")

Reference: General Python Concept (Syllabus Module 3 topic)

67. Write a Python application using Pandas and Matplotlib.

import pandas as pd

import [Link] as plt

# Load parameters and performance metrics from sensor logs

log_data = {

"Hour": [1, 2, 3, 4, 5],

"Load": [120, 150, 185, 160, 200]

df = [Link](log_data)

# Calculate statistics
print(f"Peak Operational Load: {df['Load'].max()} kW")

# Render line plot

[Link](df["Hour"], df["Load"], marker="^", color="b")

[Link]("Grid Load Profile")

[Link]("Hour")

[Link]("Load (kW)")

[Link](True)

[Link]("load_profile.png")

print("Load profile graph exported successfully.")

Reference: General Python Concept (Syllabus Module 3 topic)

68. Predict the output:

x = [1, 2, 3]

y = [Link]()

[Link](4)

print(x)

Answer:

[1, 2, 3]

Explanation: y = [Link]() creates a shallow copy of the list x, creating a new list object in memory.
Appending 4 to y modifies only y, leaving the original list x unchanged.

Reference: Lec 2, Print, Data Types [Link] — Slide 181 (Copy characteristics)

69. Predict the output:

a = [1, 2, 3]

b=a

b[0] = 10

print(a)

Answer:

[10, 2, 3]

Explanation: b = a assigns a reference to the same list object in memory to b. Since both variables
point to the same object, modifying b changes the object, which is reflected when printing a.

Reference: Lec 2, Print, Data Types [Link] — Slides 140–145 (Reference characteristics)

70. Predict the output:


def fun(a, b=5):

return a+b

print(fun(3))

Answer:

Explanation: The parameter b has a default value of 5. Calling fun(3) passes 3 to a, while b uses its
default value of 5, returning 3 + 5 = 8.

Reference: Lec 5, [Link] — Slide 332 (Default Arguments)

71. Predict the output:

for i in range(3):

print(i)

try:

print(10/0)

except:

print("Error")

Answer:

Error

Error

Error

Explanation: The loop runs 3 times (for i = 0, 1, 2). In each iteration, i is printed, then a division by
zero occurs inside the try block, which raises a ZeroDivisionError. This error is caught by the except
block, printing "Error".

Reference: Lec 4, while, [Link] — Slide 270 (Loop), Lec 5 — Slide 428 (Try-except block)

72. Predict the output: (Try block alignment)

try:

print(10/0)

except:

print("Error")

Answer:
Error

Explanation: The program attempts to divide 10 by 0, which raises a ZeroDivisionError at runtime.


The except block catches this exception and prints "Error".

Reference: Lec 5, [Link] — Slide 428

73. Identify the error:

if x = 5

print (x)

Answer:

1. Missing block separator: A colon (:) is missing at the end of the if statement.

2. Assignment in comparison: The assignment operator = is used instead of the equality


comparison operator ==.

Correct syntax:

if x == 5:

print(x)

Reference: Lec 3, Array, If_else.pdf — Slide 190, 218

74. Identify the error:

print('Hello)

Answer: SyntaxError: unterminated string literal. The single-quoted string is never closed with a
matching single quote.

Correct syntax:

print('Hello')

Reference: Lec 1. Introduction to [Link] — Slide 71

75. Identify the error:

for i in range(5)

print(i)

Answer: SyntaxError: expected ':'. The for loop declaration is missing the closing block separator
colon (:).

Correct syntax:

for i in range(5):

print(i)

Reference: Lec 4, while, [Link] — Slide 255

76. Identify the error:


x = [1, 2, 3]

print(x[5]) # PDF template layout shows: print(x[5)

Answer:

1. Syntactic SyntaxError: In the PDF layout print(x[5), the closing bracket and closing
parenthesis are missing.

2. Runtime IndexError: If compiled as print(x[5]), it raises an IndexError: list index out of range
because the list has only 3 elements (indices 0, 1, and 2), and index 5 does not exist.

Reference: Lec 1. Introduction to [Link] — Slide 102

77. Identify the error:

10/0

Answer: ZeroDivisionError: division by zero. This is a Runtime Error (Exception) that occurs because
dividing any number by zero is mathematically undefined.

Reference: Lec 2, Print, Data Types [Link] — Slide 154

You might also like