< All Topics
Print

BEU Python Programming Model Paper 2025 – Complete Answers Guide

The BEU Python Model Paper 2025 is essential reading for all Bihar Engineering University students preparing for their Python Programming exam. This comprehensive guide provides complete solutions to the latest BEU Python model paper, helping you understand key concepts and exam patterns. Whether you’re facing Section A multiple-choice questions or Section B detailed problems, our BEU Python model paper solutions cover everything you need to score high marks.

BEU Python Programming Model Paper 2025 – Complete Solutions

SECTION A SOLUTIONS

(Attempt any SEVEN questions. Each question carries 2 marks)

Q1. What will be the output of the following code?

python

x = 15
y = 4
print(x // y, x % y)

Solution:

text

3 3

Explanation:

  • // is floor division: 15 // 4 = 3 (quotient)
  • % is modulus: 15 % 4 = 3 (remainder)
  • Together they give quotient and remainder of division

Q2. Which is NOT a valid variable name?

A) _student_name
B) 2nd_year
C) totalMarks
D) subject_code

Solution: B) 2nd_year

Explanation:

  • Variable names cannot start with digits
  • Must start with letter or underscore
  • Valid: _student_nametotalMarkssubject_code
  • Invalid: 2nd_year (starts with number)

Q3. What is the output of this string operation?

python

text = "Python Programming"
print(text[7:18:2])

Solution:

text

Pormi

Explanation:

  • text[7:18] extracts “Programming”
  • Step 2 takes every second character
  • Positions: P(7), o(9), r(11), m(13), i(15)
  • Result: “Pormi”

Q4. Which method adds element at specific position?

A) append()
B) insert()
C) extend()
D) add()

Solution: B) insert()

Explanation:

  • list.insert(index, element) adds at specific position
  • append() adds at end
  • extend() adds multiple elements
  • No add() method for lists

Q5. What will be the data type of result?

python

result = 8 + 4.5 + 3j

Solution: complex

Explanation:

  • Type promotion: int → float → complex
  • 8 (int) + 4.5 (float) + 3j (complex) = complex
  • Result: (12.5+3j)

Q6. What does this dictionary operation return?

python

student = {"name": "John", "age": 20}
value = student.get("grade", "A")

Solution: A

Explanation:

  • dict.get(key, default) returns default if key not found
  • “grade” key doesn’t exist
  • Returns default value “A”

Q7. Which file mode is for reading and writing?

A) ‘r’
B) ‘w’
C) ‘a+’
D) ‘rb’

Solution: C) ‘a+’

Explanation:

  • 'a+' – append and read mode
  • 'r' – read only
  • 'w' – write (overwrites)
  • 'rb' – read binary

Q8. What is the output of this set operation?

python

set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
print(set1 - set2)

Solution: {1, 2}

Explanation:

  • set1 - set2 gives elements in set1 but not in set2
  • Set difference operation
  • Result: {1, 2}

Q9. Which module is for CSV files?

A) pickle
B) csv
C) os
D) file

Solution: B) csv

Explanation:

  • csv module handles CSV files specifically
  • pickle – object serialization
  • os – operating system interface

Q10. What will be the output?

python

def test(x=[]):
    x.append(1)
    return x

print(test())
print(test())

Solution:

text

[1]
[1, 1]

Explanation:

  • Default arguments evaluated once at function definition
  • Same list object used in every call
  • First call: [1], Second call: same list becomes [1, 1]

SECTION B SOLUTIONS

(Attempt any FOUR questions. Each question carries 14 marks)

Q2. a) Explain different types of conditional statements in Python with proper syntax and practical examples.

Conditional statements in Python are used to make decisions in a program.
They allow the program to execute a certain block of code only when a specific condition is true.


Types of Conditional Statements:

1. if statement

Used to test a single condition.
If the condition is true, the block of code is executed.

Syntax:

if condition:
    statement(s)

Example:

x = 10
if x > 5:
    print("x is greater than 5")

Output:
x is greater than 5


2. if–else statement

Used when there are two possible outcomes — one for true condition and another for false.

Syntax:

if condition:
    statement(s)
else:
    statement(s)

Example:

age = 18
if age >= 18:
    print("Eligible to vote")
else:
    print("Not eligible to vote")

Output:
Eligible to vote


3. if–elif–else statement

Used when there are multiple conditions to check one by one.

Syntax:

if condition1:
    statement(s)
elif condition2:
    statement(s)
else:
    statement(s)

Example:

marks = 72
if marks >= 90:
    print("Grade A")
elif marks >= 75:
    print("Grade B")
elif marks >= 50:
    print("Grade C")
else:
    print("Fail")

Output:
Grade B


4. Nested if statement

An if statement placed inside another if statement is called nested if.

Syntax:

if condition1:
    if condition2:
        statement(s)

Example:

num = 25
if num > 0:
    if num % 5 == 0:
        print("Positive and divisible by 5")

Output:
Positive and divisible by 5


Conclusion:

Hence, conditional statements like if, if–else, if–elif–else, and nested if help in decision-making and control the flow of a Python program according to given conditions.

Q2. b) Compare while and for loops in Python. Discuss loop control statements with examples. When would you prefer one loop type over the other?

In Python, loops are used to execute a block of code repeatedly until a certain condition is met.
The two main looping structures are while loop and for loop.


1. Comparison between while and for loops

Basiswhile loopfor loop
Syntaxwhile condition:for variable in sequence:
UseWhen the number of iterations is not known in advanceWhen the number of iterations is known or definite
Condition CheckingCondition is checked before every iterationIterates over a sequence (like list, range, string)
InitializationVariable must be initialized before loopVariable is automatically assigned by loop
Examplewhile x <= 5:for i in range(1,6):

2. Example of while loop

i = 1
while i <= 5:
    print("Hello", i)
    i += 1

Output:

Hello 1  
Hello 2  
Hello 3  
Hello 4  
Hello 5

3. Example of for loop

for i in range(1, 6):
    print("Hello", i)

Output:

Hello 1  
Hello 2  
Hello 3  
Hello 4  
Hello 5

4. Loop Control Statements

Loop control statements are used to change the normal sequence of loop execution.

Control StatementDescriptionExample
breakTerminates the loop immediately
for i in range(1,6):
    if i == 3:
        break
    print(i)

Output: 1 2 |

| continue | Skips the current iteration and continues with the next one |

for i in range(1,6):
    if i == 3:
        continue
    print(i)

Output: 1 2 4 5 |

| pass | Does nothing; used as a placeholder |

for i in range(1,6):
    if i == 3:
        pass
    print(i)

Output: 1 2 3 4 5 |


5. When to prefer which loop

  • Use while loop → when you don’t know how many times you need to repeat (e.g., reading user input until correct).
  • Use for loop → when you know the range or number of repetitions in advance (e.g., traversing a list or range).

Conclusion:

Both while and for loops are essential for repetitive tasks.
The choice depends on whether the number of iterations is known (for) or unknown (while).
Loop control statements like break, continue, and pass provide better control over loop execution.

Q3. a) Explain function definition, different types of parameters, and return values with suitable examples.  

A function in Python is a block of statements that performs a specific task.
It helps in code reusability, modularity, and better program structure.


1. Function Definition

A function is defined using the def keyword followed by the function name and parentheses ().

Syntax:

def function_name(parameters):
    # block of code
    return value

Example:

def greet():
    print("Hello, Welcome to Python!")
greet()

Output:
Hello, Welcome to Python!


2. Types of Function Parameters (or Arguments)

Functions can take different types of parameters to pass data.

(i) Positional Arguments

Values are passed in the same order as parameters.

def add(a, b):
    print(a + b)
add(5, 10)

Output: 15


(ii) Keyword Arguments

Values are passed using parameter names.

def student(name, age):
    print(name, age)
student(age=20, name="Ravi")

Output: Ravi 20


(iii) Default Arguments

A default value is assigned to a parameter if no value is passed.

def greet(name="Guest"):
    print("Hello", name)
greet()

Output: Hello Guest


(iv) Variable-Length Arguments

Used when the number of arguments is unknown.

Using *args (non-keyword arguments):

def total(*numbers):
    print(sum(numbers))
total(10, 20, 30)

Output: 60

Using **kwargs (keyword arguments):

def info(**data):
    print(data)
info(name="Ravi", age=20)

Output: {'name': 'Ravi', 'age': 20}


3. Return Values

A function can return a value to the calling part using the return statement.

Syntax:

def function_name():
    return value

Example:

def square(x):
    return x * x

result = square(5)
print("Square =", result)

Output: Square = 25


4. Conclusion

Hence, functions make programs modular, easy to read, and reusable.
Python supports different types of parameters — positional, keyword, default, and variable-length.
Functions can also return one or multiple values using the return statement.

Q3. b) Explain the concept of variable scope in Python with examples of local, global, and nonlocal variables. What is the LEGB rule?  

The scope of a variable in Python defines the part of the program where the variable can be accessed or used.
In other words, the scope decides the lifetime and visibility of a variable.


1. Types of Variable Scopes in Python

(i) Local Variable

A variable created inside a function is called a local variable.
It can be used only within that function.

Example:

def show():
    x = 10      # local variable
    print("Inside function:", x)

show()
# print(x)  # Error: x is not defined outside function

Output:

Inside function: 10

(ii) Global Variable

A variable declared outside all functions is a global variable.
It can be accessed anywhere in the program, inside or outside functions.

Example:

x = 50   # global variable

def show():
    print("Inside function:", x)

show()
print("Outside function:", x)

Output:

Inside function: 50  
Outside function: 50

(iii) nonlocal Variable

The nonlocal keyword is used to refer to a variable defined in the enclosing (outer) function, but not global.
It is mainly used in nested functions.

Example:

def outer():
    x = "outer value"
    def inner():
        nonlocal x
        x = "modified inside inner"
    inner()
    print(x)

outer()

Output:

modified inside inner

2. The LEGB Rule

The LEGB rule defines the order in which Python searches for a variable name.

LevelMeaningDescription
LLocalVariables defined inside the current function.
EEnclosingVariables in the local scope of any enclosing function.
GGlobalVariables defined at the top level of a module/script.
BBuilt-inNames pre-defined in Python (like print(), len(), etc.)

Example:

x = "global"

def outer():
    x = "enclosing"
    def inner():
        x = "local"
        print(x)  # Local
    inner()

outer()

Output:

local

3. Conclusion:

  • Local variables → exist only inside functions.
  • Global variables → can be accessed throughout the program.
  • Nonlocal variables → used in nested functions to modify outer variables.
  • LEGB rule defines the variable search order: Local → Enclosing → Global → Built-in.

Q4. a) Explain string creation, indexing, slicing, and basic string operations with examples.  

A string in Python is a sequence of characters enclosed within single quotes (‘ ‘), double quotes (” “), or triple quotes (”’ ”’ / “”” “””).
Strings are immutable, meaning their values cannot be changed after creation.


1. String Creation

Strings can be created using single, double, or triple quotes.

Example:

str1 = 'Hello'
str2 = "Python"
str3 = '''Welcome to Python Programming'''
print(str1)
print(str2)
print(str3)

Output:

Hello
Python
Welcome to Python Programming

2. String Indexing

Indexing means accessing individual characters in a string.
Each character has an index position — starting from 0 for the first character.

Example:

s = "Python"
print(s[0])   # P
print(s[3])   # h
print(s[-1])  # n  (negative index counts from end)

Output:

P
h
n

3. String Slicing

Slicing is used to extract a part (substring) from a string using the syntax:

string[start : end : step]
  • start → beginning index (inclusive)
  • end → ending index (exclusive)
  • step → skip value (optional)

Example:

s = "Programming"
print(s[0:6])     # Progra
print(s[3:8])     # gram
print(s[:])       # Full string
print(s[::-1])    # Reverse string

Output:

Progra
gram
Programming
gnimmargorP

4. Basic String Operations

(i) Concatenation (+)

Used to join two strings.

a = "Hello"
b = "World"
print(a + " " + b)

Output: Hello World


(ii) Repetition (*)

Used to repeat a string multiple times.

print("Hi " * 3)

Output: Hi Hi Hi


(iii) Length (len())

Returns the total number of characters.

s = "Python"
print(len(s))

Output: 6


(iv) Membership (in / not in)

Used to check if a substring exists within another string.

print("Py" in "Python")
print("Java" not in "Python")

Output:

True
True

(v) String Methods (Examples)

s = "hello world"
print(s.upper())   # HELLO WORLD
print(s.title())   # Hello World
print(s.replace("world", "Python"))  # hello Python

5. Conclusion:

Strings in Python support operations like indexing, slicing, concatenation, repetition, and various built-in methods.
They are immutable and widely used for handling textual data.

Q4. b) Explain important string methods and different string formatting techniques with examples.  

Strings in Python have many built-in methods that help in performing operations like changing case, searching, replacing, splitting, joining, etc.
String formatting is used to display variables and values in a formatted manner.


1. Important String Methods

Below are some commonly used string methods with examples:

MethodDescriptionExample & Output
1. upper()Converts all characters to uppercase"python".upper()PYTHON
2. lower()Converts all characters to lowercase"HELLO".lower()hello
3. title()Converts first letter of each word to uppercase"welcome to python".title()Welcome To Python
4. capitalize()Converts first letter of the string to uppercase"python programming".capitalize()Python programming
5. strip()Removes spaces from beginning and end" hello ".strip()hello
6. replace(old, new)Replaces a substring with another"I like C".replace("C", "Python")I like Python
7. split()Splits string into a list of words"a,b,c".split(",")['a', 'b', 'c']
8. join()Joins list elements into a string"-".join(['A','B','C'])A-B-C
9. find()Returns index of first occurrence of substring"Python".find("t")2
10. count()Returns number of occurrences of a substring"banana".count("a")3

2. String Formatting Techniques

String formatting allows insertion of variables or values into a string in a proper format.

(i) Using % Operator (Old Style)

name = "Ravi"
age = 20
print("My name is %s and I am %d years old." % (name, age))

Output:
My name is Ravi and I am 20 years old.


(ii) Using str.format() Method

name = "Ravi"
marks = 85
print("Student Name: {}, Marks: {}".format(name, marks))
print("Student Name: {1}, Marks: {0}".format(marks, name))

Output:

Student Name: Ravi, Marks: 85
Student Name: Ravi, Marks: 85

(iii) Using f-Strings (Modern & Preferred)

Introduced in Python 3.6, f-strings allow direct embedding of expressions inside {}.

name = "Ravi"
age = 20
print(f"My name is {name} and next year I will be {age + 1}.")

Output:
My name is Ravi and next year I will be 21.


(iv) Using format() with Named Placeholders

print("Hello, {fname} {lname}".format(fname="C. P.", lname="Chitransh"))

Output:
Hello, C. P. Chitransh


3. Conclusion:

String methods help in modifying and processing text, while formatting techniques like % operator, format(), and f-strings make it easy to display variables clearly and professionally.

Q5. a) Explain list mutability with examples of various list operations and methods. How does list slicing work? Demonstrate with examples.  

A list in Python is an ordered, mutable (changeable) collection of items.
Lists can store elements of different data types like integers, strings, or even other lists.


1. List Mutability

Mutability means the contents of a list can be changed after creation — we can add, modify, or delete elements.

Example:

numbers = [10, 20, 30, 40]
numbers[2] = 99      # Modifying element
print(numbers)

Output:
[10, 20, 99, 40]

👉 Hence, lists are mutable, unlike strings or tuples which are immutable.


2. Basic List Operations

OperationExampleOutput
Indexinga = [1, 2, 3]; print(a[0])1
Concatenation[1, 2] + [3, 4][1, 2, 3, 4]
Repetition[1, 2] * 2[1, 2, 1, 2]
Membership3 in [1, 2, 3]True
Lengthlen([1,2,3,4])4

3. Common List Methods

MethodDescriptionExample & Output
append(x)Adds an element at the enda = [1,2]; a.append(3)[1,2,3]
insert(i, x)Inserts element at index ia.insert(1, 10)[1,10,2,3]
extend(list2)Adds all elements of another list[1,2].extend([3,4])[1,2,3,4]
remove(x)Removes first occurrence of xa.remove(2)
pop(i)Removes and returns element at index ia.pop(1)
sort()Sorts the list in ascending order[3,1,2].sort()[1,2,3]
reverse()Reverses the list[1,2,3].reverse()[3,2,1]
index(x)Returns index of first occurrence[10,20,30].index(20)1
count(x)Returns number of times x appears[1,2,2,3].count(2)2

4. List Slicing

Slicing means extracting a part of a list using the syntax:

list[start : end : step]
  • start → index to begin (inclusive)
  • end → index to stop (exclusive)
  • step → number of elements to skip (optional)

Example:

nums = [10, 20, 30, 40, 50, 60]
print(nums[1:4])     # Elements from index 1 to 3
print(nums[:3])      # First 3 elements
print(nums[::2])     # Every 2nd element
print(nums[::-1])    # Reversed list

Output:

[20, 30, 40]
[10, 20, 30]
[10, 30, 50]
[60, 50, 40, 30, 20, 10]

5. Conclusion:

  • Lists are mutable, meaning they can be modified after creation.
  • Support various operations and methods like append(), remove(), sort(), etc.
  • Slicing allows easy extraction and manipulation of sublists from the main list.

A list in Python is an ordered, mutable (changeable) collection of items.
Lists can store elements of different data types like integers, strings, or even other lists.


1. List Mutability

Mutability means the contents of a list can be changed after creation — we can add, modify, or delete elements.

Example:

numbers = [10, 20, 30, 40]
numbers[2] = 99      # Modifying element
print(numbers)

Output:
[10, 20, 99, 40]

👉 Hence, lists are mutable, unlike strings or tuples which are immutable.


2. Basic List Operations

OperationExampleOutput
Indexinga = [1, 2, 3]; print(a[0])1
Concatenation[1, 2] + [3, 4][1, 2, 3, 4]
Repetition[1, 2] * 2[1, 2, 1, 2]
Membership3 in [1, 2, 3]True
Lengthlen([1,2,3,4])4

3. Common List Methods

MethodDescriptionExample & Output
append(x)Adds an element at the enda = [1,2]; a.append(3)[1,2,3]
insert(i, x)Inserts element at index ia.insert(1, 10)[1,10,2,3]
extend(list2)Adds all elements of another list[1,2].extend([3,4])[1,2,3,4]
remove(x)Removes first occurrence of xa.remove(2)
pop(i)Removes and returns element at index ia.pop(1)
sort()Sorts the list in ascending order[3,1,2].sort()[1,2,3]
reverse()Reverses the list[1,2,3].reverse()[3,2,1]
index(x)Returns index of first occurrence[10,20,30].index(20)1
count(x)Returns number of times x appears[1,2,2,3].count(2)2

4. List Slicing

Slicing means extracting a part of a list using the syntax:

list[start : end : step]
  • start → index to begin (inclusive)
  • end → index to stop (exclusive)
  • step → number of elements to skip (optional)

Example:

nums = [10, 20, 30, 40, 50, 60]
print(nums[1:4])     # Elements from index 1 to 3
print(nums[:3])      # First 3 elements
print(nums[::2])     # Every 2nd element
print(nums[::-1])    # Reversed list

Output:

[20, 30, 40]
[10, 20, 30]
[10, 30, 50]
[60, 50, 40, 30, 20, 10]

5. Conclusion:

Slicing allows easy extraction and manipulation of sublists from the main list.

Lists are mutable, meaning they can be modified after creation.

Support various operations and methods like append(), remove(), sort(), etc.

Q6. a) Explain dictionary creation, accessing and modifying key-value pairs, and important dictionary methods with examples.  

1. Dictionary in Python

A dictionary is an unordered, mutable (changeable) collection of items where data is stored in key-value pairs.
Each key must be unique and immutable (like string, number, or tuple), and each key maps to a value.

Syntax:

dictionary_name = {key1: value1, key2: value2, ...}

Example:

student = {'name': 'Amit', 'age': 20, 'course': 'Python'}
print(student)

Output:

{'name': 'Amit', 'age': 20, 'course': 'Python'}

2. Accessing Dictionary Elements

You can access values using keys.

Example:

print(student['name'])      # Using key
print(student.get('age'))   # Using get() method

Output:

Amit
20

3. Modifying and Adding Elements

Dictionaries are mutable, so you can add, change, or delete items.

Example:

student['age'] = 21          # Modify value
student['city'] = 'Ranchi'   # Add new key-value pair
print(student)

Output:

{'name': 'Amit', 'age': 21, 'course': 'Python', 'city': 'Ranchi'}

4. Deleting Elements

You can remove elements using del, pop(), or clear().

Example:

del student['city']        # Delete by key
student.pop('course')      # Remove and return value
print(student)

Output:

{'name': 'Amit', 'age': 21}

5. Important Dictionary Methods

MethodDescriptionExample & Output
keys()Returns all keysstudent.keys()dict_keys(['name', 'age'])
values()Returns all valuesstudent.values()dict_values(['Amit', 21])
items()Returns key-value pairsstudent.items()dict_items([('name','Amit'),('age',21)])
update()Updates dictionarystudent.update({'age':22})
pop(key)Removes key and returns valuestudent.pop('age')
clear()Removes all itemsstudent.clear()

6. Iterating through Dictionary

Example:

for key, value in student.items():
    print(key, ":", value)

Output:

name : Amit
age : 21

7. Conclusion

  • Dictionaries store data as key–value pairs.
  • They are mutable and unordered.
  • Useful methods: keys(), values(), items(), update(), and pop().
  • Efficient for fast lookup and data mapping.

Q6. b) Explain set operations in Python. Discuss set methods and their practical applications. What are frozen sets and when are they used?  

1. Set in Python

A Set is an unordered, mutable, and unindexed collection of unique elements.
Sets are mainly used to perform mathematical operations like union, intersection, difference, etc.

Syntax:

set_name = {element1, element2, element3, ...}

Example:

A = {1, 2, 3, 4}
B = {3, 4, 5, 6}

2. Set Operations

OperationOperator / MethodExampleOutput
Union`ABorA.union(B)`{1, 2, 3, 4, 5, 6}
IntersectionA & B or A.intersection(B){3, 4}Common elements
DifferenceA - B or A.difference(B){1, 2}In A not in B
Symmetric DifferenceA ^ B or A.symmetric_difference(B){1, 2, 5, 6}Elements not common

Example Code:

A = {1, 2, 3, 4}
B = {3, 4, 5, 6}

print("Union:", A | B)
print("Intersection:", A & B)
print("Difference:", A - B)
print("Symmetric Difference:", A ^ B)

Output:

Union: {1, 2, 3, 4, 5, 6}
Intersection: {3, 4}
Difference: {1, 2}
Symmetric Difference: {1, 2, 5, 6}

3. Common Set Methods

MethodDescriptionExample & Output
add(x)Adds an elementA.add(7){1,2,3,4,7}
update(iterable)Adds multiple elementsA.update([8,9]){1,2,3,4,8,9}
remove(x)Removes element, error if not foundA.remove(3)
discard(x)Removes element, no error if missingA.discard(10)
pop()Removes and returns random elementA.pop()
clear()Removes all elementsA.clear()

4. Practical Applications of Sets

  • Removing duplicate elements from a list
  • Performing mathematical set operations (Union, Intersection)
  • Checking membership efficiently
  • Useful in data comparison tasks (e.g., comparing student groups, keywords, etc.)

Example:

students = ["Amit", "Rahul", "Amit", "Neha"]
unique_students = set(students)
print(unique_students)

Output:

{'Amit', 'Rahul', 'Neha'}

5. Frozen Sets

A frozenset is an immutable version of a set — its elements cannot be changed after creation.
Used when we need a constant set that can be used as a dictionary key or set element.

Example:

A = frozenset([1, 2, 3, 4])
print(A)
# A.add(5) → ❌ Error (not allowed)

Output:

frozenset({1, 2, 3, 4})

6. Conclusion

  • Sets are unordered collections of unique items.
  • Support powerful set operations and methods for data manipulation.
  • Frozensets are immutable sets, useful in secure and fixed data contexts.

Q7. a) Explain different file operations in Python, and the use of ‘with’ statement.

1. File in Python

A file is a collection of data stored on disk.
Python provides built-in functions to create, read, write, and modify files.
Files can be text files (.txt) or binary files (.bin, .jpg, .pdf).

Opening a file syntax:

file_object = open("filename", "mode")

2. File Modes in Python

ModePurpose
'r'Read (default). Opens file for reading only.
'w'Write. Creates a new file or overwrites existing file.
'a'Append. Adds content at the end of file.
'r+'Read & Write. File pointer at beginning.
'b'Binary mode (can be combined with other modes, e.g., 'rb')

3. Common File Operations

(i) Creating/Writing a File

f = open("example.txt", "w")
f.write("Hello Python!\n")
f.write("File operations are easy.")
f.close()

(ii) Reading a File

f = open("example.txt", "r")
content = f.read()         # Reads whole file
print(content)
f.close()

(iii) Reading Line by Line

f = open("example.txt", "r")
for line in f:
    print(line)
f.close()

(iv) Appending to a File

f = open("example.txt", "a")
f.write("\nNew line added.")
f.close()

(v) Closing a File

Always use f.close() to release resources.


4. The with Statement

The with statement automatically closes the file after the block is executed, even if exceptions occur.
This is the preferred way to work with files.

Example:

with open("example.txt", "r") as f:
    content = f.read()
    print(content)
# File is automatically closed here

Advantages:

  • No need to explicitly call close()
  • Safer and cleaner code
  • Handles exceptions automatically

5. Conclusion

Using with statement ensures files are safely and efficiently handled

Python supports creating, reading, writing, appending, and closing files.

File modes define how the file is accessed.

Q7. b) Explain working with CSV files and binary files using the pickle module. Discuss important file methods and error handling in file operations.  

1. Working with CSV Files

CSV (Comma Separated Values) files are text files used to store tabular data.
Python provides the csv module to read and write CSV files easily.

Reading CSV

import csv

with open("data.csv", "r") as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

Writing CSV

import csv

data = [["Name", "Age"], ["Amit", 20], ["Neha", 22]]

with open("data.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerows(data)

Key Points:

  • csv.reader() → reads CSV file
  • csv.writer() → writes data to CSV
  • newline="" → avoids blank lines in Windows

2. Working with Binary Files using Pickle

The pickle module is used to serialize Python objects (convert to binary) and save them to a file.
Later, these objects can be deserialized (read back).

Writing Binary File

import pickle

data = {"name": "Amit", "age": 20}

with open("data.pkl", "wb") as file:   # wb → write binary
    pickle.dump(data, file)

Reading Binary File

import pickle

with open("data.pkl", "rb") as file:   # rb → read binary
    new_data = pickle.load(file)
    print(new_data)

Output:

{'name': 'Amit', 'age': 20}

Key Points:

  • wb → write binary
  • rb → read binary
  • pickle.dump() → save object
  • pickle.load() → load object

3. Important File Methods

MethodDescription
read(size)Reads specified number of characters/bytes
readline()Reads one line at a time
readlines()Reads all lines into a list
write()Writes a string to a file
writelines()Writes a list of strings to a file
close()Closes the file

4. Error Handling in File Operations

Errors can occur if a file does not exist or cannot be accessed.
Python uses try-except to handle file-related errors.

Example:

try:
    with open("nonexistent.txt", "r") as f:
        content = f.read()
except FileNotFoundError:
    print("File not found!")
except IOError:
    print("Error reading/writing file")

Output:

File not found!

Key Points:

  • Always handle FileNotFoundError or IOError
  • Using with + try-except ensures safe file handling

5. Conclusion

  • CSV files are used for tabular data using the csv module.
  • Binary files store serialized Python objects using pickle.
  • File methods like read(), write(), readlines() help in data manipulation.
  • Error handling ensures programs don’t crash on file-related issues.

Q8. a) Explain the usage of important built-in modules in Python with examples.  

1. Built-in Modules in Python

Python provides predefined modules that contain functions, classes, and variables to perform common tasks.
These modules save time as you don’t need to write code from scratch.

Syntax to use a module:

import module_name

Or, to import specific functions:

from module_name import function_name

2. Important Built-in Modules and Their Usage

(i) math module

Provides mathematical functions like sqrt(), ceil(), floor(), factorial(), etc.

Example:

import math

print(math.sqrt(16))    # 4.0
print(math.factorial(5)) # 120
print(math.ceil(4.3))    # 5
print(math.floor(4.7))   # 4

(ii) random module

Used to generate random numbers or select random items.

Example:

import random

print(random.randint(1, 10))   # Random integer between 1 and 10
print(random.choice(['A', 'B', 'C'])) # Random element from list

(iii) datetime module

Used to work with dates and times.

Example:

import datetime

today = datetime.date.today()
print(today)   # Current date

now = datetime.datetime.now()
print(now)     # Current date & time

(iv) os module

Provides functions to interact with the operating system, like file paths, directories, etc.

Example:

import os

print(os.getcwd())   # Current working directory
os.mkdir("NewFolder")  # Create a new folder

(v) sys module

Provides functions to interact with Python runtime environment.

Example:

import sys

print(sys.version)  # Python version
print(sys.path)     # List of module search paths

(vi) json module

Used to read and write JSON data (common in web APIs).

Example:

import json

data = {"name": "Amit", "age": 20}
json_str = json.dumps(data)      # Convert dict to JSON string
print(json_str)

dict_data = json.loads(json_str) # Convert JSON string back to dict
print(dict_data)

3. Conclusion

  • Python built-in modules like math, random, datetime, os, sys, and json provide predefined functions and classes for common tasks.
  • They save development time, improve code readability, and make programs efficient and reliable.

Q8. b) Explain how to create and use custom modules and packages in Python. Discuss the __name__ == “__main__” construct and its importance.  

1. Custom Modules in Python

A module is a Python file containing functions, classes, or variables that can be reused in other programs.
You can create your own module by writing Python code in a .py file.

Example:

  • Create a file mymodule.py:
# mymodule.py
def greet(name):
    return f"Hello, {name}!"
  • Use it in another program:
# main.py
import mymodule

print(mymodule.greet("Amit"))

Output:

Hello, Amit!

2. Custom Packages in Python

A package is a collection of modules organized in directories.
A folder with an __init__.py file is treated as a Python package.

Structure:

mypackage/
    __init__.py
    module1.py
    module2.py

Usage:

from mypackage import module1
module1.function_name()

3. The __name__ == "__main__" Construct

When a Python file is run directly, the special variable __name__ is set to "__main__".
If the file is imported as a module, __name__ is set to the module’s name.

Example:

# mymodule.py
def greet(name):
    print(f"Hello, {name}!")

if __name__ == "__main__":
    greet("Amit")   # This runs only when file is executed directly
  • Running python mymodule.py → prints Hello, Amit!
  • Importing mymodule in another program → does not execute the code under if __name__ == "__main__"

Importance:

  • Allows a file to act both as a module and a standalone program.
  • Avoids unintended execution when importing modules.

4. Conclusion

  • Custom modules help reusability and modular programming.
  • Packages organize multiple modules into a structured directory.
  • __name__ == "__main__" ensures code runs only when intended, preventing unwanted execution during imports.

Q9. a) Explain Python’s dynamic typing and strong typing characteristics with suitable examples. How does this differ from statically typed languages?  

1. Dynamic Typing in Python

Python is a dynamically typed language, meaning you do not need to declare variable types explicitly.
The type of a variable is determined automatically at runtime and can change during execution.

Example:

x = 10        # x is an integer
print(type(x)) # <class 'int'>

x = "Python"  # x now becomes a string
print(type(x)) # <class 'str'>

Key Points:

  • Variable type can change dynamically
  • Easier and faster to write code
  • Less strict, but may require careful handling of data types

2. Strong Typing in Python

Python is strongly typed, meaning operations between incompatible types are not allowed.
You cannot mix data types directly without explicit conversion.

Example:

x = 10
y = "5"

# print(x + y)  # ❌ Error: TypeError
print(x + int(y))  # ✅ Correct, after converting y to int

Key Points:

  • Python prevents accidental type errors
  • Requires explicit type conversion when necessary

3. Difference from Statically Typed Languages

FeaturePythonStatically Typed Language (e.g., C, Java)
Type DeclarationNot required; dynamic typingRequired before use
Type CheckingDone at runtimeDone at compile-time
FlexibilityVariables can change typeVariables cannot change type once declared
Error DetectionType errors occur at runtimeType errors caught during compilation

Example in Java (statically typed):

int x = 10;
x = "Python";  // ❌ Error: incompatible types

4. Conclusion

  • Dynamic typing: Variable types are determined at runtime and can change.
  • Strong typing: Operations between incompatible types are not allowed without conversion.
  • In contrast, statically typed languages require explicit type declaration and detect type errors at compile-time.

Q9. b) Describe the different numeric data types available in Python with examples. Explain type conversion between these data types with code examples.

1. Numeric Data Types in Python

Python provides several numeric data types to store numbers:

Data TypeDescriptionExample
intInteger numbers (whole numbers)x = 10
floatFloating-point numbers (decimal numbers)y = 3.14
complexComplex numbers with real and imaginary partsz = 2 + 3j

Example Code:

x = 10        # int
y = 3.14      # float
z = 2 + 3j    # complex

print(type(x))  # <class 'int'>
print(type(y))  # <class 'float'>
print(type(z))  # <class 'complex'>

2. Type Conversion (Type Casting)

Python allows conversion between numeric data types using built-in functions:

FunctionPurposeExample & Output
int()Convert to integerint(3.7)3
float()Convert to floatfloat(5)5.0
complex()Convert to complexcomplex(2, 3)(2+3j)

Example Code:

a = 10        # int
b = 3.14      # float

# int to float
c = float(a)
print(c, type(c))  # 10.0 <class 'float'>

# float to int
d = int(b)
print(d, type(d))  # 3 <class 'int'>

# int to complex
e = complex(a)
print(e, type(e))  # (10+0j) <class 'complex'>

3. Notes on Conversion

  • Converting float → int truncates the decimal part (does not round).
  • Converting int → float adds .0 to the number.
  • Converting int/float → complex makes imaginary part 0 if not provided.

4. Conclusion

Dynamic typing ensures variables can change type with conversion functions.  

Python supports int, float, and complex numeric types.

Type conversion allows arithmetic between different numeric types and ensures compatibility.


BEU Exam Preparation Strategy

Section A Tips:

  • Practice output prediction
  • Learn common errors
  • Understand basic syntax

Section B Tips:

  • Write structured answers
  • Include code examples
  • Explain concepts clearly
  • Draw comparisons

Time Management:

  • Section A: 15-20 minutes
  • Section B: 40 minutes per question
  • Revision: 10 minutes

Important Topics to Revise

  • Data types and conversion
  • Control structures
  • Functions and scope
  • Strings and lists
  • File handling
  • Error handling

Good luck with your exams! Practice regularly and understand concepts thoroughly.

#BEU #PythonProgramming #ModelPaper2025 #ExamSolutions #EngineeringExams #CSE

Table of Contents