0% found this document useful (0 votes)
14 views133 pages

Python Programming Success Mantra Guide

The document outlines the examination structure and questions for Python Programming courses BCC-301 and BCC-401 at AKTU for the academic year 2023-24. It includes sections with various types of questions, such as brief descriptions, programming tasks, and theoretical explanations covering topics like list comprehension, file handling, and data visualization. The document serves as a guide for students preparing for their exams by providing a comprehensive list of potential questions and topics to study.

Uploaded by

guest1029384765
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)
14 views133 pages

Python Programming Success Mantra Guide

The document outlines the examination structure and questions for Python Programming courses BCC-301 and BCC-401 at AKTU for the academic year 2023-24. It includes sections with various types of questions, such as brief descriptions, programming tasks, and theoretical explanations covering topics like list comprehension, file handling, and data visualization. The document serves as a guide for students preparing for their exams by providing a comprehensive list of potential questions and topics to study.

Uploaded by

guest1029384765
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

Success Mantra for Python Programming BCC-301 & BCC-401

AKTU
Previous Year Question Papers

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 1 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

[Link].
(SEM III) THEORY EXAMINATION 2023-24
PYTHON PROGRAMMING (BCC-302)
Maximum Marks: 70
SECTION A
1. Attempt all questions in brief. Marks
a Describe the concept of list comprehension with a suitable example 2
b Differentiate between / and // operator with an example 2
c Compute the output of the following python code: 2
def count(s):
for str in [Link]():
s = “&”.join(str)
return s
print(count(“Python is fun to learn.”))
d How to use the functions defined in [Link] in [Link] 2
e Describe the difference between linspace and argspace. 2
f Explain why the program generates an error. 2
x = [‘12’, ’hello’, 456]
x *= 3
x=’bye
g Describe about different functions of matplotlib and pandas. 2

SECTION B
2. Attempt any three of the following: Marks
a Illustrate Unpacking tuples, mutable sequences, and string concatenation 7
with examples
b Illustrate different list slicing constructs for the following operations on 7
the following list: L = [1, 2, 3, 4, 5, 6, 7, 8, 9]
1. Return a list of numbers starting from the last to second item of the
list[1]
2. Return a list that start from 3rd item to second last item.[1]
3. Return a list that has only even position elements of list L to list
M.[1]
4. Return a list that starts from the middle of the list L.[1]
5. Return a list that reverses all the elements starting from element at
index 0 to middle index only and return the entire list.[1]
Divide each element of the list by 2 and replace it with the
remainder.[1]

c Construct a function perfect_square(number) that returns a number if it 7


is a perfect square otherwise it returns
For example:
perfect_square(1) returns 1
perfect_square (2) returns -1
d Construct a program to change the contents of the file by reversing each 7
character separated by comma:
Hello!!
Output
H,e,l,l,o,!,!

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 2 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

e Construct a plot for following dataset using matplotlib: 7


Food Calories Potassium fat
Meat 250 40 8
Banana 130 55 5
Avocados 140 20 3
Sweet
120 30 6
Potatoes
Spinach 20 40 1
Watermelon 20 32 1.5
Coconut
10 10 0
water
Beans 50 26 2
Legumes 40 25 1.5
Tomato 19 20 2.5

SECTION C
3. Attempt any one part of the following: Marks
a Determine a python function removenth(s,n) that takes an input a string 7
and an integer n>=0 and removes a character at index n. If n is beyond the
length of s, then whole s is returned.
For example:
removenth(“MANGO”,1) returns MNGO
removenth(“MANGO”,3) returns MANO
b Construct a program that accepts a comma separated sequence of words 7
as input and prints the words in a comma-separated sequence after
sorting them alphabetically.

Suppose the following input is supplied to the program:


without, hello, bag, world
Then, the output should be:
bag, hello, without, world

4. Attempt any one part of the following: Marks


a A website requires the users to input username and password to register. 7
Construct a program to check the validity of password input by users.
Following are the criteria for checking the password:
1. At least 1 letter between [a-z]
2. At least 1 number between [0-9]
3. At least 1 letter between [A-Z]
4. At least 1 character from [@$#]
5. Minimum length of transaction password: 6
6. Maximum length of transaction password: 12

Your program should accept a sequence of comma separated passwords


and will check them according to the above criteria. Passwords that match
the criteria are to be printed, each separated by a comma
b Explore the working of while, and for loop with examples. 7

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 3 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

5. Attempt any one part of the following: Marks


a A Construct a function ret smaller(l) that returns smallest list from a 7
nested list. If two lists have same length then return the first list that is
encountered. For example:
ret smaller([ [ -2, -1, 0, 0.12, 1, 2], , [6 , 7, 8, 9, 10], ]) returns
ret smaller([ [ -2, -1, 0, 0.12, 1, 2], [‘a’, ‘b’, ’c’, ’d’, 3, 4, 5], [6 , 7, 8, 9, 10], ])
returns [6 , 7, 8, 9, 10]

b Construct following filters: 7


1. Filter all the numbers
2. Filter all the strings starting with a vowel
3. Filter all the strings that contains any of the following noun: Agra,
Ramesh, Tomato, Patna.
Create a program that implements these filters to clean the text.

6. Attempt any one part of the following: Marks


a Change all the numbers in the file to text. Construct a program for the 7
same.
Example:
Given 2 integer numbers, return their product only if the product is equal
to or lower than 10.
And the result should be:
Given two integer numbers, return their product only if the product is
equal to or lower than one zero
b Construct a program which accepts a sequence of words separated by 7
whitespace as file input. Print the words composed of digits only.

7. Attempt any one part of the following: Marks


a Construct a program to read [Link] dataset, remove last column and 7
save it in an array. Save the last column to another array. Plot the first two
columns.
b Design a calculator with the following buttons and functionalities like 7
addition, subtraction, multiplication, division and clear.

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 4 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

[Link].
(SEM IV) THEORY EXAMINATION 2023-24
PYTHON PROGRAMMING (BCC-402)
Maximum Marks: 70
SECTION A
1. Attempt all questions in brief. Marks
a Give difference between == and is operator. 2
b How we print the character of a given ASCII value in Python? 2
c Can you use else with a for loop? If so, when is it executed? 2
d What will be the output of the following Python code? 2
l = [1, 0, 0, 2, 'hi', '', [ ]]
print(list(filter(bool, l)))
e Describe the purpose of the split() method in string manipulation. 2
f What does the readline() function return when it reaches the end of a file? 2
g Which function is used to create identity matrix in NumPy? 2

SECTION B
2. Attempt any three of the following: Marks
a Explain the concept of dynamic typing in Python with an example. 7
b Explain how to define a list in Python. Write a Python program to remove 7
duplicates from a list and print the resulting list.
c Explain the concept of functions in Python. Write a function that takes a 7
list of numbers and returns the sum of all the numbers in the list.
d Write a Python program to read a file named “[Link]” and count the 7
number of lines, words, and characters in the file.
e Explain the basic usage of matplotlib for plotting graphs. Write a Python 7
program to plot a simple line graph showing the relationship between x =
and y =.

SECTION C
3. Attempt any one part of the following: Marks
a Explain for and while loops used in Python with appropriate example 7
b Write a Python Program to find the LCM of two numbers. 7

4. Attempt any one part of the following: Marks


a Write a program takes two strings and checks common letters in both the 7
strings.
Enter first string: Hari
Enter second string: Hale
The common letters are:
H
a
b Write a Python Program to find the sum all the items in a dictionary. 7
For example if d= {'A':100,'B':540,'C':239} then output should be 879.

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 5 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

5. Attempt any one part of the following: Marks


a Explain the concept of a set in Python and its characteristics. How 7
elements are added or removed in set.
b Explain how lambda functions can be used within a list comprehension. 7
Write a Python program that uses a lambda function within a list
comprehension to convert a list of temperatures in Celsius to Fahrenheit.

6. Attempt any one part of the following: Marks


a Explain different file opening modes also write a Python Program to read 7
a file and capitalize the first letter of every word in the file.
b What do you mean by generators in Python? How it is created in Python? 7

7. Attempt any one part of the following: Marks


a Describe how to generate random numbers using NumPy. Write a Python 7
program to create an array of 5 random integers between 10 and 50.
b Explain the concept of DataFrame in pandas. Write a Python program to 7
create a DataFrame from a dictionary and print it.

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 6 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

[Link].
(SEM III) THEORY EXAMINATION 2024-25
PYTHON PROGRAMMING (BCC-302)
Maximum Marks: 70

SECTION A
1. Attempt all questions in brief. 2M X 7 = 14M
a State how to handle exceptions in Python? Provide a simple example. 2
b What will be the output of the following Python code? 2
def compute(x):
return [i**2 for i in x if i%2==0]
print(compute())
c Explain floor division with an example. 2
d Describe the purpose of the ‘with’ statement in file handling? 2
e Briefly describe the use of lambda functions in Python. 2
f Demonstrate how to assign a single value to a tuple. 2
g Explain why numpy is used instead of python arrays for mathematical 2
calculations?

SECTION B
2. Attempt any three of the following 7M X 3 =21M
a Design a basic calculator in Python that supports addition, subtraction, 7
multiplication, division.
b Define Membership and Identity Operators. 7
Given:
a=3
b=3
Distinguish between: (a is b) and (a == b) ?
c Write a Python function to count the frequency of each character in a given 7
string and return the output in a dictionary.
Example:
char_frequency("HELLO")
returns {'H':1, 'E':1, 'L':2, 'O':1}
d Write a program to reverse the contents of a file character by character, 7
separating each character with a comma.
e Create a pie chart using matplotlib to represent the following data: 7
Languages Popularity
Python 30
Java 25
C++ 20
JavaScript 15
Ruby 10

SECTION C
3. Attempt any one of the following 7M X 1 =7M
a Write short notes on the following with examples: 7
a) Operator Precedence
b) Python Indentation
c) Type Conversion
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 7 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

b Write a program to validate email addresses using regular expressions. 7


Criteria:
1. Must contain @ symbol
2. Must contain domain name
3. Should not have spaces

4. Attempt any one of the following 7M X 1 =7M


a Write a program to create a hollow pyramid pattern given below: 7
*
**
**
* *
* *
*********
b Explain the why loops are needed and the types of loops in python. Discuss 7
break and continue with example.

5. Attempt any one of the following 7M X 1 =7M


a Write a function to find the longest word in a given list of words. Example: 7
longest_word(['apple', 'banana', 'cherry']) returns 'banana'.
b Distinguish between a Tuple and a List with examples. Explain with 7
examples at least 4 built-in methods of Dictionary.

6. Attempt any one of the following 7M X 1 =7M


a Discuss different types of file modes in Python and explain with examples. 7
b Write a program to read a CSV file and display the rows where a specific 7
column value exceeds a given threshold.

7. Attempt any one of the following 7M X 1 =7M


a Discuss the role of event handling in Tkinter. How can events be bound to 7
widgets? Provide examples.
b Write a program to read data from a CSV file '[Link]', calculate the 7
average marks for each student, and display the results.

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 8 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

[Link].
(SEM IV) THEORY EXAMINATION 2024-25
PYTHON PROGRAMMING (BCC-402)
Maximum Marks: 70

SECTION A
1. Attempt all questions in brief. 2M X 7 = 14M
a What are Python variables? Explain with examples. 2
b Describe Python basic operators with suitable examples. 2
c Explain different Python data types with examples. 2
d How are numeric data types declared and used in Python? 2
e Write a Python program to demonstrate type casting between int, float, 2
and string.
f Explain the use of if, else, and elif. Write a Python program to check the 2
given number is even or odd using if and else statement.
g Differentiate between for loop and while loop with syntax and examples. 2

SECTION B
2. Attempt any three of the following 7M X 3 =21M
a What are break, continue, and pass statements? Give code examples. 7
b Write a Python program using for loop and dictionary to display student 7
grades.
c Discuss the use of nested loops in Python. Write a program to print a right- 7
angled triangle of stars.
d Explain string slicing and string operations in Python. 7
e Describe how tuples differ from lists in Python with examples. 7

SECTION C
3. Attempt any one of the following 7M X 1 =7M
a Write a program to demonstrate Create, Read, Update, and Delete (CRUD) 7
operations on a dictionary.
b Explain commonly used string methods in Python. Write a program using 7
the following operations on the given string:
text = " Machine Learning "
Use the following methods
 lower()
 upper()
 strip()
 replace()
 find()
 count()

4. Attempt any one of the following 7M X 1 =7M


a How can data be organized using complex data types in Python? 7
b Explain file handling modes in Python. 7

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 9 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

5. Attempt any one of the following 7M X 1 =7M


a Write a program to read and write data from a text file. How do readline() 7
and readlines() work? Explain with examples.
b What is the purpose of the seek() method in file handling? Demonstrate a 7
program that copies content from one file to another.

6. Attempt any one of the following 7M X 1 =7M


a Write a Python program using numpy to perform matrix operations. 7
b Explain the use of matplotlib for data visualization. Write a program to 7
visualize Line plots using these data:
x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 40]

7. Attempt any one of the following 7M X 1 =7M


a What is GUI programming in Python? Write a GUI-based Python program 7
using Tkinter to accept and display student data.
b How do we use packages in Python programming? Explain the use of 7
pandas.

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 10 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

[Link].
(SEM III) THEORY EXAMINATION 2023-24
PYTHON PROGRAMMING (BCC-302)
Maximum Marks: 70
SECTION A

Q.1. Attempt all questions in brief. (2M X 7 =14M)

a) Describe the concept of list comprehension with a suitable example


Solution:
 List comprehension is a simple and concise way to create lists in Python using a
single line of code.
 It combines a for loop and optional if condition into a compact expression.

Example 1: Squares of numbers


numbers = [1, 2, 3, 4, 5]
squares = [x**2 for x in numbers]
print(squares)
Output:
[1, 4, 9, 16, 25]

This single line [x**2 for x in numbers] replaces the 3 lines of the for loop.

Example 2: Even numbers only


numbers = [1, 2, 3, 4, 5, 6]
evens = [x for x in numbers if x % 2 == 0]
print(evens)
Output:
[2, 4, 6]

The condition if x % 2 == 0 filters only even numbers.

Advantages of List Comprehension


 Shorter code compared to normal loops
 More readable and Pythonic
 Efficient for simple operations
 Easy to apply filters or transformations

b) Differentiate between / and // operator with an example


Solution:

1. / Operator (Division)
Performs floating-point division and always returns a float, even if the
division is exact.
2. // Operator (Floor Division)
Performs division and returns the integer part of the quotient and discards
the decimal part.

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 11 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

Table: Difference between / and // operator


Exam
Operator Name Description Output
ple
Division Performs floating-point
/ 7/2 3.5
Operator division
Floor Performs integer division,
// 7 // 2 3
Division discards decimal

Example Program: / and // operator


a=7
b=2
print(a / b) # Output: 3.5 (normal division)
print(a // b) # Output: 3 (floor division)

Output:
3.5
3
c) Compute the output of the following python code:
def count(s):
for str in [Link]():
s = “&”.join(str)
return s
print(count(“Python is fun to learn.”))

Solution:
SyntaxError: invalid character in identifier

Corrected Program
def count(s):
for str in [Link](): # Fixed: [Link]() instead of [Link]()
s = "&".join(str) # This overwrites 's' in each iteration
return s
print(count("Python is fun to learn."))
Final Output:
l&e&a&r&n&.

d) How to use the functions defined in [Link] in [Link]


Solution:
Steps:
1. Create [Link] with the functions
2. Create [Link] with the import statement
3. Run [Link] - it will automatically use functions from [Link]
4. Both files must be in the same folder

File 1: [Link]
# [Link]
# This file contains some useful functions

def add(a, b):


return a + b

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 12 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

def multiply(a, b):


return a * b

File 2: [Link]
# [Link]
# This file uses the functions from [Link]

# Step 1: Import the functions from [Link]


from library import add, multiply

# Step 2: Use the imported functions


num1 = 5
num2 = 3

print("Addition Result:", add(num1, num2))


print("Multiplication Result:", multiply(num1, num2))

Output:
Addition Result: 8
Multiplication Result: 15

Explanation:
1. [Link] – contains function definitions (add and multiply).
2. [Link] – imports those functions using
from library import add, multiply.
3. The functions are then called directly in [Link].
4. You only run [Link], and it automatically uses the functions from [Link].

Note:
Both files ([Link] and [Link]) must be saved in the same folder.

e) Describe the difference between linspace and arrange.


Solution:
linspace generates evenly spaced numbers over a specified inter val, while arange
generates numbers in a specified range with a specified step
import numpy as np
np. linspace (0 , 1, 5) # Output: [0. 0.25 0.5 0.75 1.]
np. arange(0 , 1, 0.25) # Output: [0. 0.25 0.5 0.75]

f) Explain why the program generates an error.


x = [‘12’, ’hello’, 456]
x *= 3
x=’bye
Solution:
1. Line 1: x = ['12', 'hello', 456] ✅ - Works fine
2. Line 2: x *= 3 ✅ - Works fine (repeats the list 3 times)
3. Line 3: x = 'bye ❌ - ERROR!
The string 'bye is missing its closing single quote and it throws a syntax error

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 13 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

g) Describe about different functions of matplotlib and pandas.


Solution:

Purpose
Matplotlib (Visualization) Pandas (Data Manipulation)
Creates visual representations of data Organizes, cleans, and analyzes tabular data

Difference between Matplotlib vs Pandas


Matplotlib Pandas
Like a paintbrush Like an Excel sheet
Creates visualizations Organizes and cleans data
Makes graphs and charts Handles tables and calculations
Output: Pictures/Graphs Output: Cleaned/Processed Data

Note: for 2 Marks the above answer is enough.

Function Comparison
Matplotlib Pandas
Purpose Purpose
Function Function
[Link]() Line charts pd.read_csv() Read data files
[Link]() Dot plots [Link]() View first few rows
Vertical bar Data structure and
[Link]() [Link]()
charts types
[Link]() Histograms [Link]() Summary statistics
[Link]() Pie charts df['column'] Select specific column
Group data for
[Link]() Add chart title [Link]()
aggregation
[Link]() /
Axis labels df.sort_values() Sort data by column
[Link]()
Add legend to
[Link]() [Link]() Remove missing values
chart
[Link]() Add grid lines [Link]() Fill missing values
Correlation between
[Link]() Display the plot [Link]()
columns

SECTION B

Q.2. Attempt any three of the following (7M X 3 =21M)

a. Illustrate Unpacking tuples, mutable sequences, and string concatenation with


examples.

Solution:
1. Unpacking Tuples
 Unpacking means assigning the elements of a tuple to separate variables in a
single statement.
 Number of variables must match the number of elements in the tuple.

Example Unpacking Tuples

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 14 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

t = (10, 20, 30) Output:


a, b, c = t 10
print(a) # 10 20
print(b) # 20 30
print(c) # 30

2. Mutable Sequences
 Mutable sequences can be changed after creation (like lists).
 You can modify, add, or remove elements.

Example (List):
numbers = [1, 2, 3] Output:
numbers[0] = 10 # modify first element [10, 2, 3, 4]
[Link](4) # add element at the end
print(numbers) # [10, 2, 3, 4]

3. String Concatenation
 Concatenation means joining strings together using +.
 Creates a new string without modifying original strings.

Example String Concatenation


str1 = "Hello" Output:
str2 = "World" Hello World
result = str1 + " " + str2
print(result) # Hello World
Explanation:
1. str1 = "Hello" → Assigns the string "Hello" to variable str1.
2. str2 = "World" → Assigns the string "World" to variable str2.
3. result = str1 + " " + str2 → Concatenates (+) the two strings with a space "
" in between.
4. print(result) → Displays the final string:

b. Illustrate different list slicing constructs for the following operations on the
following list: L = [1, 2, 3, 4, 5, 6, 7, 8, 9]
1. Return a list of numbers starting from the last to second item of the list
2. Return a list that start from 3rd item to second last item.
3. Return a list that has only even position elements of list L to list M.
4. Return a list that starts from the middle of the list L.
5. Return a list that reverses all the elements starting from element at index 0 to
middle index only and return the entire list.

Divide each element of the list by 2 and replace it with the remainder.

Solution:
Given List
L = [1, 2, 3, 4, 5, 6, 7, 8, 9]

1. Return a list of numbers starting from the last to the second item of the list:
Use slicing with negative indices and step -1 for reverse order.

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 15 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

L = [1, 2, 3, 4, 5, 6, 7, 8, 9] Output:
print(L[-1:0:-1]) [9, 8, 7, 6, 5, 4, 3, 2]
Explanation:
 L[-1:0:-1] → starts from last element (-1) and stops before index 0.
 Step -1 means reverse order.

2. Return a list that starts from the 3rd item to the second last item:
Index positions start from 0.

L = [1, 2, 3, 4, 5, 6, 7, 8, 9] Output:
print(L[2:-1]) [3, 4, 5, 6, 7, 8]

Explanation:
 Index starts from 0.
 L[2:-1] means from the 3rd element (index 2) to the second last element (index
-1).

3. Return a list that has only even position elements of list L to list M:
Even positions mean indices 0, 2, 4, 6, 8...

L = [1, 2, 3, 4, 5, 6, 7, 8, 9] Output:
M = L[::2] [1, 3, 5, 7, 9]
print(M)
Explanation:
 L[::2] → step of 2 means take every 2nd element starting from index 0.

4. Return a list that starts from the middle of the list L:


Find the middle index using len(L)//2.

L = [1, 2, 3, 4, 5, 6, 7, 8, 9] Output:
mid = len(L)//2 [5, 6, 7, 8, 9]
print(L[mid:])
Explanation:
 len(L)//2 gives the middle index = 4.
 L[4:] gives all elements from index 4 to the end.

5. Return a list that reverses all elements starting from index 0 to the middle index
only and return the entire list:
Reverse the first half and keep the second half as it is.

# Method-1 Output:
L = [1, 2, 3, 4, 5, 6, 7, 8, 9] [4, 3, 2, 1, 5, 6, 7, 8, 9]
mid = len(L)//2
result = L[:mid][::-1] + L[mid:]
print(result)

Explanation:
 L[:mid][::-1] reverses the first half → [1, 2, 3, 4] → [4, 3, 2, 1]
 L[mid:] keeps the second half same.
 + joins both lists together.

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 16 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

# Method-2
# Step 1: Define the original list
L = [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Step 2: Find the middle index


mid = len(L) // 2 # len(L) = 9 → mid = 4

# Step 3: Slice the first half of the list


first_half = L[:mid] # L[0:4] → [1, 2, 3, 4]

# Step 4: Reverse the first half


reversed_first_half = first_half[::-1] # → [4, 3, 2, 1]

# Step 5: Slice the second half of the list


second_half = L[mid:] # L[4:] → [5, 6, 7, 8, 9]

# Step 6: Combine both halves


result = reversed_first_half + second_half

# Step 7: Print the final result


print(result)
Output:
[4, 3, 2, 1, 5, 6, 7, 8, 9]

Explanation:
 L[:mid] gets the first half.
 [::-1] reverses that half.
 L[mid:] gets the second half.
 + joins both parts into one list.

6. Divide each element of the list by 2 and replace it with the remainder:
Use list comprehension with the modulus operator %.

L = [1, 2, 3, 4, 5, 6, 7, 8, 9] Output:
L = [x % 2 for x in L] [1, 0, 1, 0, 1, 0, 1, 0, 1]
print(L)

Explanation:
 x % 2 gives the remainder when each element is divided by 2.
 Even numbers give 0, odd numbers give 1.

c. Construct a function perfect_square(number) that returns a number if it is a


perfect square otherwise it returns
For example:
perfect_square(1) returns 1
perfect_square (2) returns -1

Solution:
Example: Perfect Square Program without using math Library (Method-1)

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 17 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

def perfect_square(number): Output:


i=1 Enter a number: 9
Output: 9
# Loop until i*i exceeds the number
while i * i <= number: Enter a number: 25
Result: 25
# Check if i*i equals the number
if i * i == number: Enter a number: 20
return number Result: -1
i += 1
# If no perfect square found, return -1
return -1

# Take input from the keyboard


num = int(input("Enter a number: "))
# Call the function and display result
result = perfect_square(num)
print("Result:", result)

Explanation:
 The program checks whether the number is a perfect square.
 If yes → returns the number itself.
 If not → returns -1.
 The user enters the number from the keyboard, and the result is printed.

Example: Perfect Square Program using math Library (Method-2)


import math Output:
Enter a number: 9
def perfect_square(number): Output: 9
root = int([Link](number))
if root * root == number: Enter a number: 25
return number Result: 25
else:
return -1 Enter a number: 20
Result: -1
# Take input from the user
num = int(input("Enter a number: "))

# Call the function and display result


result = perfect_square(num)
print("Result:", result)
Explanation:
1. [Link](number) → finds the square root of the number.
Example:
 [Link](9) → 3.0
 [Link](15) → 3.8729…
2. int([Link](number)) → takes only the integer part (e.g., 3).
3. The program checks whether root * root == number:
 If True → number is a perfect square.
 Else → it’s not.

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 18 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

d. Construct a program to change the contents of the file by reversing each character
separated by comma:
Hello!!
Output
H,e,l,l,o,!,!
Solution:
Example: Reverse Each Character and Separate by Comma

If file [Link] contains: Hello!!


# Open the file in write mode and add the text
file = open("[Link]", "w")
[Link]("Hello!!")
[Link]()

# Open the file in read mode


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

# Reverse the content and separate each character by comma


reversed_content = ",".join(content[::-1])

# Open the file again in write mode to update the content


file = open("[Link]", "w")
[Link](reversed_content)
[Link]()
print("File content has been updated successfully!")
print("Output:", reversed_content)

Output:
File content has been updated successfully!
Output: !,!,o,l,l,e,H

Explanation:
1. Write "Hello!!" into a file named [Link].
2. Read the file content using .read().
3. Reverse the string using slicing → content[::-1].
4. Insert commas between characters using ",".join(...).
5. Write the modified string back to the file.
**In this question, it is stated to reverse the file content "Hello!!", but the given
output is H,e,l,l,o,!,!. Therefore, we only need to insert commas between each
character. The program is given below.

Hello!!
Output
H,e,l,l,o,!,!

Example: Separate Each Character by a Comma


If file [Link] contains: Hello!!
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 19 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

# Step 1: Open the file in write mode and add text


file = open("[Link]", "w")
[Link]("Hello!!")
[Link]()

# Step 2: Open the file in read mode


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

# Step 3: Add commas between each character


new_content = ",".join(content)

# Step 4: Open the file again in write mode to update content


file = open("[Link]", "w")
[Link](new_content)
[Link]()

# Step 5: Display the updated content


print("File content has been updated successfully!")
print("Output:", new_content)

Output:
File content has been updated successfully!
Output: H,e,l,l,o,!,!

Explanation:
1. The file [Link] is created and the word Hello!! is written into it.
2. The program reads the content of the file.
3. The statement ",".join(content) inserts a comma after every character.
4. The updated string is written back into the same file.
5. The final output is displayed on the screen.

e. Construct a plot for following dataset using matplotlib:


Food Calories Potassium fat
Meat 250 40 8
Banana 130 55 5
Avocados 140 20 3
Sweet
120 30 6
Potatoes
Spinach 20 40 1
Watermelon 20 32 1.5
Coconut
10 10 0
water
Beans 50 26 2
Legumes 40 25 1.5
Tomato 19 20 2.5

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 20 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

Solution:

Example: Separate Each Character by a Comma


import [Link] as plt
import numpy as np

# Data
food = ["Meat", "Banana", "Avocados", "Sweet Potatoes", "Spinach",
"Watermelon", "Coconut water", "Beans", "Legumes", "Tomato"]

calories = [250, 130, 140, 120, 20, 20, 10, 50, 40, 19]
potassium = [40, 55, 20, 30, 40, 32, 10, 26, 25, 20]
fat = [8, 5, 3, 6, 1, 1.5, 0, 2, 1.5, 2.5]

# X-axis positions
x = [Link](len(food))
width = 0.25 # width of each bar

# Plot bar chart


[Link](x - width, calories, width, label='Calories', color='red')
[Link](x, potassium, width, label='Potassium', color='green')
[Link](x + width, fat, width, label='Fat', color='blue')

# Labels and title


[Link]("Food Items")
[Link]("Nutritional Values")
[Link]("Nutritional Comparison of Food Items")
[Link](x, food, rotation=30)
[Link]()

# Display chart
[Link]()
Output:

Explanation:
1. Import libraries:
 [Link] → used to create graphs.
 numpy → used for handling numerical data and positions on the X-
axis.
2. Data creation:

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 21 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

 Lists food, calories, potassium, and fat store the nutritional


information for each food item.
3. X-axis setup:
 [Link](len(food)) creates numeric positions for each food item.
 width = 0.25 sets the thickness of each bar.
4. Plotting bars:
 [Link](x - width, calories, ...) → plots red bars for Calories.
 [Link](x, potassium, ...) → plots green bars for Potassium.
 [Link](x + width, fat, ...) → plots blue bars for Fat.
 This arrangement groups the bars for each food item side by side.
5. Labels and formatting:
 Adds X-axis, Y-axis labels, and a title.
 [Link](..., rotation=30) rotates the food names for readability.
 [Link]() shows the color key (Calories, Potassium, Fat).
6. Show the chart:
 [Link]() displays the final grouped bar chart comparing
nutritional values.

SECTION C

Q.3. Attempt any one part of the following: 7M X 1 = 7M

a. Determine a python function removenth(s,n) that takes an input a string and an


integer n>=0 and removes a character at index n. If n is beyond the length of s, then
whole s is returned.
For example:
removenth(“MANGO”,1) returns MNGO
removenth(“MANGO”,3) returns MANO
Solution:

Program: A python function removenth(s,n)

def removenth(s, n): # Define function with string s and index n


if n < 0 or n >= len(s) : # Check if n is invalid
return s # Return original string if n out of bounds
return (s[:n] + s[n+1:]) # Return new string removing char at n

input_string = input("Enter a string: ") # Get string from user


index = int(input("Enter the index to remove (0 or greater): ")) # Get index as integer

result = removenth(input_string, index) # Call function and store result


print(f"Result after removing character at index {index}: {result}") # Print result
Output: Case-2
Enter a string: MANGO
Enter the index to remove (0 or greater): 1
Result after removing character at index 1: MNGO
Output: Case-2
Enter a string: MANGO
Enter the index to remove (0 or greater): 3
Result after removing character at index 5: MANO

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 22 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

How s[:n] + s[n+1:] Works


For s = "MANGO", n = 1:

Part Expression Result Explanation


Before s[:1] "M" Characters from start (index 0) to before index 1
Skip s[1:2] "A" SKIPPED - This is the character we remove
After s[2:] "NGO" Characters from index 2 to end
Combine "M" + "NGO" "MNGO" Final result

Note:
Output for different cases for quick references:
Input n Condition n < 0 or n >= len(s) Result
"MANGO", 1 1 False (0 ≤ 1 < 5) "MNGO"
"MANGO", 3 3 False (0 ≤ 3 < 5) "MANO"
"MANGO", 5 5 True (5 ≥ 5) "MANGO"
"MANGO", -1 -1 True (-1 < 0) "MANGO"

b. Construct a program that accepts a comma separated sequence of words as input


and prints the words in a comma-separated sequence after sorting them
alphabetically.

Suppose the following input is supplied to the program:


without, hello, bag, world
Then, the output should be:
bag, hello, without, world

Solution:
METHOD-1: Sort words even if separated by commas and/or spaces
text = input("Enter words (use commas and/or spaces): ")

# 1) Replace commas with spaces, then split on whitespace


words = [Link](",", " ").split()
# 2) Sort (optional: ignore case with key=[Link])
[Link]()
# 3) Join back (choose space or comma as you like)
print("Sorted words (space-separated):", " ".join(words))
print("Sorted words (comma-separated):", ", ".join(words))
Output:
Enter words (use commas and/or spaces): without, hello, bag, world
Sorted words (space-separated): bag hello without world
Sorted words (comma-separated): bag, hello, without, world

METHOD-2: sort words into lower case


text = input("Enter words (use commas and/or spaces): ")

# 1) Replace commas with spaces, then split on whitespace


words = [Link](",", " ").split()

# 2) Convert all to lowercase


words = [[Link]() for w in words if w]
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 23 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

# 3) Sort (already lowercase, so normal alphabetical order)


[Link]()

# 4) Join back (space or comma style)


print("Sorted words (space-separated):", " ".join(words))
print("Sorted words (comma-separated):", ", ".join(words))
Output:
Enter words (use commas and/or spaces): Rahul, ECE, Department, JSSATE, NOIDA
Sorted words (space-separated): department ece jssate noida rahul
Sorted words (comma-separated): department, ece, jssate, noida, rahul

METHOD-3: sort words without converting into lower case


text = input("Enter words (use commas and/or spaces): ")

# 1) Replace commas with spaces, then split on any whitespace


words = [Link](",", " ").split()
# 2) Sort ignoring case
[Link](key=[Link])
# 3) Join back (choose space or comma as you like)
print("Sorted words (space-separated):", " ".join(words))
print("Sorted words (comma-separated):", ", ".join(words))
Output:
Enter words (use commas and/or spaces): Rahul, ECE, Department, JSSATE, NOIDA
Sorted words (space-separated): Department ECE JSSATE NOIDA Rahul
Sorted words (comma-separated): Department, ECE, JSSATE, NOIDA, Rahul

Q.4. Attempt any one part of the following: 7M X 1 = 7M

a. A website requires the users to input username and password to register.


Construct a program to check the validity of password input by users.

Following are the criteria for checking the password:


1. At least 1 letter between [a-z]
2. At least 1 number between [0-9]
3. At least 1 letter between [A-Z]
4. At least 1 character from [@$#]
5. Minimum length of transaction password: 6
6. Maximum length of transaction password: 12

Your program should accept a sequence of comma separated passwords and will
check them according to the above criteria. Passwords that match the criteria are to
be printed, each separated by a comma

Solution:
# Check if a password is valid
def check_password(password):
# Rule 1: Length between 6 and 12
if len(password) < 6 or len(password) > 12:
return False

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 24 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

# Rule 2 to 5: Check for required characters


has_lower = False
has_upper = False
has_digit = False
has_special = False

for ch in password:
if ch in "abcdefghijklmnopqrstuvwxyz": # or if 'a' <= ch <= 'z':
has_lower = True
if ch in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": # or elif 'A' <= ch <= 'Z':
has_upper = True
if ch in "0123456789": # or elif '0' <= ch <= '9':
has_digit = True
if ch in "@$#": # elif ch in "@$#":
has_special = True

# Return True only if all rules are satisfied


if has_lower and has_upper and has_digit and has_special:
return True
else:
return False

# Get input from user


text = input("Enter passwords separated by commas: ")

# Split the input into a list


passwords = [Link](",")

# Check each password and collect valid ones


valid_passwords = []
for p in passwords:
if check_password(p):
valid_passwords.append(p)

# Show valid passwords


print("Valid passwords:", ",".join(valid_passwords))
Output:
Enter passwords separated by commas: ABc123$, Pass#1, hello123, A1@bcdef, XYZ$12,
aB3@x
Valid passwords: ABc123$, Pass#1, A1@bcdef, aB3@x

b. Explore the working of while, and for loop with examples


Solution:
Loops are used to repeat a block of code multiple times until a certain condition
is met.
Python provides two main types of loops:
1. for loop
2. while loop
1. for Loop:

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 25 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

 The for loop is used to iterate over a sequence (like a list, tuple, string, or
range of numbers).
 It automatically goes through each element in the sequence.

Syntax: for Loop


for variable in sequence:
# body of loop
Explanation:
 variable: Takes each value from the sequence one at a time.
 sequence: Can be a list, tuple, string, or range().

Flowchart of for Loop

# Example of for loop Output:


for i in range(1, 6): Number: 1
print("Number:", i) Number: 2
Number: 3
Number: 4
Number: 5
Explanation:
 range(1, 6) generates numbers from 1 to 5.
 The loop runs five times, printing each number.

2. while Loop:
 The while loop repeats a block of code as long as a given condition is true.
 You must make sure the condition eventually becomes false to avoid an
infinite loop.

Syntax: while Loop


while condition:
# body of loop
Explanation:
 condition: A boolean expression (True or False).
 As long as this condition is True, the loop continues executing.

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 26 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

Flowchart of while Loop

# Example of while loop Output:


i=1 Number: 1
while i <= 5: Number: 2
print("Number:", i) Number: 3
i=i+1 Number: 4
Number: 5
Explanation:
 The loop starts with i = 1.
 It runs as long as i <= 5.
 Each time, it prints the value of i and increases it by 1.

Difference between for and while Loops


Feature for Loop while Loop
Use case Used when number of Used when number of iterations
iterations is known is unknown
Syntax for i in range(…): while condition:
Control Iterates through a sequence Runs until a condition becomes
false

Q.5. Attempt any one part of the following: 7M X 1 = 7M

a. Construct a function ret smaller(l) that returns smallest list from a nested list. If
two lists have same length then return the first list that is encountered.
For example:
ret smaller([ [ -2, -1, 0, 0.12, 1, 2], , [6 , 7, 8, 9, 10] ])  returns [6 , 7, 8, 9, 10]
ret smaller([ [ -2, -1, 0, 0.12, 1, 2], [‘a’, ‘b’, ’c’, ’d’, 3, 4, 5], [6 , 7, 8, 9, 10] ])  returns [6 ,
7, 8, 9, 10]

Solution:
def ret_smaller(lists):
smallest = lists[0] # Start with first list
for each in lists: # Look at each list
if len(each) < len(smallest): # If shorter
smallest = each # Use it as new smallest
return smallest # Give back smallest list

# Tests
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 27 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

print(ret_smaller([[-2, -1, 0, 1, 2], [6, 7, 8, 9, 10]]))


print(ret_smaller([[-2, -1, 0, 1, 2], ['a', 'b', 'c', 'd', 3, 4, 5], [6, 7, 8, 9, 10]]))
Output:
[-2, -1, 0, 1, 2]
[6, 7, 8, 9, 10]
Explanation
1. Function definition
def ret_smaller(lists):
 This defines a function named ret_smaller.
 It takes one argument lists, which is expected to be a nested list (a list
containing other lists).
2. Start with the first list
smallest = lists[0]
 The first sublist is assumed to be the smallest for now.
 Example: if lists = [[1,2,3], [4,5]], then smallest = [1,2,3] initially.
3. for each in lists:
 Goes through each sublist one by one from the main list.
4. Compare lengths
5. if len(each) < len(smallest):
6. smallest = each
 len(each) gives the number of elements in the current sublist.
 If it is smaller than the length of the current smallest,
then that sublist becomes the new smallest.
 If two lists have the same length, the first one remains (because no <
change happens).
7. Return result
return smallest
 After checking all lists, the function returns the shortest sublist.
8. Testing the function
9. print(ret_smaller([[-2, -1, 0, 1, 2], [6, 7, 8, 9, 10]]))
10. Both lists have equal length (5) → Returns the first list: [-2, -1, 0, 1, 2]
print(ret_smaller([[-2, -1, 0, 1, 2], ['a', 'b', 'c', 'd', 3, 4, 5], [6, 7, 8, 9, 10]]))
 Lengths:
1. 1st list = 5
2. 2nd list = 7
3. 3rd list = 5
The first smallest list is kept if two lists have the same size: Smallest list = [6, 7, 8, 9,
10]

b. Construct following filters:


1. Filter all the numbers
2. Filter all the strings starting with a vowel
3. Filter all the strings that contains any of the following noun: Agra, Ramesh,
Tomato, Patna.
Create a program that implements these filters to clean the text.

Solution:

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 28 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

# Ask the user to enter words


text = input("Enter words separated by spaces: ")

# Split the sentence into a list of words


words = [Link]()

# Lists to store filtered results


numbers = []
vowel_words = []
special_nouns = []

# Vowels and special nouns to check


vowels = "aeiouAEIOU"
nouns = ["Agra", "Ramesh", "Tomato", "Patna"]

# Go through each word


for word in words:
# Check if it's a number
if [Link]():
[Link](word)

# Check if it starts with a vowel


elif word[0] in vowels:
vowel_words.append(word)

# Check if it's a special noun


elif word in nouns:
special_nouns.append(word)

# Show the results


print("\n--- Filter Results ---")
print("Numbers:", numbers)
print("Words starting with a vowel:", vowel_words)
print("Special nouns:", special_nouns)
Enter words separated by spaces: apple 123 Orange Ramesh Agra 45 umbrella
Tomato Patna banana
Output:
--- Filter Results ---
Numbers: ['123', '45']
Words starting with a vowel: ['apple', 'Orange', 'umbrella']
Special nouns: ['Ramesh', 'Agra', 'Tomato', 'Patna']

Explanation
Input from the user
text = input("Enter words separated by spaces: ")
This line asks the user to enter a few words separated by spaces.
Example input:
Agra is 45 a beautiful city Ramesh lives in Patna 100 Tomato
The entered text is stored in the variable text.
Split the sentence into words
words = [Link]()
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 29 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

The split() function breaks the sentence into separate words based on
spaces.
Example result:
['Agra', 'is', '45', 'a', 'beautiful', 'city', 'Ramesh', 'lives', 'in', 'Patna', '100',
'Tomato']
Define vowels and special nouns
vowels = "aeiouAEIOU"
nouns = ["Agra", "Ramesh", "Tomato", "Patna"]
 vowels contain all uppercase and lowercase vowels.
 nouns is a list of specific words we want to find in the text. These are
special nouns - Agra, Ramesh, Tomato, and Patna.
Create empty lists to store results
numbers = []
vowel_words = []
noun_words = []
 These are empty lists where we will store filtered words:
 numbers → will store all numeric values (e.g., 45, 100)
 vowel_words → will store words starting with vowels (e.g., Agra, is,
a)
 noun_words → will store the special nouns (e.g., Agra, Patna)
Check each word using a loop
for word in words:
 This for loop goes through each word from the list words.
 Example sequence: checks "Agra", then "is", then "45", and so on.
Filter 1 → Check if it is a number
if [Link]():
[Link](word)
 isdigit() checks if the word is made up of only digits (0–9).
 If yes, the word is added to the numbers list. Example: "45" and "100"
will be added.
Filter 2 → Check if it starts with a vowel
elif word[0] in vowels:
vowel_words.append(word)
 word[0] takes the first letter of the word.
 If this letter is present in "aeiouAEIOU", the word starts with a vowel.
 It is then added to the vowel_words list. Example: "Agra", "is", and "a"
will be added.
Filter 3 → Check if it matches any special noun
elif word in nouns:
noun_words.append(word)
 Checks if the whole word exactly matches any of the special nouns in
the list.
 If found, it is added to the noun_words list. Example: "Agra", "Ramesh",
"Patna", "Tomato".
Display the results
print("\n--- Filter Results ---")
print("Numbers:", numbers)
print("Words starting with a vowel:", vowel_words)
print("Special nouns:", noun_words)
 Prints a neat summary of all filtered results.
 \n adds a blank line before printing results.
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 30 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

Example Execution

Input:
Agra is 45 a beautiful city Ramesh lives in Patna 100 Tomato
Output:
--- Filter Results ---
Numbers: ['45', '100']
Words starting with a vowel: ['Agra', 'is', 'a']
Special nouns: ['Agra', 'Ramesh', 'Patna', 'Tomato']

Q.6. Attempt any one part of the following: 7M X 1 = 7M

a. Change all the numbers in the file to text. Construct a program for the same.
Example:
Given 2 integer numbers, return their product only if the product is equal to or lower than
10.
And the result should be:
Given two integer numbers, return their product only if the product is equal to or lower
than one zero

Solution:

Replace Numbers with Words in Text


# Step 1: Define a dictionary for number-to-word conversion
num_to_word = {
'0': 'zero',
'1': 'one',
'2': 'two',
'3': 'three',
'4': 'four',
'5': 'five',
'6': 'six',
'7': 'seven',
'8': 'eight',
'9': 'nine',
'10': 'one zero'
}
# Step 2: Input sentence from user
text = input("Enter a sentence: ")
# Step 3: Split sentence into words
words = [Link]()

# Step 4: Replace numbers with words


new_words = []
for word in words:
if word in num_to_word:
new_words.append(num_to_word[word])
else:
new_words.append(word)
# Step 5: Join and print the updated sentence
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 31 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

new_text = ' '.join(new_words)


print("\nUpdated sentence:")
print(new_text)
Enter a sentence: Given 2 integer numbers, return their product only if the product is
equal to or lower than 10.

Output:
Updated sentence:
Given two integer numbers, return their product only if the product is equal
to or lower than one zero.
Explanation
Define a dictionary
num_to_word = {'0': 'zero', '1': 'one', '2': 'two', ...}
 A dictionary stores number–word pairs.
Example: '2' → 'two', '10' → 'one zero'.
Take input from the user
text = input("Enter a sentence: ")
 The program asks the user to type a sentence.
 Example:
 Given 2 integer numbers ...
Split the sentence into words
words = [Link]()
 split() breaks the sentence into a list of words.
Example:
 ['Given', '2', 'integer', 'numbers,', ...]
Check each word and replace numbers
for word in words:
if word in num_to_word:
new_words.append(num_to_word[word])
else:
new_words.append(word)
 The program goes through each word:
 If it’s a number (like '2'), it replaces it using the dictionary.
 Otherwise, it keeps the original word.
 The modified words are stored in a new list called new_words.
Join the new words into a sentence
new_text = ' '.join(new_words)
 Joins all the updated words into one complete sentence with spaces between
them.
Display the result
print(new_text)
 Prints the final sentence where all numbers are now written in words.

b. Construct a program which accepts a sequence of words separated by whitespace


as file input. Print the words composed of digits only.

Solution:
Print Words Made of Digits Only from a File (Methos-1: Using .txt file)

The file .txt contains:

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 32 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

hello 123 welcome 45 to 6789 python 007 this file 55 contains 9


numbers 10
# Step 1: Open the input file
with open("[Link]", "r") as file:
text = [Link]() # Read all text

# Step 2: Split the content into words (spaces, tabs, or newlines)


words = [Link]()

# Step 3: Check each word


for word in words:
if [Link](): # If the word is made of digits only
print(word) # Print it
Output:
123
45
6789
007
55
9
10
Explanation
Opening the file
with open("[Link]", "r") as file:
 This line opens the file named [Link] in read mode ("r").
 The keyword with ensures the file closes automatically after reading it is
safe and efficient.
 The opened file is referred to by the variable file.

Reading the content of the file


text = [Link]()
 This reads the entire text content of the file and stores it in the variable text.
 Example content inside the file might be:
 hello 123 welcome 45 to 6789 python 007
 this file 55 contains 9 numbers 10
 After reading,
 text = "hello 123 welcome 45 to 6789 python 007 this file 55 contains 9
numbers 10"
Splitting the text into words
words = [Link]()
 The split() function divides the text into a list of individual words using
spaces, tabs, or newlines as separators.
 Example result:
 ['hello', '123', 'welcome', '45', 'to', '6789', 'python', '007', 'this', 'file', '55',
'contains', '9', 'numbers', '10']
Loop through each word
for word in words:
 This loop checks each word in the list one by one.
 Example: it first checks 'hello', then '123', then 'welcome', and so on.
Check if a word is made of digits
if [Link]():
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 33 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

 The function isdigit() returns True if all characters in the word are digits
(0–9).
 Example results:
 '123'.isdigit() → True
 'hello'.isdigit() → False
 '007'.isdigit() → True
Print the numeric words
print(word)
 If the condition is True, the program prints that word meaning it’s a
number.
 Each number appears on a new line in the output.

Print Words Made of Digits Only from a File (Methos-2: Using String operation)
# Step 1: Ask the user to enter a sequence of words separated by
spaces
text = input("Enter a sequence of words separated by spaces: ")
# Step 2: Split the text into a list of words
words = [Link]()
# Step 3: Print words composed of digits only
print("\nWords composed of digits only:")
for word in words:
if [Link](): # Check if the word contains only digits
print(word)
Enter a sequence of words separated by spaces: hello 123 world 45 python
6789 code 007

Output:
Words composed of digits only:
123
45
6789
007
Explanation
1. The program asks for a sentence or sequence of words.
2. It splits the sentence into individual words using split().
3. For each word:
 isdigit() checks if it’s made only of digits (0–9).
 If yes, it prints that word.
4. So, only numeric words are shown in the output.

Q.7. Attempt any one part of the following: 7M X 1 = 7M

a. Construct a program to read [Link] dataset, remove last column and save it in
an array. Save the last column to another array. Plot the first two columns.

Solution:
import pandas as pd
import [Link] as plt
import io

# ---- 1. Sample CSV with your header & extra column ----
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 34 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

csv_content = """City, State, Population, Temperature


Delhi, Delhi, 30000000, 35
Mumbai, Maharashtra, 20000000, 32
Bangalore, Karnataka, 13000000, 28
Chennai, Tamil Nadu, 11000000, 33
Kolkata, West Bengal, 15000000, 30"""

# ---- 2. Load as DataFrame ----


cities_df = pd.read_csv([Link](csv_content))

# ---- 3. Convert to arrays ----


cities_array = cities_df.values
last_column = cities_array[:, -1] # Temperature
data_without_last = cities_array[:, :-1] # City, State, Population

# ---- 4. PLOT: Population vs Temperature (Numeric!) ----


population = data_without_last[:, 2].astype(float) # 3rd column
temperature = last_column.astype(float)

[Link](figsize=(8, 5))
[Link](population, temperature, color='blue', s=100,
edgecolors='black')

# Add city names on points


cities = data_without_last[:, 0]
for i, city in enumerate(cities):
[Link](population[i] + 200000, temperature[i], city, fontsize=10)

[Link]('Population vs Temperature')
[Link]('Population')
[Link]('Temperature (°C)')
[Link](True, alpha=0.5)
plt.tight_layout()
[Link]()

# ---- 5. Print arrays correctly ----


print("Data WITHOUT last column (City, State, Population):")
print(data_without_last)
print("\nLast column (Temperature):")
print(last_column)
Output:
Data WITHOUT last column (City, State, Population):
[['Delhi' 'Delhi' 30000000]
['Mumbai' 'Maharashtra' 20000000]
['Bangalore' 'Karnataka' 13000000]
['Chennai' 'Tamil Nadu' 11000000]
['Kolkata' 'West Bengal' 15000000]]

Last column (Temperature):


[35. 32. 28. 33. 30.]

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 35 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

Explanation
Step 1: Import Libraries
import pandas as pd
import [Link] as plt
import io
 pandas (pd): helps read and organize tabular data.
 [Link] (plt): used for drawing plots and graphs.
 io: allows us to read data from a string instead of a file.

Step 2: Create Sample CSV Data


csv_content = """City, State, Population, Temperature
Delhi, Delhi, 30000000, 35”””
 This is sample CSV text stored in a string (like a file’s content).
 Each line represents a city’s data:
 City name
 State name
 Population
 Temperature

Step 3: Read Data into a DataFrame


cities_df = pd.read_csv([Link](csv_content))
 Converts the text data into a DataFrame (table format).
 Example DataFrame:
City State Population Temperature
Delhi Delhi 30000000 35
Mumbai Maharashtra 20000000 32
Bangalore Karnataka 13000000 28
Chennai Tamil Nadu 11000000 33
Kolkata West Bengal 15000000 30

Step 4: Convert DataFrame to Array


cities_array = cities_df.values
 Converts the table to a NumPy array, making it easier to extract columns by
index.
Step 5: Separate Columns
last_column = cities_array[:, -1]
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 36 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

data_without_last = cities_array[:, :-1]


 [:, -1] → takes the last column (Temperature).
 [:, :-1] → takes everything except the last column (City, State, Population).
Step 6: Extract Numeric Data
population = data_without_last[:, 2].astype(float)
temperature = last_column.astype(float)
 Converts Population and Temperature columns into numeric values (float).
 Needed for plotting on the graph.
Step 7: Create a Scatter Plot
[Link](figsize=(8,5))
[Link](population, temperature, color='blue', s=100, edgecolors='black')
 [Link]() → plots dots on a graph (X=Population, Y=Temperature).
 Blue circles represent each city.
Step 8: Add City Names
for i, city in enumerate(cities):
[Link](population[i] + 200000, temperature[i], city, fontsize=10)
 Loops through each city and adds its name next to its point.
 +200000 shifts the text slightly to the right.
Step 9: Label and Show the Plot
[Link]('Population vs Temperature')
[Link]('Population')
[Link]('Temperature (°C)')
[Link](True, alpha=0.5)
plt.tight_layout()
[Link]()
 Adds title, axis labels, and grid for readability.
 [Link]() displays the plot window.
Step 10: Print the Arrays
print("Data WITHOUT last column...")
print(data_without_last)
print("Last column...")
print(last_column)
 Displays both arrays clearly in the console output.

b. Design a calculator with the following buttons and functionalities like addition,
subtraction, multiplication, division and clear.

Solution:
import tkinter as tk

# Function to update the display


def update_display(value):
current_text = display_var.get()
if current_text == "0":
display_var.set(value)
else:
display_var.set(current_text + value)

# Function to clear the display


def clear_display():
display_var.set("0")

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 37 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

# Function to evaluate the expression and display the result


def calculate_result():
try:
result = eval(display_var.get())
display_var.set(result)
except Exception as e:
display_var.set("Error")

# Create the main window


parent = [Link]()
[Link]("Calculator")

# Create a variable to store the current display value


display_var = [Link]()
display_var.set("0")

# Create the display label


display_label = [Link](parent, textvariable=display_var, font=("Arial", 24), anchor="e",
bg="lightgray", padx=10, pady=10)
display_label.grid(row=0, column=0, columnspan=4)
# Define the button layout
button_layout = [
("7", 1, 0), ("8", 1, 1), ("9", 1, 2), ("/", 1, 3),
("4", 2, 0), ("5", 2, 1), ("6", 2, 2), ("*", 2, 3),
("1", 3, 0), ("2", 3, 1), ("3", 3, 2), ("-", 3, 3),
("0", 4, 0), (".", 4, 1), ("=", 4, 2), ("+", 4, 3),
]
# Create and place the buttons
for (text, row, col) in button_layout:
button = [Link](parent, text=text, padx=20, pady=20, font=("Arial", 18),
command=lambda t=text: update_display(t) if t != "=" else calculate_result())
[Link](row=row, column=col)

# Create a Clear button


clear_button = [Link](parent, text="C", padx=20, pady=20, font=("Arial", 18),
command=clear_display)
clear_button.grid(row=5, column=0, columnspan=3)

# Start the Tkinter event loop


[Link]()

OUTPUT:

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 38 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

FLOW CHART

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 39 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

[Link].
(SEM IV) THEORY EXAMINATION 2023-24
PYTHON PROGRAMMING (BCC-402)
Maximum Marks: 70
SECTION A
Q.1. Attempt all questions in brief.
a) Give difference between == and is operator.
Solution:
 == → checks value equality (same contents).
 is → checks object identity (are they the same object in memory).
 Use is for None checks: x is None (preferred).

# Example 1: lists
a = [1, 2]; b = [1, 2]; c = a
print(a == b) # True (same values)
print(a is b) # False (different objects)
print(a is c) # True (same object)
Output:
True
False
True
b) How we print the character of a given ASCII value in Python?
Solution:
In Python, chr(n) turns a number into the character with that code.
Example: chr(65) → 'A'.
# Print character from an ASCII code
n = int(input("Enter ASCII code (0-127): "))
print("Character:", chr(n))
Output:
Enter ASCII code (0-127): 65
Character: A
c) Can you use else with a for loop? If so, when is it executed?
Solution:
Yes. In Python you can use else with a for (and while).
The else block runs only if the loop finishes normally (no break) including
when the loop has zero iterations. It does not run if the loop hits a break.
Example-1: else runs (no break)

nums = [1, 2, 4]
for x in nums:
if x == 3:
print("found")
break
else:
print("not found") # runs because no break happened
Output:
not found
Example-2: else skipped (loop broke)
nums = [1, 2, 4]
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 40 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

for x in nums:
if x == 2:
print("found")
break
else:
print("not found") # skipped due to break
Output:
found
d) What will be the output of the following Python code?
l = [1, 0, 0, 2, 'hi', '', [ ]]
print(list(filter(bool, l)))
Solution:
[1, 2, 'hi']
filter(bool, l) keeps only truthy items. In Python, 0, '' (empty string), and [ ]
(empty list) are falsy, while 1, 2, and 'hi' are truthy, so they remain.
e) Describe the purpose of the split() method in string manipulation.

Solution:
split() breaks a string into a list of pieces using a separator.
 Default: splits on any whitespace and collapses multiple spaces.
 With sep: splits exactly on that substring.
Example:
# Split on spaces (default)
s = "apple banana cherry"
print([Link]()) # ['apple', 'banana', 'cherry']

# Split on a comma
csv = "red,green,blue"
print([Link](",")) # ['red', 'green', 'blue']
Output:
['apple', 'banana', 'cherry']
['red', 'green', 'blue']

f) What does the readline() function return when it reaches the end of a file?

Solution:
 readline() reads one line at a time from a file.
 It includes the newline character \n if present.
 When it reaches the end of the file (EOF), it returns an empty string "
", which is the signal to stop reading.
Example:
# Assume a file named "[Link]" with the following content:
# Hello
# World
# Python

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


line1 = [Link]() # Reads first line
line2 = [Link]() # Reads second line
line3 = [Link]() # Reads third line
line4 = [Link]() # Reaches EOF, returns empty string
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 41 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

print("Line 1:", [Link]()) # Output: Line 1: Hello


print("Line 2:", [Link]()) # Output: Line 2: World
print("Line 3:", [Link]()) # Output: Line 3: Python
print("Line 4:", [Link]()) # Output: Line 4: (empty, as EOF returns "")
Output:
Line 1: Hello
Line 2: World
Line 3: Python
Line 4:
g) Which function is used to create identity matrix in NumPy?
Solution:
[Link](n) and [Link](n) both create an identity matrix of size n×n.

[Link](n)
 Creates a square identity matrix of size n×n.
 Diagonal contains 1s, all other elements are 0.
 Simple and direct for standard identity matrices.

Example: [Link](n)
import numpy as np
x= [Link](3)
Print(x)
Output:
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
Explanation:
[Link](3) creates a 3×3 identity matrix with 1s on the main diagonal and 0s
elsewhere.

[Link](n, m=None, k=0)


 More flexible than [Link]().
 You can specify:
 n: number of rows
 m: number of columns (optional; defaults to n)
 k: diagonal offset
 k = 0: main diagonal
 k > 0: above main diagonal
 k < 0: below main diagonal

Example: np. eye(n)


import numpy as np
x = [Link](4)
print(x)
Output:
[[1. 0. 0. 0.]
[0. 1. 0. 0.]
[0. 0. 1. 0.]
[0. 0. 0. 1.]]

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 42 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

SECTION B
Q.2. Attempt any three of the following.
a) Explain the concept of dynamic typing in Python with an example.
Solution:
Dynamic Typing in Python
i. Dynamic typing means that the type of a variable is determined at
runtime, not in advance.
ii. You don’t need to declare the data type of a variable when creating it.
iii. You can even change the type of a variable later by assigning a
different kind of value.
iv. Python figures it out automatically based on the value assigned.
Example:
# Step 1: Assign an integer value
x = 10
print("Value of x:", x)
print(type(x)) # x is an integer

# Step 2: Assign a string value to the same variable


x = "Hello"
print("\nValue of x:", x)
print(type(x)) # now x is a string

# Step 3: Assign a float value


x = 12.5
print("\nValue of x:", x)
print(type(x)) # now x is a float
Output:
Value of x: 10
<class 'int'>

Value of x: Hello
<class 'str'>

Value of x: 12.5
<class 'float'>
Explanation:
 In Step 1, x is assigned an integer value (10), so Python treats it as an int.
 In Step 2, the same variable x is given a string ("Hello"), and its type
changes to str.
 In Step 3, x is assigned a float value (12.5), and Python automatically
updates the type to float.
Advantages of Dynamic Typing in Python
1. No need for type declarations:
 You don’t have to specify the data type of variables.
 This reduces the amount of code and makes programming simpler.
2. Faster development:
 Since Python automatically determines the data type, programs can
be written and tested more quickly.
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 43 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

3. Flexibility:
 A single variable can hold different types of data at different times.
 This makes the code more adaptable and easier to modify.
4. Ease of use:
 Dynamic typing allows beginners to focus on logic rather than
worrying about data types.
 It helps in writing concise and readable code.
5. Improved productivity:
 Developers spend less time declaring and managing data types,
leading to faster coding and debugging.

b) Explain how to define a list in Python. Write a Python program to remove


duplicates from a list and print the resulting list.
Solution:
A list in Python is an ordered collection of items that can hold elements of
different data types (like integers, strings, or even other lists).
Lists are mutable, meaning their contents can be changed (you can add, remove,
or modify elements).
You can define a list using square brackets [ ].
Example: list
# Defining a list
my_list = [10, 20, 30, 40, 50]
print(my_list)
Output:
[10, 20, 30, 40, 50]
Program to Remove Duplicates from a List

# Simple program to remove duplicates from a list


numbers = [1, 2, 2, 3, 4, 4, 5] # list with duplicates
numbers = list(set(numbers)) # remove duplicates
print(numbers) # print the result
Output:
[1, 2, 3, 4, 5]
Explanation:
 The list [1, 2, 2, 3, 4, 4, 5] has duplicate elements.
 The set() function removes duplicates automatically.
 Then, list(set(numbers)) changes it back into a list.
 The final list [1, 2, 3, 4, 5] contains only unique elements.
c) Explain the concept of functions in Python. Write a function that takes a
list of numbers and returns the sum of all the numbers in the list.
Solution:
 A function in Python is a block of reusable code that performs a specific task.
 Functions help to make programs modular, easier to read, and avoid
repetition.
 Functions are defined using the keyword def.
 They can take inputs (parameters) and can return outputs.
 You can call a function anywhere in your program after defining it.
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 44 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

Syntax:
def function_name(parameters):
# block of code
return value
Example
def greet():
print("Hello, welcome to Python!")

# Calling the function


greet()

Output:

Hello, welcome to Python!


Explanation:
 def → used to define a function.
 greet() → function name.
 The code inside the function runs only when you call it.
 This example prints a greeting message.

Program to Find the Sum of Numbers in a List


def add_numbers(nums):
return sum(nums) # adds all numbers in the list

numbers = [1, 2, 3, 4, 5]
print("Sum:", add_numbers(numbers))
Output:
Sum: 15
Explanation:
 The function add_numbers() takes a list as input.
 It uses the sum() function to add all numbers.
 The result (15) is printed.
d) Write a Python program to read a file named “[Link]” and count the
number of lines, words, and characters in the file.
Solution:
Program to Count Lines, Words, and Characters
# Open the file in read mode
file = open("[Link]", "r")

# Read the content of the file


text = [Link]()

# Count lines, words, and characters


lines = [Link]("\n")
words = [Link]()
chars = len(text)

# Display the results


print("Number of lines:", len(lines))
print("Number of words:", len(words))
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 45 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

print("Number of characters:", chars)

# Close the file


[Link]()
Output:
Number of lines: 3
Number of words: 13
Number of characters: 73
Explanation:
 Lines: There are 3 lines in the file.

 Words:
The total number of words =
Hello (1) + Rahul (2) + He (3) + is (4) + a (5) + Handsome (6) +
Person (7) + Rahul (8) + is (9) + a (10) + knowledgeable (11) +
person (12) → about 12–13 words depending on spacing.
Characters:
Each letter, space, and newline counts as one character, giving about
73 total.
e) Explain the basic usage of matplotlib for plotting graphs. Write a Python
program to plot a simple line graph showing the relationship between x =
and y =.
Solution:
Matplotlib is one of the most popular libraries in Python used for data
visualization.
It helps in creating different types of graphs, charts, and plots such as:
 Line graphs
 Bar charts
 Pie charts
 Scatter plots, and more
Matplotlib makes it easy to understand data visually.

Steps to Plot a Graph


1. Import the library: import [Link] as plt
pyplot is a sub-module in Matplotlib used for plotting graphs quickly
and easily.
2. Prepare the data
Define values for the x-axis and y-axis
For example, x = [1, 2, 3] and y = [2, 4, 6]).
3. Plot the data: [Link](x, y)
This draws a line connecting the data points.
4. Add labels and a title
[Link]("X values")
[Link]("Y values")
[Link]("Simple Line Graph")
5. Display the graph: [Link]()
This displays the graph window with your plot.

Program to plot Line Graph

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 46 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

# Import matplotlib
import [Link] as plt
# Data for plotting
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
# Plot the line graph
[Link](x, y)
# Add labels and title
[Link]("X values")
[Link]("Y values")
[Link]("Simple Line Graph")
# Display the graph
[Link]()

Output:

A simple straight line graph showing a linear relationship between x and y


Explanation:
 [Link](x, y) → draws a line connecting the points (x, y).
 [Link]() and [Link]() → label the axes.
 [Link]() → gives a title to the graph.
 [Link]() → displays the graph window.

SECTION C
Q.3. Attempt any one part of the following.
a) Explain for and while loops used in Python with appropriate example.
Solution:
Loops are used to repeat a block of code multiple times until a certain condition is
met.
Python provides two main types of loops:
3. for loop
4. while loop
3. for Loop:
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 47 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

 The for loop is used to iterate over a sequence (like a list, tuple, string, or
range of numbers).
 It automatically goes through each element in the sequence.

Syntax: for Loop


for variable in sequence:
# body of loop
Explanation:
 variable: Takes each value from the sequence one at a time.
 sequence: Can be a list, tuple, string, or range().

Figure: Flowchart of for Loop


# Example of for loop
for i in range(1, 6):
print("Number:", i)
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Explanation:
 range(1, 6) generates numbers from 1 to 5.
 The loop runs five times, printing each number.

4. while Loop:
 The while loop repeats a block of code as long as a given condition is
true.
 You must make sure the condition eventually becomes false to avoid an
infinite loop.

Syntax: while Loop


while condition:
# body of loop
Explanation:
 condition: A boolean expression (True or False).
 As long as this condition is True, the loop continues executing.

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 48 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

Figure: Flowchart of while Loop

# Example of while loop


i=1
while i <= 5:
print("Number:", i)
i=i+1
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Explanation:
 The loop starts with i = 1.
 It runs as long as i <= 5.
 Each time, it prints the value of i and increases it by 1.

Difference between for and while Loops


Feature for Loop while Loop
Use Used when number of iterations Used when number of iterations is
case is known unknown
Syntax for i in range(…): while condition:
Control Iterates through a sequence Runs until a condition becomes
false

b) Write a Python Program to find the LCM of two numbers.


Solution:
Logic of the Program
 LCM (Least Common Multiple) of two numbers is the smallest number
that is divisible by both numbers.
 The formula to find LCM using GCD (Greatest Common Divisor) is:

𝒂×𝒃
LCM(𝒂, 𝒃) =
GCD(𝒂, 𝒃)
Method-1: Using Formula
import math # to use gcd function
a = int(input("Enter first number: "))
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 49 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

b = int(input("Enter second number: "))

lcm = (a * b) // [Link](a, b)
print("The LCM of", a, "and", b, "is:", lcm)
Output:
Enter first number: 4
Enter second number: 6
The LCM of 4 and 6 is: 12
Explanation:
 The program takes two numbers as input.
 [Link](a, b) finds the greatest common divisor (GCD).
 (a * b) // [Link](a, b) gives the least common multiple (LCM).
 The result is then printed.

Method-2: Using Loop Method


# Program to find LCM of two numbers without using [Link]
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))

# Start from the greater number


greater = max(a, b)

while True:
if (greater % a == 0) and (greater % b == 0):
lcm = greater
break
greater += 1
print("The LCM of", a, "and", b, "is:", lcm)
Output:
Enter first number: 4
Enter second number: 6
The LCM of 4 and 6 is: 12
Explanation:
 The loop starts from the larger number (max(a, b)).
 It keeps checking if the number is divisible by both a and b.
 When it finds such a number, that number is the LCM, and the loop
stops.
Program Logic:
Find the greater number: greater = max(a, b)
 The LCM can never be smaller than the larger of the two numbers.
For example, if numbers are 4 and 6, the LCM must be at least 6 or
greater. Find the greater number:
 So, we start checking from the greater number.

Loop to find the LCM:


while True:
if (greater % a == 0) and (greater % b == 0):
lcm = greater
break
greater += 1

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 50 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

a = 4, b = 6
greater = 6
1. Check if 6 % 4 == 0 → No
2. Increase greater → 7, 8, 9, 10, 11 → No
3. When greater = 12:
12 % 4 == 0 and 12 % 6 == 0
Found LCM = 12
Exit loop

Q.4. Attempt any one part of the following:


a) Write a program takes two strings and checks common letters in both the
strings.
Enter first string: Hari
Enter second string: Hale
The common letters are:
H
a

Solution:
Checking Common Letters Between Two Strings
When we convert a string to a set, it stores only unique letters.
Then, we can find the common letters between two sets using either:
1. Intersection operator (&)
2. Intersection method (.intersection())
Both methods do the same thing they return the common elements between two
sets.

Method-1: Using Intersection operator (&)


# Program to find common letters in two strings

# Take input from the user


str1 = input("Enter first string: ")
str2 = input("Enter second string: ")

# Convert both strings to sets (to remove duplicates)


set1 = set(str1)
set2 = set(str2)

# Find common letters using intersection


common = set1 & set2

# Display the result


print("The common letters are:")
for letter in common:
print(letter)
Output:
Enter first string: Hari
Enter second string: Hale
The common letters are:
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 51 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

H
A
Explanation:
1. set(str1) and set(str2) convert each string into a set of unique
characters.
 Example: "Hari" → {'H', 'a', 'r', 'i'}
 "Hale" → {'H', 'a', 'l', 'e'}
2. set1 & set2 finds the intersection — letters present in both sets.
 Common letters → {'H', 'a'}
3. Finally, the program prints each common letter on a new line.

Method-2: Using Intersection method (.intersection())


# Program to find common letters in two strings

# Take input from the user


str1 = input("Enter first string: ")
str2 = input("Enter second string: ")

# Convert both strings to sets (to remove duplicate letters)


set1 = set(str1)
set2 = set(str2)

# Find common letters using intersection()


common = [Link](set2)

# Display the result


print("The common letters are:")
for letter in common:
print(letter)
Output:
Enter first string: Hari
Enter second string: Hale
The common letters are:
H
A
Explanation:
1. set(str1) and set(str2) convert each string into sets of unique
characters.
 "Hari" → {'H', 'a', 'r', 'i'}
 "Hale" → {'H', 'a', 'l', 'e'}
2. [Link](set2) finds letters common to both sets.
 Result → {'H', 'a'}
3. The loop prints each common letter on a new line.

b) Write a Python Program to find the sum all the items in a dictionary.
For example if d= {'A':100,'B':540,'C':239} then output should be 879.

Solution:

Method-1: Using sum() Function


# Program to find the sum of all items in a dictionary
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 52 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

d = {'A': 100, 'B': 540, 'C': 239}

total = sum([Link]())
print("Sum of all items:", total)
Output:
Sum of all items: 879
Explanation:
 [Link]() → gets all the values [100, 540, 239]
 sum() → adds them all up → 100 + 540 + 239 = 879

Method-2: Using a for Loop


# Program to find the sum of all items in a dictionary
d = {'A': 100, 'B': 540, 'C': 239}
total = 0
for value in [Link]():
total = total + value
print("Sum of all items:", total)
Output:
Sum of all items: 879
Explanation:
 The loop goes through each value in the dictionary.
 Each value is added to total one by one.
 Finally, the total sum is printed.

Method-3: Using a for loop with keys


# Program to find the sum of all items in a dictionary using keys

d = {'A': 100, 'B': 540, 'C': 239}


total = 0
for key in d:
total = total + d[key]
print("Sum of all items:", total)
Output:
Sum of all items: 879
Explanation:
 The loop goes through each key ('A', 'B', 'C') in the dictionary.
 For each key, it gets the value (d[key]) and adds it to total.

Method-4: Using a List and sum( )


# Program to find the sum of all items in a dictionary using a list

d = {'A': 100, 'B': 540, 'C': 239}


values_list = list([Link]()) # Convert dictionary values into a list
total = sum(values_list)
print("Sum of all items:", total)
Output:
Sum of all items: 879
Explanation:
 [Link]() gets all the dictionary values.
 list([Link]()) converts them into a list like [100, 540, 239].
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 53 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

 sum() adds them up and gives the total.

Q.5. Attempt any one part of the following:


a) Explain the concept of a set in Python and its characteristics. How
elements are added or removed in set.
Solution:
 A set is an unordered, unindexed collection of unique elements in
Python.
 It’s mainly used when you want to store multiple items but avoid
duplicates. For example, unique names, IDs, or numbers.
Two Ways to Create a Set in Python:
1. Using curly braces { }
2. Using the set() constructor
1. Using Curly Braces { }
 Enclose elements separated by commas.
 Automatically removes duplicates.
Example:
fruits = {"apple", "banana", "cherry", "banana"}
print(fruits)
Output:
{'apple', 'banana', 'cherry'}
Duplicates are automatically removed!
Note: { } creates an empty dictionary, not a set.
2. Using the set() Constructor
 Useful when converting from other data types (like lists, tuples).
 Useful for removing duplicates from sequences.

Example:
numbers = set([1, 2, 3, 2])
print(numbers) # Output: {1, 2, 3}
Output:
{1, 2, 3}
Duplicates are automatically removed!

Characteristics of Sets
1. Unordered:
The elements have no fixed order (their positions may change each
time you print the set).
2. Unindexed:
You cannot access elements by index like lists (e.g., my_set[0] will
cause an error).
3. Unique elements:
A set automatically removes duplicates.
4. Mutable:
You can add or remove elements after creating a set.
5. Heterogeneous elements allowed:
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 54 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

A set can contain elements of different data types (e.g., integers,


strings, floats).
6. Cannot contain mutable types:
Lists or dictionaries cannot be elements of a set (since they are
changeable).

Adding Elements to a Set:


 Use add() to insert a single element.
 Use update() to add multiple elements.

Example:
s = {1, 2}
[Link](3) # Adds a single element
[Link]([4, 5]) # Adds multiple elements from an iterable
print(s)

Output:
{1, 2, 3, 4, 5}
Removing Elements from a Set:
 remove(x): Removes x; raises error if not found.
 discard(x): Removes x; no error if not found.
 pop(): Removes and returns a random element.
 clear(): Empties the set.

Example:
# Initial set
s = {1, 2, 3, 4, 5}
print("Original set:", s)

# Remove element 2
[Link](2)
print("After remove(2):", s)

# Discard element 10 (not present)


[Link](10)
print("After discard(10):", s)

# Pop a random element


removed = [Link]()
print("After pop():", s)
print("Popped element:", removed)

# Clear the set


[Link]()
print("After clear():", s)

Output:
Original set: {1, 2, 3, 4, 5}
After remove(2): {1, 3, 4, 5}
After discard(10): {1, 3, 4, 5}
After pop(): {3, 4, 5}
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 55 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

Popped element: 1
After clear(): set()

b) Explain how lambda functions can be used within a list comprehension.


Write a Python program that uses a lambda function within a list
comprehension to convert a list of temperatures in Celsius to Fahrenheit.
Solution:
 A lambda function is a small, anonymous (nameless) function in Python.
 It is mainly used for short, simple calculations instead of defining a full
function using def.
Syntax:
lambda arguments: expression
lambda → keyword used to define the function
arguments → input values
expression → operation to perform and return

Example:
square = lambda x: x * x
print(square(5))
Output:
25
Explanation:
 lambda x: x * x creates a function that squares the input x.
 square(5) calls it and returns 25.

Lambda Function inside a List Comprehension


Using a lambda function inside a list comprehension allows you to:
 Apply a quick transformation to each item in a list
 Without writing a separate function

Syntax:
[ (lambda x: expression)(item) for item in iterable ]
 lambda x: expression defines the transformation.
 (item) passes each element to the lambda.
 The result is collected into a new list.

Program that uses a lambda function within a list comprehension to


convert a list of temperatures in Celsius to Fahrenheit.
celsius = [0, 10, 20, 30, 40]

# Lambda function inside list comprehension


fahrenheit = [(lambda c: (c * 9/5) + 32)(c) for c in celsius]

print("Celsius:", celsius)
print("Fahrenheit:", fahrenheit)
Output:
Celsius: [0, 10, 20, 30, 40]
Fahrenheit: [32.0, 50.0, 68.0, 86.0, 104.0]
Explanation:
 (lambda c: (c * 9/5) + 32) converts a single Celsius value to Fahrenheit.

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 56 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

 [ ... for c in celsius ] applies the lambda to each value in the list.
 The result is a new list of converted Fahrenheit values.
Note:
The logic to convert Celsius to Fahrenheit is:
𝟗
 Formula: Fahrenheit = (Celsius × 𝟓) + 𝟑𝟐

Explanation:
 Multiply the Celsius temperature by 9/5 (or 1.8) this converts it from
the Celsius scale to the Fahrenheit scale.
 Add 32, because 0°C corresponds to 32°F.

Q.6. Attempt any one part of the following:


a) Explain different file opening modes also write a Python Program to read
a file and capitalize the first letter of every word in the file.
Solution:
Python provides different file opening modes that define how a file will be
accessed when using the open() function.

File opening modes:


Python provides different file opening modes that define how a file will be accessed when
using the open() function.
Mode Purpose
'r' Read mode: Opens a file for reading (default). Gives an error if the file
doesn’t exist.
'w' Write mode: Opens a file for writing. Creates a new file or overwrites
existing content.
'a' Append mode: Opens a file for writing but adds data at the end without
deleting old content.

Read and Write Combination Modes:


These modes allow you to both read and write to a file at the same time.
Mode Purpose
'r+' Opens the file for both reading and writing. The file must already
exist; otherwise, an error occurs.
'w+' Opens the file for reading and writing, but it creates a new file or
overwrites the existing one. Use carefully as existing data will be lost.
'a+' Opens the file for reading and appending. If the file doesn’t exist, it is
created automatically. New data is added at the end of the file without
erasing previous content.

Binary Modes
Used for non-text files like images, audio, or videos:
Mode Purpose
'rb' Opens a binary file for reading. Used to read non-text data like images
or audio files.
'wb' Opens a binary file for writing. Creates a new file or overwrites an
existing one.
'ab' Opens a binary file for appending. Adds new binary data at the end of
the file without deleting old data.

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 57 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

Python Program to read a file and capitalize the first letter of every word in
the file.
Content of [Link]
rahul is faculty in ece department, jss academy of technical education, noida
uttar pradesh
india

# Program to read a file and capitalize the first letter of every word

# Open the file in read mode


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

# Read the content of the file


content = [Link]()

# Capitalize the first letter of every word


capitalized_content = [Link]()

# Close the file


[Link]()

# Display the results


print("Original Content:\n", content)
print("\nCapitalized Content:\n", capitalized_content)
Output:

Original Content:
rahul is faculty in ece department, jss academy of technical education, noida
uttar pradesh
india

Capitalized Content:
Rahul Is Faculty In Ece Department, Jss Academy Of Technical Education, Noida
Uttar Pradesh
India
Explanation:
 The program opens [Link] in read mode.
 It reads all text and uses the .title() function to capitalize the first letter of every
word.
 Both the original and modified contents are printed.

b) What do you mean by generators in Python? How it is created in Python?

Solution:
Generators in Python:
 A generator in Python is a special type of function that produces a sequence of
values one at a time instead of returning them all at once.

 Unlike normal functions that use the return statement and stop after sending
one value, a generator uses the yield statement, which pauses the function and
resumes from where it left off the next time it’s called.

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 58 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

 This means the values are generated on demand, not stored in memory all at
once, making generators memory-efficient and faster when working with large
data or continuous data streams.
 In simple terms, a generator helps you iterate through data step by step, saving
memory and improving performance.

Generators Creations:
Generators in Python can be created in two main ways:
1. Using yield in a Function
2. Using Generator Expressions

Example: Using yield in a Function


# Generator using yield

def count_up_to(n):
for i in range(1, n + 1):
yield i # yields one value at a time

# Using the generator


for num in count_up_to(5):
print(num)
Output:
1
2
3
4
5
Explanation:
 The function count_up_to() uses the yield keyword instead of return.
 Each time the loop runs, it yields one number and then pauses.
 When the loop continues, the function resumes from where it
stopped.
 This allows values to be generated one by one, not all at once.

Example: Using Generator Expressions


# Generator using generator expression

squares = (x * x for x in range(1, 6))

for val in squares:


print(val)
Output:
1
4
9
16
25
Explanation:
 (x * x for x in range(1, 6)) is a generator expression.
 It looks like a list comprehension but uses parentheses () instead of
brackets [ ].
 The values are generated one at a time when needed, not stored in
memory.
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 59 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

Note:
Difference between yield in function and Generator expression
Feature yield in Function Generator Expression
Syntax Multi-line (with def) One-line (with ())
Use Case Complex or reusable logic Simple and short operations
Memory Use Efficient Efficient
Pause/Resume Yes Automatically handled
Readability Better for large logic Better for short tasks

Q.7. Attempt any one part of the following:


a) Describe how to generate random numbers using NumPy. Write a Python program
to create an array of 5 random integers between 10 and 50.

Solution:

Generating Random Numbers Using NumPy


 NumPy is a powerful Python library used for scientific and numerical
computations.
 It provides a special module called [Link] which can be used to generate
random numbers efficiently
 These random numbers can be integers, floating-point numbers, or values from
different probability distributions.
 Random numbers are often used in data science, simulations, games, and
machine learning.

Function & Example Description

[Link](low, high, size) Generates random integers between


Example: [Link](1, 10, 5) low (inclusive) and high (exclusive)
[Link](size) Generates random floating-point
Example: [Link](5) numbers between 0 and 1

[Link](list) Randomly selects elements from a


Example: [Link]([1,2,3]) given list or array
[Link](value) Sets the seed to reproduce the same
Example: [Link](10) random values each time

[Link]( ) Syntax: [Link](low, high, size)


Parameters:
 low → Lower bound (inclusive)
 high → Upper bound (exclusive)
 size → Number of random integers to generate

Example:
[Link](10, 51, size=5) generates 5 random integers between 10
and 50 (since upper limit 51 is exclusive).

Python program to create an array of 5 random integers between 10 and 50.


import numpy as np

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 60 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

# Generate an array of 5 random integers between 10 and 50


random_array = [Link](10, 51, size=5)

# Display the result


print("Random integers between 10 and 50:", random_array)
Output:
Random integers between 10 and 50: [23 47 12 35 18]

Note: Output will vary each time you run the program.
Explanation:
1. Import NumPy:
The statement import numpy as np imports the NumPy library.
2. Generate Random Numbers:
[Link](10, 51, size=5) creates 5 random integers between
10 and 50.
3. Print Result:
The array of random numbers is printed using the print() function.

Advantages of Using NumPy for Random Numbers


1. Fast and Efficient:
Generates large arrays of random numbers quickly.
2. Memory Efficient:
Handles big data arrays efficiently without using loops.
3. Supports Multiple Distributions:
Can generate random data for uniform, normal, and other distributions.
4. Reproducibility:
Using [Link]() ensures the same output each time.
5. Widely Used in Real Projects:
Common in data analysis, simulations, and AI model training.
b) Explain the concept of DataFrame in pandas. Write a Python program to
create a DataFrame from a dictionary and print it.

Solution:

 A DataFrame is one of the most important data structures provided by the


Pandas library in Python.
 It is used to store and manage data in tabular form (rows and columns)
similar to a spreadsheet or SQL table.
 Each column in a DataFrame can contain data of different types such as
integers, floats, strings, or even dates.

Key Features of a DataFrame:


Feature Description
2-Dimensional Data is organized in rows and columns (like a table).
Rows and columns have labels (called index and
Labeled Axes
column names).
Heterogeneous
Each column can have different data types.
Data
Size Mutable You can add or delete columns and rows.
Data Alignment Handles missing data gracefully.

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 61 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

Can be created from dictionaries, lists, CSV files, Excel


Data Sources
sheets, etc.
Creating a DataFrame:
You can create a DataFrame in many ways:
 From a dictionary
 From a list of lists or tuples
 From external data files (CSV, Excel, SQL, etc.)

Example-1: Python program to create DataFrame from a Dictionary


import pandas as pd

# Create a dictionary of data


data = {
'Name': ['Rahul', 'Mayank'],
'Age': [35, 42],
'Department': ['ECE', 'CSE'],
'Institute': ['JSSATE, Noida.', 'JSS University, Noida.']
}

# Create DataFrame from dictionary


df = [Link](data)

# Display the DataFrame


print("DataFrame created from dictionary:")
print(df)
Output:
DataFrame created from dictionary:
Name Age Department Institute
0 Rahul 35 ECE JSSATE, Noida.
1 Mayank 42 CSE JSS University, Noida.
Explanation:
 The data dictionary contains column names as keys and lists as values.
 The [Link](data) function converts this dictionary into a
DataFrame.
 Each list becomes a column, and each element of the list becomes a row
entry.
 Finally, print(df) displays the table neatly.

OR

Example-2: Python program to create DataFrame from a Dictionary


import pandas as pd

# Create a dictionary of data


data = {
'Name': ['Rahul', 'Arun', 'Mayank', 'Neha'],
'Age': [35, 43, 42, 25],
'Department': ['ECE', 'ECE', 'CSE', 'CSE'],
'Institute': ['JSSATE, Noida.', 'JSSATE, Noida.', 'JSS University, Noida.', 'GL
Bajaj.']
}

# Create DataFrame from dictionary

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 62 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

df = [Link](data)

# Display the DataFrame


print("DataFrame created from dictionary:")
print(df)
Output:
DataFrame created from dictionary:
Name Age Department Institute
0 Rahul 35 ECE JSSATE, Noida.
1 Arun 43 ECE JSSATE, Noida.
2 Mayank 42 CSE JSS University, Noida.
3 Neha 25 CSE GL Bajaj.
Explanation:
 The dictionary data contains four columns Name, Age, Department, and
Institute.
 [Link](data) converts this dictionary into a tabular DataFrame.
 Each key becomes a column name, and each list of values becomes a
column’s data.
 The DataFrame is displayed neatly using print(df).

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 63 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

[Link].
(SEM III) THEORY EXAMINATION 2024-25
PYTHON PROGRAMMING (BCC-302)
Maximum Marks: 70
SECTION A

Q.1. Attempt all questions in brief. (2M X 7 =14M)

a. State how to handle exceptions in Python? Provide a simple example.

Solution:

 An exception is an error that occurs during program execution. Common


examples include:
 Division by zero
 Accessing an invalid index
 Opening a missing file
 Entering incorrect data type
 If not handled, the program terminates abruptly, potentially losing progress
or confusing the user.

Why Handle Exceptions?


 To prevent program crashes
 To guide users with meaningful messages
 To ensure smooth execution
 To perform cleanup tasks (e.g., closing files or releasing resources)

Flow diagram:

Figure 1: Flow diagram of how to handle exceptions in Python


This diagram shows how Python handles exceptions using try, except, and finally step
by step:

1. try block
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 64 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

 First, Python runs the code inside the try block.


 This is where we put code that might cause an error.

2. Error?
 Python checks: Did an error happen in the try block?
 If No error:
 Python skips the except block.
 It goes directly to the finally block (if it exists).

 If Yes (error occurs):


 Python jumps to the except block.

3. except block
 This block runs only when an error happens in the try block.
 Here, we write code to handle the error safely.

4. finally block
 The finally block always runs.
 It doesn’t matter if there was an error or not.
 Useful for cleanup tasks (like closing files, releasing resources).

Note:
1. try → run code.
2. If error → go to except.
3. If no error → skip except.
4. After that, finally runs in both cases.

Detailed Explanation of how to handle exceptions in Python

General Syntax
try:
# Code that might cause an error
except <ExceptionType>:
# Code to handle the error
finally:
# (Optional) Code that always runs

Example
try:
num1 = int(input("Enter numerator: "))
num2 = int(input("Enter denominator: "))
result = num1 / num2
print("Result:", result)

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

except ValueError:
print("Error: Invalid input! Please enter numbers only.")

finally:
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 65 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

print("Program execution completed.")


Output: Case 1: Valid Input
Enter numerator: 10
Enter denominator: 2
Result: 5.0
Program execution completed.
Output: Case 2: Division by Zero
Enter numerator: 10
Enter denominator: 0
Error: Cannot divide by zero!
Program execution completed.
Output: Case 3: Wrong Input
Enter numerator: hello
Error: Invalid input! Please enter numbers only.
Program execution completed.

b. What will be the output of the following Python code?

def compute(x):
return [i**2 for i in x if i%2==0]
print(compute([1, 2, 3, 4, 5]))

Solution:
 The function compute(x) uses list comprehension.
 It takes each element i from list x.
 if i % 2 == 0 → Only even numbers are considered.
 i**2 → Squares each even number.

Step-by-step:
Input list: [1, 2, 3, 4, 5]
 1 → odd → ignored
 2 → even → 2**2 = 4
 3 → odd → ignored
 4 → even → 4**2 = 16
 5 → odd → ignored

Output: [4, 16]

c. Explain floor division with an example.

Solution:
 Floor division in Python means dividing two numbers and rounding down the
result to the nearest whole number (also called integer division).
 It is done using the // operator.

Example of floor division


# Example of floor division
a = 17
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 66 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

b=5

result = a // b
print(result)
Output:
3
Explanation:
 Normal division 17 / 5 = 3.4
 Floor division 17 // 5 = 3 (rounds down to the nearest integer).

d. Describe the purpose of the ‘with’ statement in file handling?

Solution:
The with statement in Python is used to open files, perform operations, and
automatically close them after use, making file handling simpler, safer, and error-
free.

Example Without with:


file = open("[Link]", "r")
content = [Link]()
[Link]()
Here, you must remember to close the file manually using [Link](). If you forget, the
file might stay open which can cause errors or data loss.

Example using with Statement (Better Way):


with open("[Link]", "r") as file:
content = [Link]()
print(content)
The file automatically closes after the block of code ends. You don’t need to write
[Link]().

e. Briefly describe the use of lambda functions in Python.

Solution:
 A lambda function is a small, anonymous (nameless) function in Python defined
using the lambda keyword.
 It is used for short, one-line functions that are not reused elsewhere.
A lambda function can take any number of arguments but only one expression.

 It is mainly used for short, simple operations such as quick calculations or with
functions like map(), filter(), and reduce().

Syntax:
lambda arguments : expression

Example 1 – Basic Use


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

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 67 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

[Link]()
Output:
25

Example 2 – With Two Arguments


add = lambda a, b: a + b
print(add(4, 3))
Output:
7

Example 3 – Used with filter()


numbers = [1, 2, 3, 4, 5, 6]
even = list(filter(lambda x: x % 2 == 0, numbers))
print(even)
Output:
[2, 4, 6]

f. Demonstrate how to assign a single value to a tuple.


Solution:
 In Python, if you want to assign a single value to a tuple, you must include
a comma after the value.
 Otherwise, Python will treat it as just a normal variable (not a tuple).

Example of floor division


# Single value tuple
t1 = (10,) # tuple with one element
print(t1)
print(type(t1))

# Without comma
t2 = (10) # not a tuple, just an integer
print(t2)
print(type(t2))
Output:
(10,)
<class 'tuple'>
10
<class 'int'>
Explanation: The comma is mandatory for a single-value tuple.

g. Explain why numpy is used instead of python arrays for mathematical


calculations?

Solution:
Python List / Array:
 A list (or built-in array using the array module) is a general-purpose
container in Python that can hold elements of different data types (e.g.,
integers, strings, floats).
 It is not optimized for mathematical or numerical operations.

NumPy Array:
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 68 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

 A NumPy array is a special type of box made only for numbers.


 It is fast, powerful, and uses less memory, best for mathematics, statistics,
and data analysis.

Example: Python List (Normal Addition)


a = [1, 2, 3]
b = [4, 5, 6]

# Adding two lists concatenates them


print(a + b)
Output:
[1, 2, 3, 4, 5, 6]

Example: NumPy Array (Mathematical Addition)


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

# Adding two arrays performs element-wise addition


print(a + b)
Output:
[5 7 9]

Advantages of NumPy over Python Lists:


Feature NumPy Array Python List / Array
Much faster (implemented in
Speed Slower
C)
Memory Consumes less memory Uses more memory
Heterogeneous (mixed types
Data Type Homogeneous (all same type)
allowed)
Mathematical Needs loops or list
Direct element-wise support
Operations comprehension
Rich set of mathematical,
Functions statistical, and linear algebra Limited built-in operations
functions
Multi-
Mostly 1D lists (no native matrix
dimensional Supports 1D, 2D, 3D... arrays
support)
Support

SECTION B

Q.2. Attempt any three of the following (7M X 3 =21M)

a. Design a basic calculator in Python that supports addition, subtraction,


multiplication, division.

Solution:
Program: Method-1 (Without Using Function)
# Very Simple Calculator

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 69 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

num1 = float(input("Enter first number: "))


op = input("Enter operator (+, -, *, /): ")
num2 = float(input("Enter second number: "))

if op == '+':
print("Result =", num1 + num2)
elif op == '-':
print("Result =", num1 - num2)
elif op == '*':
print("Result =", num1 * num2)
elif op == '/':
if num2 != 0:
print("Result =", num1 / num2)
else:
print("Error: Cannot divide by zero")
else:
print("Invalid operator")
OUTPUT: Case 1: Multiplication OUTPUT: Case 2: Division by zero
Enter first number: 6 Enter first number: 8
Enter operator (+, -, *, /): * Enter operator (+, -, *, /): /
Enter second number: 4 Enter second number: 0
Result = 24.0 Error: Cannot divide by zero

Program: Method-1 (Using Function)


# Simple Calculator Program

def calculator():
print("Basic Calculator")
print("Operations: + - * /")

# Taking input from user


num1 = float(input("Enter first number: "))
operator = input("Enter operator (+, -, *, /): ")
num2 = float(input("Enter second number: "))

# Performing operation
if operator == '+':
print("Result:", num1 + num2)
elif operator == '-':
print("Result:", num1 - num2)
elif operator == '*':
print("Result:", num1 * num2)
elif operator == '/':
if num2 != 0: # to avoid division by zero error
print("Result:", num1 / num2)
else:
print("Error: Division by zero is not allowed.")
else:
print("Invalid operator")

# Call the calculator function


AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 70 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

calculator()
OUTPUT:
Basic Calculator
Operations: + - * /
Enter first number: 10
Enter operator (+, -, *, /): *
Enter second number: 5
Result: 50.0

b. Define Membership and Identity Operators.


Given:
a=3
b=3
Distinguish between: (a is b) and (a == b) ?

Solution:
Membership and Identity Operators in Python:
 Python provides special operators to test relationships between variables,
values, or objects.
 Two such important types are Membership Operators and Identity Operators.

Membership Operators
Membership operators are used to check whether a particular value exists in a given
sequence such as a list, tuple, string, set, or dictionary.

Operators:
 in → Returns True if the value is found in the sequence.
 not in → Returns True if the value is not found in the sequence.

Purpose: To test the presence or absence of an element in a collection.

Syntax:
value in sequence
value not in sequence

Example: Membership Operator


fruits = ["apple", "banana", "mango"]

print("apple" in fruits) # True → 'apple' is present in the list


print("grapes" not in fruits) # True → 'grapes' is not present
print("banana" not in fruits) # False → because 'banana' exists
Output:
True
True
False
Explanation:
The operator in checks inside the list fruits to see if the given element is present.
If found, it returns True; otherwise, False.

Identity Operators
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 71 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

Identity operators are used to compare the memory locations (identities) of two
objects to check if they are actually the same object in memory.

Operators:
 is → Returns True if both variables point to the same memory location.
 is not → Returns True if they do not point to the same memory location.

Syntax:
object1 is object2
object1 is not object2

Example: Identity Operator


a=3
b=3

print(a == b) # True → Values are equal


print(a is b) # True → Same memory location (small integers are interned)
Output:
True
True
Explanation:
In Python, small integers (-5 to 256) are cached (interned) to improve
performance.
Hence, both a and b refer to the same object in memory, so both comparisons return
True.

 a == b → Compares values.
 3 == 3 → True

 a is b → Compares memory addresses (object identity).


 In Python, small integers (from -5 to 256) are stored in the same memory
location (called interning).
 So a and b point to the same object → True.

However, for larger numbers or objects, this may differ and is shown in below
example

Example: Larger numbers or objects


x = 300
y = 300
print(x == y) # True → values same
print(x is y) # False → different memory locations
Output:
True
False

Difference Between a is b and a == b


Comparison Meaning Checks Example Result
Equality
a == b Compares values 3 == 3 True
Operator

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 72 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

Identity Compares object identity True (for small


a is b a is b
Operator / memory location integers)

Notes
1. == → compares values.
2. is → compares memory addresses (object identity).
3. in / not in → used with sequences like list, tuple, string, set, dictionary, etc.
4. Python automatically reuses memory for small integers and strings to save
space (called interning).

c. Write a Python function to count the frequency of each character in a given string
and return the output in a dictionary. Example: char_frequency("HELLO") returns
{'H':1, 'E':1, 'L':2, 'O':1}

Solution:
Method-1: dictionary counting using if-else
def char_frequency(s):
freq = {} # empty dictionary to store character counts

for ch in s:
if ch in freq:
freq[ch] += 1 # increase count if character already exists
else:
freq[ch] = 1 # add character with count 1

return freq

# Example
print(char_frequency("HELLO"))
Output:
{'H': 1, 'E': 1, 'L': 2, 'O': 1}
Explanation:
1. An empty dictionary freq = {} is created to store characters as keys and their
counts as values.
2. The for loop iterates through each character ch in the string s.
3. If ch already exists in freq, its value (count) is incremented by 1.
4. If ch does not exist in freq, it is added with an initial count of 1.
5. Finally, the dictionary freq is returned containing all character frequencies.

Example with "HELLO":


 Start: { }
 Read "H" → {'H': 1}
 Read "E" → {'H': 1, 'E': 1}
 Read "L" → {'H': 1, 'E': 1, 'L': 1}
 Read "L" → {'H': 1, 'E': 1, 'L': 2}
 Read "O" → {'H': 1, 'E': 1, 'L': 2, 'O': 1}

Method-2: Using get() method


def char_frequency(s):
freq = {}
for ch in s:
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 73 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

freq[ch] = [Link](ch, 0) + 1
return freq

print(char_frequency("HELLO"))
Output:
{'H': 1, 'E': 1, 'L': 2, 'O': 1}
Explanation:
 This method automatically handles missing keys and is slightly shorter, but the
logic is the same.
 Handles both uppercase and lowercase inputs uniformly.

Method-3: Using [Link] (Counter-based approach)


from collections import Counter

def char_frequency(s):
return dict(Counter(s))

print(char_frequency("HELLO"))
Output:
{'H': 1, 'E': 1, 'L': 2, 'O': 1}
Explanation
1. Importing Counter:
 Counter is a class from Python’s collections module.
 It automatically counts how many times each element appears in a
given sequence (like a string or list).
2. Function Definition:
 The function char_frequency(s) takes a string s as input.
 Inside the function, Counter(s) creates a dictionary-like object where:
 Keys → characters from the string
 Values → number of times each character appears
3. Conversion to Dictionary:
 dict(Counter(s)) converts the Counter object into a regular Python
dictionary.
4. Return Value:
 The function returns this dictionary containing character frequencies.
5. Example Execution:
 Input string: "HELLO"
 Step-by-step counting:
 'H' → 1
 'E' → 1
 'L' → 2
 'O' → 1

d. Write a program to reverse the contents of a file character by character,


separating each character with a comma.

Solution:
Method-1: Simple Read–Reverse–Join (same-file overwrite)
Initial content of [Link]
Hello Rahul
# Step 1: Open and read the file
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 74 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

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


text = [Link]() # text = "Hello Rahul"
[Link]()

# Step 2: Reverse the text and add commas


reversed_text = text[::-1] # reversed_text = "luhaR olleH"
result = ",".join(reversed_text) # result = "l,u,h,a,R, ,o,l,l,e,H"

# Step 3: Overwrite the same file with the result


file = open("[Link]", "w")
[Link](result)
[Link]()
Output:
l,u,h,a,R, ,o,l,l,e,H
Explanation:
1. Open the file for reading
file = open("[Link]", "r")
 Opens the file named [Link] in read mode.
2. Read the content
text = [Link]()
 Reads all the text from the file and stores it in the variable text.
 Example: if file has Hello Rahul, then text = "Hello Rahul".
3. Close the file
[Link]()
 Always close the file after reading to free up system resources.
4. Reverse the text
reversed_text = text[::-1]
 [::-1] reverses the string.
 "Hello Rahul" becomes "luhaR olleH".
5. Add commas between characters
result = ",".join(reversed_text)
 join() puts a comma between each character.
 "luhaR olleH" becomes "l,u,h,a,R, ,o,l,l,e,H".
6. Open the file again for writing
file = open("[Link]", "w")
 Opens the same file in write mode, which overwrites the old content.
7. Write the result into the file
[Link](result)
 Writes the new reversed, comma-separated text back into the file.
8. Close the file
[Link]()
 Saves the changes and closes the file.

Method-2: Using "utf-8" - Unicode Transformation Format (8-bit).


Initial content of [Link]
Hello Rahul

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 75 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

# Read -> reverse -> join -> write (same file)


with open("[Link]", "r", encoding="utf-8") as f:
s = [Link]()

with open("[Link]", "w", encoding="utf-8") as f:


[Link](",".join(s[::-1]))
Output:
l,u,h,a,R, ,o,l,l,e,H
Explanation:
1. with open("[Link]", "r") as f:
 Opens the file [Link] in read mode (r).
 The with statement automatically closes the file after reading (no
need for close()).
2. s = [Link]()
 Reads the entire text from the file and stores it in the variable s.
 Example: If the file has Hello Rahul, then s = "Hello Rahul".
3. s[::-1]
 Reverses the string using slicing.
 "Hello Rahul" becomes "luhaR olleH".
4. ",".join(s[::-1])
 Joins each character of the reversed string with a comma.
 "luhaR olleH" becomes "l,u,h,a,R, ,o,l,l,e,H".
5. Second with open("[Link]", "w") as f:
 Opens the same file again in write mode (w).
 This overwrites the old content in the file.
6. [Link](",".join(s[::-1]))
 Writes the reversed,
comma-separated text
back into the file.

Note:
What is encoding="utf-8"?
 Encoding means how characters (letters, symbols, numbers) are stored
as bytes in a computer file.
 "utf-8" stands for Unicode Transformation Format (8-bit).
 It is the most common and standard encoding used worldwide because
it supports:
 All English characters
 Special symbols
 Emojis
 Letters from all languages (Hindi, Chinese, Arabic, etc.)

Example:
If your file has the text "Hello राहुल", then encoding="utf-8" ensures both English
and Hindi letters are read correctly. Without specifying it, Python might give an
error.

e. Create a pie chart using matplotlib to represent the following data:


Languages Popularity
Python 30
Java 25
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 76 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

C++ 20
JavaScript 15
Ruby 10

Solution:
Method-1: Using Variables (Best for Learning)
import [Link] as plt

# Data
languages = ['Python', 'Java', 'C++', 'JavaScript', 'Ruby']
popularity = [30, 25, 20, 15, 10]
# Create pie chart
[Link](popularity, labels=languages)

# Add title
[Link]('Programming Language Popularity')

# Show the chart


[Link]()

Output:

Method-2: Direct Values (Short & Fast)


import [Link] as plt

[Link]([30,25,20,15,10], labels=['Python','Java','C++','JavaScript','Ruby'])
[Link]("Language Popularity")
[Link]()

Output:

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 77 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

Method-3: With Percentages (Most Informative)


import [Link] as plt

[Link]([30, 25, 20, 15, 10],


labels=['Python','Java','C++','JavaScript','Ruby'],
autopct='%1.0f%%') # ← This adds percentages!

[Link]("Language Popularity")
[Link]()
Output:

Note:
autopct:
1. autopct stands for “automatic percentage”.
2. It tells Matplotlib to display the percentage value for each slice of the
pie chart.

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 78 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

autopct='%1.0f%%')
Part Meaning
'%' Starts a format string
Tells Python to format the number as a floating-point number with
1.0f
0 digits after the decimal
%% Prints a literal percent sign (%) after the number
So, ' %1.0f%% ' means: Show the number as a floating-point value with no decimal
places, followed by a percent sign.

SECTION C

Q.3. Attempt any one part of the following: 7M X 1 = 7M

a. Write short notes on the following with examples:


i. Operator Precedence
ii. Python Indentation
iii. Type Conversion
Solution:
i. Operator Precedence
 Operator precedence determines the order in which operations are performed
in an expression.
 Python follows a fixed priority

Common Precedence Order (High to Low):


 ( ) Parentheses can be used to change the default order.
 ** Exponentiation
 *, /, //, % Multiplication and Division
 +, - Addition and Subtraction
 Comparison operators (<, >, ==, etc.)
 Logical operators (and, or, not)

Example:
print(2 + 3 * 4) # 14 (multiplication first)
print((2 + 3) * 4) # 20 (parentheses first)
Output:
14
20

ii. Python Indentation


 Indentation refers to the spaces or tabs used at the beginning of a line to
define blocks of code.
 In Python, indentation is mandatory to define code blocks (like loops,
functions, conditions).
 Improper indentation gives an IndentationError.

Example:
if True:
print("Indented block") # This line is inside the if-block
print("Outside block") # This line is outside the if-block

iii. Type Conversion


AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 79 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

Type conversion refers to changing a value from one data type to another.

Two Types of Type Conversion:


1. Implicit Conversion (Automatic by Python)
 Python automatically converts smaller data types to larger ones to
avoid data loss.
 No manual intervention is needed.
Example:
x = 10 # Integer
y = 2.5 # Float
z=x+y # Python converts x to float
print(z) # Output: 12.5

2. Implicit Conversion (Automatic by Python)


 The programmer uses built-in functions to convert data types.
 Common functions: int(), float(), str(), bool(), list(), tuple()
Example:
a = "123" # String
b = int(a) # Convert to integer
print(b + 1) # Output: 124

b. Write a program to validate email addresses using regular expressions. Criteria:


i. Must contain @ symbol
ii. Must contain domain name
iii. Should not have spaces

Solution:
Method-1: User Input–based Email Validation (Regex)
import re # Import regular expression module

# Simple email pattern


pattern = r"^[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[a-zA-Z]{2,}$"

# Input from user


email = input("Enter your email address: ")

# Check the pattern


if [Link](pattern, email):
print("✅ Valid Email Address")
else:
print("❌ Invalid Email Address")
Explanation:
1. import re → imports the regular expression module used for pattern matching.
2. pattern → defines the email format to check.
 ^ → start of string
 [a-zA-Z0-9]+ → letters or numbers before @
 @ → must have one @ symbol
 [a-zA-Z0-9]+ → domain name (like gmail)
 \. → dot before domain extension
 [a-zA-Z]{2,} → domain extension (like com, in, org)
 $ → end of string
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 80 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

3. [Link]() → checks if the entered email follows the given pattern.


4. If matched → prints “✅ Valid Email Address.”
5. Else → prints “❌ Invalid Email Address.”

Note:
The part [a-zA-Z]{2,} means the domain extension (like .com, .org, .in, .edu) must have
at least two letters.

Method-2: Predefined Test Emails – Loop-based Email Validation (Regex)


import re # Import regular expression module

# Simple email pattern


pattern = r"^[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[a-zA-Z]{2,}$"

# Two test emails


test_emails = [
"user@[Link]", # valid
"hello@domain" # invalid (missing .com/.in etc.)
]

# Check each test email


for email in test_emails:
if [Link](pattern, email):
print(f"✅ Valid Email Address: {email}")
else:
print(f"❌ Invalid Email Address: {email}")
Output:
✅ Valid Email Address: user@[Link]
❌ Invalid Email Address: hello@domain

Q.4. Attempt any one part of the following: 7M X 1 = 7M

a. Write a program to create a hollow pyramid pattern given below:


*
**
**
* *
* *
*********

Solution:
Method-1: Using nested for loop
rows = [1, 2, 2, 2, 2, 9]

for r in range(len(rows)):
for s in range(rows[r]):

# Add big space for 4th and 5th row


AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 81 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

if r == 3 or r == 4:
print("*", end=" ") # extra spaces
else:
print("*", end=" ") # normal space
print() # move to next line
Output:
*
**
**
* *
* *
******
Explanation:
1. rows = [1, 2, 2, 2, 2, 9] → tells how many * to print in each row.
2. Outer loop (for r in range(len(rows))) → runs once for each row.
3. Inner loop (for s in range(rows[r])) → prints stars in that row.
4. Conditional spacing:
 For 4th and 5th rows, adds more space (end=" ").
 For all other rows, uses normal spacing (end=" ").
5. print() → moves to the next line after each row.

Method-2: Without using nested for loop


rows = [1, 2, 2, 2, 2, 9]

for i in range(6):
if i == 0:
print("*")
elif i == 1 or i == 2:
print("* *")
elif i == 3 or i == 4:
print("* *")
else:
print("* * * * * * * * *")
Output:
*
**
**
* *
* *
******
Explanation (step by step)
1. rows = [1, 2, 2, 2, 2, 9]
 Defines how many stars to print in each row (used just for reference
pattern control is done using if conditions).
2. for i in range(6):
 Runs 6 times (for 6 rows: i = 0 to 5).
3. if i == 0:
 Prints the first row → only one star
→*

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 82 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

4. elif i == 1 or i == 2:
 Prints second and third rows → two stars
→**
5. elif i == 3 or i == 4:
 Prints fourth and fifth rows → stars with extra space in between
→**
6. else:
 Prints the last row → nine stars
→*********

b. Explain the why loops are needed and the types of loops in python. Discuss break
and continue with example.

Solution:
Why loops are needed?
 In Python programming, loops are used to execute a block of code repeatedly until
a certain condition is met.
 Without loops, if we want to perform a task multiple times (like printing 1 to 100),
we would need to write the same statement again and again which is time-
consuming and inefficient.

Types of loops in python:


Python provides two main types of loops:
5. for loop
6. while loop
5. for Loop:
 The for loop is used to iterate over a sequence (like a list, tuple, string, or range
of numbers).
 It automatically goes through each element in the sequence.

Syntax: for Loop


for variable in sequence:
# body of loop
Explanation:
 variable: Takes each value from the sequence one at a time.
 sequence: Can be a list, tuple, string, or range().

Figure: Flowchart of for Loop


Example: Simple for loop

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 83 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

# Example of for loop


for i in range(1, 6):
print("Number:", i)
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Explanation:
 range(1, 6) generates numbers from 1 to 5.
 The loop runs five times, printing each number.

6. while Loop:
 The while loop repeats a block of code as long as a given condition is true.
 You must make sure the condition eventually becomes false to avoid an infinite
loop.

Syntax: while Loop


while condition:
# body of loop
Explanation:
 condition: A boolean expression (True or False).
 As long as this condition is True, the loop continues executing.

Figure: Flowchart of while Loop


Example: Simple while loop
# Example of while loop
i=1
while i <= 5:
print("Number:", i)
i=i+1
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Explanation:

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 84 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

 The loop starts with i = 1.


 It runs as long as i <= 5.
 Each time, it prints the value of i and increases it by 1.

break and continue Statements:


Both break and continue are loop control statements used to change the normal flow
of execution inside loops.

break Statement:
The break statement is used to terminate (stop) the loop immediately, even if the
condition is still true.

continue Statements:
The continue statement is used to skip the current iteration of the loop and move to
the next iteration.

Syntax:
break Statement Syntax continue Statements Syntax
for/while condition: for/while condition:
if test_condition: if test_condition:
break continue
# rest of the loop # rest of the loop

Example Program:
break Statement continue Statements
for i in range(1, 6): for i in range(1, 6):
if i == 4: if i == 3:
break continue
print(i) print(i)
Output: Output:
1 1
2 2
3 4
5
The loop stops when i == 4. The loop skips printing 3 but continues
running.

Q.5. Attempt any one part of the following: 7M X 1 = 7M

a. Write a function to find the longest word in a given list of words.


Example:
longest_word(['apple', 'banana', 'cherry'])
returns 'banana'

Solution:
Method-1

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 85 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

def longest_word(words):

longest = words[0] # assume first word is longest initially


for word in words:
if len(word) > len(longest):
longest = word # update if current word is longer
return longest

# Example
print(longest_word(['apple', 'banana', 'cherry']))
Output:
banana
Explanation:
1. Assume the first word in the list is the longest.
2. Loop through each word in the list.
3. If a word has length greater than the current longest, update it.
4. Return the longest word after checking all words.

Method-2
def longest_word(words):
return max(words, key=len)

# Test
print(longest_word(['apple', 'banana', 'cherry']))
Output:
banana
Explanation:
 max(words, key=len) finds the word with the maximum length.
 key=len tells Python to compare words based on their length.
 The function returns 'banana' because it has the most characters.

b. Distinguish between a Tuple and a List with examples. Explain with examples at
least 4 built-in methods of Dictionary.

Solution:
Difference Between Tuple and List
Feature List Tuple
A list is an ordered, mutable A tuple is an ordered, immutable
Definition
(changeable) collection of items. (unchangeable) collection of items.
Syntax Defined using square brackets [ ] Defined using parentheses ( )
Elements can be changed, added, or Elements cannot be changed after
Mutability
removed. creation.
Used when data may change Used when data should remain
Use Case (student marks, shopping cart, constant (coordinates, days of
etc.). week, etc.).
Example my_list = [10, 20, 30] my_tuple = (10, 20, 30)

Example: list
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 86 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

my_list = [10, 20, 30]


print("Original List:", my_list)

my_list.append(40) # Adding element


print("After append:", my_list)

my_list[1] = 25 # Modifying element


print("After modification:", my_list)
OUTPUT:
Original List: [10, 20, 30]
After append: [10, 20, 30, 40]
After modification: [10, 25, 30, 40]

Example: tuple
my_tuple = (10, 20, 30)
print("Tuple:", my_tuple)

# my_tuple[1] = 25 ❌ This will give error (immutable)


# my_tuple.append(40) ❌ This will also give ERROR
OUTPUT:
Tuple: (10, 20, 30)
Explanation: Lists can be changed, tuples cannot.

Dictionary Built-in Methods (with Examples)


 A dictionary in Python stores data as key–value pairs inside { }.

Example Dictionary
student = {"name": "Rahul", "age": 20, "branch": "ECE"}

DICTIONARY IN-BUILT METHODS


In-built
Example Output Explanation
Function
Returns number of key-
len() len({'a':1,'b':2}) 2
value pairs.
Returns sorted list of
sorted() sorted({'b':2,'a':1}) ['a','b']
dictionary keys.
sum() sum({'a':10,'b':20}.values()) 30 Adds all numeric values.
Finds smallest or largest
min() / max() max({'a':1,'b':5}.values()) 5
value.
keys() list({'a':1,'b':2}.keys()) ['a','b'] Returns list of all keys.
values() list({'a':1,'b':2}.values()) [1,2] Returns list of all values.
Returns key-value pairs as
items() list({'a':1,'b':2}.items()) [('a',1),('b',2)]
tuples.
[Link]('name','Not
get() 'Rahul' Safely gets value for a key.
Found')

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 87 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

Removes and returns value


pop() d={'a':1,'b':2}; [Link]('a') 1
of given key.
Removes and returns last
popitem() d={'x':1,'y':2}; [Link]() ('y',2)
inserted pair.
Adds or updates key-value
update() d={'a':1}; [Link]({'b':2}) {'a':1,'b':2}
pairs.
Note: Explain any 4 built-in methods and write simple example program covering 4
built-in methods.

Example Program: DICTIONARY IN-BUILT METHODS


d = {'a': 10, 'b': 20, 'c': 30}
print("Original Dictionary:", d)

# 1. len()
print("1. Length:", len(d))

# 2. sorted()
print("2. Sorted keys:", sorted(d))

# 3. sum(), min(), max()


print("3. Sum:", sum([Link]()))
print(" Min:", min([Link]()))
print(" Max:", max([Link]()))

# 4. keys(), values(), items()


print("4. Keys:", list([Link]()))
print(" Values:", list([Link]()))
print(" Items:", list([Link]()))

# 5. get()
print("5. Get value of 'b':", [Link]('b'))

# 6. pop()
[Link]('a')
print("6. After pop:", d)

# 7. popitem()
[Link]()
print("7. After popitem:", d)

# 8. update()
[Link]({'x': 100})
print("8. After update:", d)
Output:
Original Dictionary: {'a': 10, 'b': 20, 'c': 30}
1. Length: 3
2. Sorted keys: ['a', 'b', 'c']
3. Sum: 60
Min: 10
Max: 30
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 88 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

4. Keys: ['a', 'b', 'c']


Values: [10, 20, 30]
Items: [('a', 10), ('b', 20), ('c', 30)]
5. Get value of 'b': 20
6. After pop: {'b': 20, 'c': 30}
7. After popitem: {'b': 20}
8. After update: {'b': 20, 'x': 100}

Q.6. Attempt any one part of the following: 7M X 1 = 7M

a. Discuss different types of file modes in Python and explain with examples.

Solution:
File Modes in Python
 File modes in Python tell the program how a file should be opened and what kind
of operation can be performed on it such as reading, writing, or appending data.
 When we open a file using the open() function, we specify the mode as a string
argument.

Syntax: open()
file_object = open("filename", "mode")
 Here, the file name is "[Link]" and the mode describes how the file will be opened
(read, write, append, etc.).
 After all operations, the file must be closed using the close() method.

Syntax: close()
file_object.close()

The best practice to open the file is with open statement so the file closes automatically:

Syntax: with open


with open("filename", "mode") as file:
# file operations
Using with automatically closes the file when the block ends no need to call close()
manually.

Types of File Modes in Python:


Creates
Mode Operation Type Description
File?
'r' Read Opens file for reading only (file must exist). No
'w' Write Opens file for writing. Overwrites file if it exists. Yes
'a' Append Opens file for appending new data to the end. Yes
Creates a new file. Gives error if file already
'x' Create Yes
exists.
'r+' Read & Write Opens file for both reading and writing. No
'w+' Write & Read Overwrites existing file or creates new one. Yes
'a+' Append & Read Opens file for reading and appending data. Yes
'b' Binary Used for binary files (images, videos, etc.). -
't' Text Default mode for text files. -
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 89 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

1. Read Mode ('r'):


Used when you only want to read data from a file.
Example Program:
If [Link] file already contains: Hello Rahul
file = open("[Link]", "r")
print([Link]())
[Link]()
The file content of [Link] contains after running the program: Hello Rahul
Note: File must already exist, otherwise an error occurs.

2. Write Mode ('w'):


Used to create a new file or overwrite an existing one.
Example Program:
If [Link] file already contains: XXXXXX
file = open("[Link]", "w")
[Link]("Hello Rahul")
[Link]()
The file content of [Link] contains after running the program: Hello Rahul
Note: Existing content is erased.

3. Append Mode ('a'):


Used to add new data at the end of an existing file.
Example Program:
If [Link] file already contains: Hi
file = open("[Link]", "a")
[Link]("\nHello Rahul")
[Link]()
The file content of [Link] contains after running the program:
Hi
Hello Rahul
Note: Existing content is not erased.

4. Create Mode ('x'):


Used to create a new file. Gives an error if the file already exists.
Example Program:
If [Link] file already contains: Hi
file = open("[Link]", "x")
[Link]("Hello Rahul")
[Link]()
The file content of [Link] contains after running the program, file becomes:
FileExistsError
Note:
 If file already exists → ❌ FileExistsError.
 'x' mode fails if the file already exists.

5. Read + Write Mode ('r+'):


Used to both read and write data in the same file.
Example Program:
If [Link] file already contains: Hello Rahul
file = open("[Link]", "r+")
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 90 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

print("Before:", [Link]())
[Link]("\nHello Rahul")
[Link]()
Note: File must already exist.
(Assuming [Link] initially contains Hello Rahul.)

6. Write + Read Mode ('w+'):


Used to write and then read a file. It overwrites the existing file.

Example Program:
If [Link] file already contains: Hello Rahul
file = open("[Link]", "w+")
[Link]("Hello Rahul")
[Link](0)
print([Link]())
[Link]()
Output:
Hello Rahul
Note: seek(0) moves the file pointer to the beginning for reading.

7. Append + Read Mode ('a+'):


Used to append data and read from the same file.
Example Program:
file = open("[Link]", "a+")
[Link]("\nHello Rahul")
[Link](0)
print([Link]())
[Link]()
(Result in file will include one more “Hello Rahul” at the end.)

8. Binary Modes ('rb', 'wb'):


(Used for binary files like images, videos, or audio files.
Example Program:
# Write bytes
with open("[Link]", "wb") as f:
[Link](b"Hello Rahul")

# Read bytes
with open("[Link]", "rb") as f:
data = [Link]()
print(data)
Output:
b'Hello Rahul'
Note: Binary modes handle raw bytes. Typically used for images or media files.

9. Using with (Recommended Method):


Automatically closes the file after the block finishes.
Example Program:
with open("[Link]", "w") as f:
[Link]("Hello Rahul")
The file closes automatically after the block finishes.
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 91 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

b. Write a program to read a CSV file and display the rows where a specific column
value exceeds a given threshold.

Solution:

Example Program:
Initial File Content [Link]
Name,Marks
Rahul,45
Bharat,78
Manoj,62
Ritesh,39
import csv

# Set threshold value


threshold = 50

# Open and read the CSV file


with open("[Link]", "r") as file:
reader = [Link](file) # Reads rows as dictionaries

print("Rows where Marks > 50:")


for row in reader:
if int(row["Marks"]) > threshold:
print(row)
Output:
Rows where Marks > 50:
{'Name': 'Bharat', 'Marks': '78'}
{'Name': 'Manoj', 'Marks': '62'}
Explanation:
1. import csv Loads the CSV module to handle file reading.
2. threshold = 50 Sets the minimum marks to filter.
3. open("[Link]", "r") Opens the file in read mode.
4. [Link](file) Reads each row as a dictionary: Example → {'Name': 'Rahul',
'Marks': '45'}
5. int(row["Marks"]) > threshold Converts the "Marks" value to integer and checks if
it's greater than 50.
6. print(row) Displays the entire row if condition is true.

Q.7. Attempt any one part of the following: 7M X 1 = 7M

a. Discuss the role of event handling in Tkinter. How can events be bound to widgets?
Provide examples.

Solution:
1. Role of Event Handling in Tkinter

 Event handling in Tkinter refers to the process of responding to user


actions such as mouse clicks, key presses, or window events.

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 92 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

 Tkinter applications run an event loop (mainloop()) which continuously


monitors for such events and triggers the associated event handlers
(functions).
 It allows GUI programs to become interactive and dynamic instead of
being static displays.

Example of events:

 Clicking a button
 Pressing a key
 Moving the mouse over a widget

Purpose:
Event handling helps in executing specific functions automatically when a user
performs an action.

2. Binding Events to Widgets

Events can be bound to widgets in two main ways:

(a) Using command attribute:


Some widgets (like Button, Menu, etc.) have a built-in command option that
executes a function when the widget is activated.

from tkinter import *


def greet():
print("Hello, Tkinter!")
root = Tk()
btn = Button(root, text="Click Me", command=greet)
[Link]()
[Link]()

(b) Using bind() method:


The bind() function allows you to connect a specific event to a callback
function for any widget.

Syntax:

[Link]("<event>", handler_function)

Example:

from tkinter import *


def on_click(event):
print("Mouse clicked at:", event.x, event.y)
root = Tk()
label = Label(root, text="Click inside this label", bg="lightblue", width=25,
height=4)
[Link]()

[Link]("<Button-1>", on_click) # Left mouse click event


AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 93 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

[Link]()

3. Common Tkinter Events (1 Mark)

Event Description
<Button-1> Left mouse click
<Double-Button-1> Double click
<Enter> Mouse enters widget area
<Leave> Mouse leaves widget area
<Key> Any key pressed
<Return> Enter key pressed

Event handling is a crucial part of Tkinter that makes GUI applications responsive
and interactive. It can be implemented easily using either the command parameter
or the bind() method to connect widgets with user actions.

b. Write a program to read data from a CSV file '[Link]', calculate the average
marks for each student, and display the results

Solution:
Method-1: Using [Link] (Basic CSV Reading with Lists)
Assume the CSV file looks like this (3 subjects per student):
Name,Math,Science,English
Rahul,80,75,90
Bharat,60,70,65
Manoj,90,95,85
Ritesh,50,55,58
import csv

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


reader = [Link](f)
next(reader) # skip header row: Name,Math,Science,English

for row in reader:


name = row[0]
m1 = int(row[1])
m2 = int(row[2])
m3 = int(row[3])

avg = (m1 + m2 + m3) / 3


print(name, "-> Average:", round(avg, 2))
Output:
Student Averages:
Rahul -> Average: 81.67
Bharat -> Average: 65.0
Manoj -> Average: 90.0
Ritesh -> Average: 54.33
Explanation:
1. import csv
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 94 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

 We import the csv module so we can read data from a CSV file.
2. with open("[Link]", "r") as f:
 Opens the file named [Link] in read mode ("r").
 with makes sure the file will close automatically.
3. reader = [Link](f)
 Creates a CSV reader that reads the file line by line.
4. next(reader)
 Skips the first row in the file (Name,Math,Science,English) because that row
is just column titles, not data.
5. for row in reader:
 Goes through each remaining row in the file.
 Each row is a list of values from the CSV, for example:
["Rahul", "80", "75", "90"]
6. name = row[0]
 Gets the student's name (first column).
7. m1 = int(row[1]), m2 = int(row[2]), m3 = int(row[3])
 Gets the three marks (Math, Science, English) and converts them from strings
to integers.
8. avg = (m1 + m2 + m3) / 3
 Calculates the average marks for that student.
9. print(name, "-> Average:", round(avg, 2))
 Prints the student's name and their average.
 round(avg, 2) keeps only 2 decimal places (like 81.67).

Method-2: Using [Link] (Reading CSV as Dictionaries)


Assume the CSV file looks like this (3 subjects per student):
Name,Math,Science,English
Rahul,80,75,90
Bharat,60,70,65
Manoj,90,95,85
Ritesh,50,55,58
import csv

# Open and read the CSV file


with open("[Link]", "r") as file:
reader = [Link](file) # reads each row as a dictionary

print("Student Averages:")
for row in reader:
name = row["Name"]

# Get marks for the subjects and convert to int


math = int(row["Math"])
sci = int(row["Science"])
eng = int(row["English"])

# Calculate average
avg = (math + sci + eng) / 3

# Print result (rounded to 2 decimal places)


print(name, "-> Average:", round(avg, 2))
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 95 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

Output:
Student Averages:
Rahul -> Average: 81.67
Bharat -> Average: 65.0
Manoj -> Average: 90.0
Ritesh -> Average: 54.33
Explanation:
1. import csv → Imports Python’s CSV module for reading CSV files easily.
2. with open("[Link]", "r") as file:
Opens the file in read mode ("r"). The with statement ensures the file closes
automatically.
3. [Link](file) → Reads each line as a dictionary.
Example row:
4. {'Name': 'Rahul', 'Math': '80', 'Science': '75', 'English': '90'}
5. Extract name:
name = row["Name"]
6. Extract marks:
[int(value) for key, value in [Link]() if key != "Name"]
→ Converts all subject marks into integers.
7. Find average:
avg = sum(marks) / len(marks)
→ Adds marks and divides by total subjects.
8. Display result:
print(name, "-> Average:", round(avg, 2))
→ Prints average up to two decimal places.

Method-3: Using pandas (DataFrame-Based Calculation of Averages)


Assume the CSV file looks like this (3 subjects per student):
Name,Math,Science,English
Rahul,80,75,90
Bharat,60,70,65
Manoj,90,95,85
Ritesh,50,55,58
import pandas as pd
df = pd.read_csv("[Link]")
df["Average"] = df[["Math", "Science", "English"]].mean(axis=1)

print(df[["Name", "Average"]].round(2))
Output:
Name Average
0 Rahul 81.67
1 Bharat 65.00
2 Manoj 90.00
3 Ritesh 54.33
Note:
 pd.read_csv() → Reads data from a CSV file into a DataFrame.
 df["Average"] → Creates a new column with calculated averages.
 [Link]() → Loops through each row in the DataFrame.
 round(value, 2) → Rounds the average to 2 decimal places.
Explanation:
Step 1: import pandas as pd
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 96 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

 This loads the pandas library.


 Pandas helps us work with table data (like data in Excel or CSV files).
Step 2: df = pd.read_csv("[Link]")
 pd.read_csv("[Link]") reads the CSV file named [Link].
 The data is stored in a table called df (DataFrame).
 Now df has columns: Name, Math, Science, English.

Example of what df looks like:


Name Math Science English
Rahul 80 75 90
Bharat 60 70 65
Manoj 90 95 85
Ritesh 50 55 58
Step 3:
df["Average"] = df[["Math", "Science", "English"]].mean(axis=1)
Break it:
 df[["Math", "Science", "English"]]
 Take only the three marks columns from the table.
 .mean(axis=1)
 For each row (for each student), calculate the average of those three marks.
 Example for Rahul:
 (80 + 75 + 90) / 3 = 81.67
 df["Average"] = ...
 Create a new column called Average in the table and store the result there.

Now the table df looks like:


Name Math Science English Average
Rahul 80 75 90 81.6667
Bharat 60 70 65 65.0000
Manoj 90 95 85 90.0000
Ritesh 50 55 58 54.3333
Step 4:
print(df[["Name", "Average"]].round(2))
Break it:
 df[["Name", "Average"]]
 Pick only the Name column and the new Average column.
 We don't print all marks now.
 .round(2)
 Round the Average to 2 decimal places (for neat output like 81.67 instead of
81.6666667).
 print(...)
 Show the result.
Final Output on screen:
Name Average
0 Rahul 81.67
1 Bharat 65.00
2 Manoj 90.00
3 Ritesh 54.33

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 97 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

[Link].
(SEM IV) THEORY EXAMINATION 2024-25
PYTHON PROGRAMMING (BCC-401)

Maximum Marks: 70
SECTION A

Q.1. Attempt all questions in brief. (2M X 7 =14M)


a) What are Python variables? Explain with examples.

Solution:
 A variable is a name given to store data in memory.
 It acts as a container for values that can change during program execution.
 In Python, you don’t need to declare data types they’re assigned
automatically.

Example Program:
x = 10 # integer
name = "Rahul" # string
price = 99.5 # float
print(x, name, price)

Output:
10 Rahul 99.5

RULES FOR NAMING VARIABLES


Allowed:
 Must start with a letter or an underscore.
 Can contain letters, digits, and underscores.
 Are case sensitive (Value ≠ value).

Not allowed:
 Cannot contain spaces or special characters (@, $, %, -).
 Cannot use Python keywords (if, for, True, etc.).

Valid example
 student_name
 marks_obtained
 _temp
 roll_number10

b) Describe Python basic operators with suitable examples.


Solution:
Operators perform operations on variables and values.
Type Operator Example Result
Arithmetic +, -, *, /, % 10 + 5 15
Comparison ==, !=, >, < 5 < 10 True
Logical and, or, not x>5 and x<10 True
Assignment =, +=, -= x += 2 Adds 2 to x
Membership in, not in "a" in "apple" True
Identity is, is not a is b True if same object
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 98 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

Example Program:
a, b = 10, 5
print(a + b) # 15
print(a > b) # True
print(a != b) # True

Output:
15
True
True

c) Explain different Python data types with examples.


Solution:
In Python, data types define the type of value a variable can hold. Since Python is
dynamically typed, you don’t need to declare the data type explicitly it is
determined automatically.
The main categories of python data types
 Numeric Types: int, float, complex
 Text Type: str
 Sequence Types: list, tuple, range
 Mapping Type: dict
 Set Types: set, frozenset
 Boolean Type: bool
 Binary Types: bytes, byte array, memory view
 None Type: None Type

Example:
# Numeric data types
a=5 # Integer data type
b = 4.5 # Float data type
c = 1 + 2j # Complex data type

# String data type


name = "Python"

print(a)
print(b)
print(c)
print("String:", name)
Output:
5
4.5
(1+2j)
String: Python

d) How are numeric data types declared and used in Python?


Solution:
Python provides three numeric data types to represent numbers:
1. int (Integer)
2. float (Floating-point numbers)
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 99 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

3. complex (Complex numbers)


1. Integer (int)
 Whole numbers (positive, negative, or zero).
 No decimal point.
 Can be of any length (Python handles big integers automatically).

2. Float (float)
 Numbers with decimal point.
 Can also be written in scientific notation (e or E for powers of 10).

3. Complex (complex)
 Numbers with real and imaginary parts.
 Written as real + imag j (where j is the imaginary unit).

Example Program: Numeric data type


a=5 # Integer data type
b = 4.5 # Float data type
c = 1 + 2j # Complex data type

print(a)
print(b)
print(c)
Output:
5
4.5
(1+2j)

e) Write a Python program to demonstrate type casting between int, float, and string.
Solution:
Example Program: type casting (conversion) between int, float, and str
# Original values
a = 10 # int data type
b = 3.6 # float data type
c = "Hello" # string data type (string in quotes)

print("Original int:", a)
print("Original float:", b)
print("Original string:", c)

# int to float
x = float(a)
print("int to float:", x)
# float to int
y = int(b)
print("float to int:", y)

# int to string
z = str(a)
print("int to string:", z)
Output:
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 100 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

Original int: 10
Original float: 3.6
Original string: Hello
int to float: 10.0
float to int: 3
int to string: 10

f) Explain the use of if, else, and elif. Write a Python program to check the given
number is even or odd using if and else statement.
Solution:

Use of if, elif, else in Python


 if → Used to check a condition. If the condition is True, the code inside the if
block is executed.
 elif → (short for else if) Used when there are multiple conditions to check.
 else → Runs when all previous conditions are False.

if condition1:
# code if condition1 is true
elif condition2:
# code if condition2 is true
else:
# code if none of the conditions are true

# Program to check whether a number is even or odd


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

if num % 2 == 0:
print(num, "is Even")
else:
print(num, "is Odd")
Output: Output:
Enter a number: 8 Enter a number: 7
8 is Even 7 is Odd

g) Differentiate between for loop and while loop with syntax and examples.
Solution:
For Loop
 Used to iterate over a sequence (like a list, tuple, string, or range).
 Number of iterations is known or definite.

Syntax Example Program


for variable in sequence: # Print numbers from 1 to 5
# code to execute for i in range(1, 6):
print(i)
Output:
1
2
3
4
5
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 101 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

While Loop
 Repeats a block of code as long as a condition is True.
 Number of iterations is unknown or indefinite until the condition becomes
False.

Syntax Example Program


while condition: # Print numbers from 1 to 5
# code to execute i=1
while i <= 5:
print(i)
i += 1
Output:
1
2
3
4
5

Table: Comparison for Loop vs while Loop


Feature For Loop While Loop
Iterate over a sequence Repeat while a condition is
Usage
(definite) True (indefinite)
for variable in
Syntax while condition:
sequence:
Unknown (depends on
Iterations Known (fixed)
condition)
Example for i in range(5): while i < 5:

SECTION B

Q.2. Attempt any three of the following (7M X 3 =21M)


a. What are break, continue, and pass statements? Give code examples.

Solution:
Python provides special statements that let us control the flow of loops. These are
useful when we want to skip iterations, exit early, or handle conditions differently.
The different loop manipulation statements in Python are:
1. pass
2. continue
3. break

pass Statement:
 pass is a null statement in Python.
 It does nothing when executed.
 It is used as a placeholder where syntactically a statement is required but
you don’t want any action to occur.
 This helps avoid syntax errors when writing code structures that are not
yet fully implemented.

Syntax:
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 102 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

for item in sequence:


pass # Loop body intentionally left empty

while condition:
pass # Placeholder for future logic

Example Program: pass Statement


# Example: do nothing when number is 4
for i in range(1, 7):
if i == 4:
pass # placeholder, does nothing
print("Number:", i)
print("Program executed successfully.")
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Number: 6
Program executed successfully.
Explanation:
 When i is 4, Python just executes pass (does nothing) and continues
normally.
Continue statement:
 The continue statement is used inside loops to skip the current iteration
and move directly to the next iteration of the loop.
 The loop does not terminate; it simply bypasses the remaining code in that
iteration.

Syntax: for Loop with continue Syntax: while Loop with continue
for item in sequence: for item in sequence:
if condition: if condition:
continue continue
# remaining code # remaining code

Example Program: continue Statement

# Example: skip printing the number 4


for i in range(1, 7):
if i == 4:
continue
print("Number:", i)
print("Loop finished normally.")
Output:
Number: 1
Number: 2
Number: 3
Number: 5
Number: 6
Loop finished normally.
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 103 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

Explanation:
 When i is 4, continue skips that iteration and moves to the next number.

break statement:
 The break statement is used to exit a loop immediately, regardless of
whether the loop condition is still true or the sequence has more items.
 Once break is executed:
 The current loop (either for or while) terminates instantly.
 The program continues with the next statement after the loop.

Syntax of break in a for loop


for variable in sequence:
if condition:
break # Exit the loop completely
# Code here runs only if break is not executed

Example Program: break Statement


# Example: stop the loop when number reaches 4
for i in range(1, 7):
if i == 4:
break
print("Number:", i)
print("Loop stopped at i =", i)
Output:
Number: 1
Number: 2
Number: 3
Loop stopped at i = 4
Explanation:
 When i becomes 4, break stops the loop completely.

b. Write a Python program using for loop and dictionary to display student grades.
Solution:
 A dictionary stores data in key: value pairs (here, student: grade).

Example Program: Display Student Grades (METHOD-1)


# Dictionary with student names and their grades
grades = {"Rahul": "A", "Bharat": "A+", "Manoj": "B+", "John":
"A++"}

# Using for loop to print each student's grade


for student in grades:
print(student, "got grade", grades[student])
Output:
Rahul got grade A
Bharat got grade A+
Manoj got grade B+
John got grade A++
Explanation:
 grades is a dictionary.
 Keys → Student names ("Rahul", "Bharat", "Manoj", "John")
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 104 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

 Values → Their grades ("A", "A+", "B+", "A++")


 The for loop goes through each student name.
 grades[student] gives the grade for that student.
 The program prints name + grade like a small report card.

Example Program: Display Student Grades Using .items() (METHOD-2)


# Dictionary with student names and their grades
grades = {"Rahul": "A", "Bharat": "A+", "Manoj": "B+", "John": "A++"}

# Using for loop with .items() to print each student's grade


for student, grade in [Link]():
print(student, "got grade", grade)
Output:
Rahul got grade A
Bharat got grade A+
Manoj got grade B+
John got grade A++
Explanation
1. Dictionary creation
 grades is a dictionary.
 It stores student names as keys (Rahul, Bharat, Manoj, John).
 It stores grades as values (A, A+, B+, A++).
2. for loop with .items()
 .items() gives both key (student) and value (grade) together.
 So, in each loop:
 student = one name
 grade = that student’s grade
3. Printing
 print(student, "got grade", grade) displays the result in a clear way.

c. Discuss the use of nested loops in Python. Write a program to print a right-
angled triangle of stars.
Solution:
 A nested loop means one loop inside another loop.
 The outer loop controls the number of rows.
 The inner loop controls the number of columns (what to print in each
row).
 Commonly used for patterns, matrices, tables, etc.

Syntax:

for i in range(outer_limit): # Outer loop


for j in range(inner_limit): # Inner loop
# Statements to execute inside inner loop

Method-1: Right-Angled Triangle of Stars Simplest Method

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 105 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

# Define number of stars in each row


rows = [1, 2, 3, 4, 5]

for count in rows:


for i in range(count):
print("*", end=" ")
print()
Output:
*
**
***
****
*****

Method-2: Right-Angled Triangle Method-3: Right-Angled Triangle of


of Stars Stars
rows = 5 # number of rows # Outer loop for rows (from 1 to 5)
for i in range(1, rows + 1): for i in range(1, 6):
# Outer loop for rows # Inner loop for printing stars in each
for j in range(i): row
# Inner loop for stars for j in range(i):
print("*", end=" ") print("*", end=" ")
print() # Print star and stay on the same line
# Move to next line after each row print()
# Move to the next line after each row
Output: Output:
* *
** **
*** ***
**** ****
***** *****

d. Explain string slicing and string operations in Python.


Solution:

String:
 A string is a sequence of characters enclosed in single (' '), double (" "),
or triple quotes (''' ''' or """ """).
 Strings are immutable, meaning they cannot be changed after creation.

Example:
text = "Python Programming"
print(text)

Output:
Python Programming

String Slicing
String slicing means extracting a portion (substring) of a string using index
positions.
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 106 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

Syntax:
string[start:end:step]

start : Index position to begin slicing (inclusive)


end : Index position to stop slicing (exclusive)
step : (Optional) Skip characters by this step size

Example Program: Basic Slicing

text = "PYTHON"

print(text[0:3]) # First 3 characters


print(text[2:6]) # Characters from index 2 to 5
print(text[:4]) # From start to index 3
print(text[3:]) # From index 3 to end
print(text[-3:]) # Last 3 characters
print(text[::-1]) # Reverse the string

Output:
PYT
THON
PYTH
HON
HON
NOHTYP

Explanation:
1. text[0:3] → characters from index 0,1,2 → "PYT"
2. text[2:6] → "THON"
3. text[:4] → start to index 3 → "PYTH"
4. text[3:] → from index 3 to end → "HON"
5. text[-3:] → last 3 letters → "HON"
6. text[::-1] → reverse order → "NOHTYP"

Example Program: Step Slicing


word = "Programming"
print(word[0:11:2]) # Every 2nd character

Output:
Pormig

Explanation:
 It starts from index 0 to 10 and picks every second character.

String Operations:
Python provides many built-in operations and functions to manipulate strings
easily.

A. Concatenation (Joining Strings)


s1 = "Hello"
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 107 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

s2 = "Rahul"
result = s1 + " " + s2
print(result)

Output:
Hello Rahul

Explanation:
The + operator joins two strings together.

B. Repetition
text = "Hi "
print(text * 3)

Output:
Hi Hi Hi

Explanation:
The * operator repeats a string multiple times.

C. Membership Operators
text = "Python Programming"
print("Python" in text) # True
print("Java" not in text) # True

Output:
True
True

Explanation:
 "in" checks if a substring exists.
 "not in" checks if it doesn’t exist.

D. String Comparison
a = "apple"
b = "banana"
print(a == b)
print(a < b)

Output:
False
True

Explanation:
String comparison is done alphabetically (lexicographically) based on Unicode
values.

E. Built-in String Functions:


Function Description Example Output
len() Returns length len("Python") 6
upper() Converts to uppercase "hello".upper() HELLO
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 108 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

lower() Converts to lowercase "HELLO".lower() hello


title() Capitalizes each word "python programming".title() Python Programming
strip() Removes spaces " Hello ".strip() Hello
replace(a,b) Replace substring "Python".replace("Py", "My") Mython
find() Finds position "Programming".find("g") 3
count() Counts occurrences "banana".count("a") 3

Example Program: Built-in String Functions operation

text = " Python Programming "

print("Original:", text)
print("Length:", len(text))
print("Uppercase:", [Link]())
print("Lowercase:", [Link]())
print("Stripped:", [Link]())
print("Replaced:", [Link]("Python", "Java"))
print("Count of 'm':", [Link]("m"))

Output:
Original: Python Programming
Length: 23
Uppercase: PYTHON PROGRAMMING
Lowercase: python programming
Stripped: Python Programming
Replaced: Java Programming
Count of 'm': 2

Explanation:
1. len() → counts spaces too → 23 characters.
2. upper() / lower() → change case.
3. strip() → removes spaces from both sides.
4. replace() → replaces “Python” with “Java”.
5. count() → counts how many times “m” appears.

e. Describe how tuples differ from lists in Python with examples.


Solution:
List:
 A list is an ordered, mutable (changeable) collection of elements.
 It allows adding, removing, or modifying elements after creation.
 Defined using square brackets [ ].

Syntax:
variable = [item1, item2, item3]

Example:
my_list = ["apple", "banana", "cherry"]

Tuple:
 A tuple is an ordered, immutable (unchangeable) collection of elements.
 Once created, its elements cannot be modified.
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 109 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

 Defined using parentheses ( ).

Syntax:
variable = (item1, item2, item3)

Example:
my_tuple= (35, 45, 55)

Example Program 1: List vs Tuple

# Creating a list and a tuple


my_list = [10, 20, 30, 40]
my_tuple = (10, 20, 30, 40)

# Modifying list
my_list[2] = 99
print("Modified List:", my_list)

# Trying to modify tuple (will cause error)


# my_tuple[2] = 99 # This will raise TypeError
print("Tuple remains unchanged:", my_tuple)

Output:
Modified List: [10, 20, 99, 40]
Tuple remains unchanged: (10, 20, 30, 40)
Explanation:
1. my_list can be modified because lists are mutable.
 The third element 30 is changed to 99.
2. my_tuple cannot be modified.
 Attempting to change any value gives an error:
TypeError: 'tuple' object does not support item assignment.

Example Program 2: List vs Tuple


# List example
fruits = ["apple", "banana", "cherry"]
fruits[1] = "orange" # Modifying list element
[Link]("grape") # Adding new item
print("List:", fruits)
# Tuple example
colors = ("red", "green", "blue")
# colors[1] = "yellow" # This will cause an error (tuples are
immutable)
print("Tuple:", colors)

Output:
List: ['apple', 'orange', 'cherry', 'grape']
Tuple: ('red', 'green', 'blue')

Explanation:
Lists are mutable: You can change, add, or remove elements.
 fruits[1] = "orange" changes "banana" to "orange".
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 110 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

 [Link]("grape") adds "grape" to the end of the list.


 Final output: ['apple', 'orange', 'cherry', 'grape']
Tuples are immutable: You cannot change their elements once defined.
 Attempting colors[1] = "yellow" will raise a TypeError.
 Tuples are useful when you want to protect data from modification.
 Final output: ('red', 'green', 'blue')

DIFFERENCE BETWEEN LIST AND TUPLE:


Feature List Tuple
Type Mutable Immutable
variable = [item1, item2, item3] variable = (item1, item2, item3)
Syntax
Example my_list = [1, 2, 3] my_tuple = (1, 2, 3)
Performance Slightly slower Faster (due to immutability)
Add Elements Allowed using append(), insert() Not allowed
Remove Elements Allowed using remove(), pop() Not allowed
Suitable for Changing data Fixed data
Example Use Student marks (changeable) Days of week (fixed)

SECTION C

Q.3. Attempt any one part of the following: (7M X 1 = 7M)

a. Write a program to demonstrate Create, Read, Update, and Delete (CRUD)


operations on a dictionary.
Solution:

In Python, CRUD stands for:


 C → Create (Add items)
 R → Read (Access items)
 U → Update (Modify items)
 D → Delete (Remove items)

Dictionaries store data in key–value pairs and allow all these operations easily.

Example Program 1:
# Program: Demonstrate CRUD operations on a dictionary

# CREATE: Creating a dictionary with initial key-value pairs


student = {"name": "Rahul", "age": 20, "marks": 85}
print("Initial Dictionary:", student)

# READ: Accessing and displaying specific values using keys


print("Name:", student["name"])
print("Marks:", student["marks"])

# UPDATE: Adding a new key-value pair to the dictionary


student["age"] = 21 # Updates 'age' from 20 to 21
student["branch"] = "CSE" # Adds 'branch' with value 'CSE'
print("After Update:", student)

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 111 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

# DELETE: Removing a key-value pair using del


del student["marks"] # Delete a key-value pair
print("After Deletion:", student)

# Removing a key-value pair using pop()


[Link]("branch")
print("After pop() Deletion:", student)

Output:
Initial Dictionary: {'name': 'Rahul', 'age': 20, 'marks': 85}
Name: Rahul
Marks: 85
After Update: {'name': 'Rahul', 'age': 21, 'marks': 85, 'branch': 'CSE'}
After Deletion: {'name': 'Rahul', 'age': 21, 'branch': 'CSE'}
After pop() Deletion: {'name': 'Rahul', 'age': 21}

Step-by-Step Explanation:
1. CREATE:
 The dictionary student is created with keys "name", "age", and
"marks".
 New items can also be added later:
student["branch"] = "CSE"
2. READ:
 Access values using their keys:
student["name"] → "Rahul"
3. UPDATE:
 Modify values of existing keys:
student["age"] = 21
 Add new key–value pairs:
student["branch"] = "CSE"
4. DELETE:
 Remove keys using del or pop():
del student["marks"] removes the "marks" key.
[Link]("branch") removes "branch" and returns its value.

Summary Table: CRUD


Operation Description Example
Create Add key–value pairs student = {"name": "Rahul", "age": 20}
Read Access values by keys student["name"]
Update Modify or add entries student["age"] = 21
Delete Remove entries del student["marks"] or pop("key")

b. Explain commonly used string methods in Python. Write a program using


the following operations on the given string:
text = " Machine Learning "
Use the following methods
 lower()
 upper()
 strip()
 replace()
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 112 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

 find()
 count()

Solution:
A string in Python is a sequence of characters enclosed in single quotes (‘ ’), double
quotes (“ ”), or triple quotes (‘’’ ’’’). Strings are immutable, meaning their contents
cannot be changed once created.
Example:
text = "Python Programming"

Python provides many built-in string methods that return new strings after
performing operations such as conversion, searching, replacing, and formatting.

Purpose of String Methods


String methods are used for:
 Changing letter cases (uppercase/lowercase)
 Removing or replacing characters
 Searching for substrings
 Counting occurrences
 Checking content type (digits, alphabets, spaces, etc.)

Commonly used string methods:


Method Description Example Output
Converts all letters to
upper() "hello".upper() 'HELLO'
uppercase
Converts all letters to
lower() "HELLO".lower() 'hello'
lowercase
Converts first letter of 'Python
title() "python language".title()
each word to uppercase Language'
Converts first character
capitalize() "python".capitalize() 'Python'
of the string to uppercase
Removes extra spaces
strip() " hello ".strip() 'hello'
from start and end
replace(old, Replaces all occurrences "Hi ‘Hi
new) of old substring with new Rahul".replace("Rahul","Mayank") Mayank'
Returns index of first
find(sub) "banana".find("na") 2
occurrence of substring
Counts how many times
count(sub) "banana".count("a") 3
substring appears
Returns True if string
startswith(sub) "apple".startswith("a") True
starts with substring
Returns True if string
endswith(sub) "apple".endswith("e") True
ends with substring
Splits string into list
split() "a b c".split() ['a','b','c']
using spaces or delimiter
Joins list elements into
join() " ".join(['a','b','c']) 'a b c'
one string
Returns True if all
isdigit() "123".isdigit() True
characters are digits
Returns True if all
isalpha() "abc".isalpha() True
characters are alphabets
Returns True if all are
isalnum() "abc123".isalnum() True
alphabets or digits

Example Program:

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 113 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

text = " Machine Learning "

print("Original String:", repr(text))


print("1. lower() →", [Link]())
print("2. upper() →", [Link]())
print("3. strip() →", [Link]())
print("4. replace() →", [Link]("Machine", "Deep"))
print("5. find() →", [Link]("Learning"))
print("6. count('n') →", [Link]("n"))

Output:
Original String: ' Machine Learning '
1. lower() → machine learning
2. upper() → MACHINE LEARNING
3. strip() → Machine Learning
4. replace() → Deep Learning
5. find() →9
6. count('n') → 2

Explanation:
1. lower() → changes all letters to small letters.
→ Output: machine learning
2. upper() → changes all letters to capital letters.
→ Output: MACHINE LEARNING
3. strip() → removes extra spaces at the beginning and end.
→ Output: Machine Learning
4. replace("Machine", "Deep") → replaces the word "Machine" with
"Deep".
→ Output: Deep Learning
5. find("Learning") → tells where the word "Learning" starts in the string.
→ Output: 9
6. count("n") → counts how many times the letter n appears.
→ Output: 2

Q.4. Attempt any one part of the following: (7M X 1 = 7M)


a. How can data be organized using complex data types in Python?

Solution:
In Python, complex data types are data structures that can store multiple values or organize data
in more structured and flexible ways than simple data types like int, float, or bool.

Figure 1: Complex Data Types in Python


AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 114 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

String
A string is a sequence of characters enclosed in single (' '), double (" "), or
triple (''' ''') quotes.
 It is ordered and immutable (cannot be changed once created).
Syntax:
string_variable = "Hello World"
Example:
name = "Rahul"
print(name[0]) # Access first character
print([Link]()) # Convert to uppercase

Output:
R
RAHUL

List
 A list stores multiple items in square brackets [ ].
 It is ordered and mutable (elements can be changed).
 Can hold different data types.

Syntax:
list_variable = [item1, item2, item3]
Example:
fruits = ["apple", "banana", "cherry"]
[Link]("orange") # Add element
print(fruits)

Output:
['apple', 'banana', 'cherry', 'orange']

Tuple
 A tuple is similar to a list but immutable (cannot be changed).
 Defined using parentheses ( ).
 Useful when data should not change.

Syntax:
tuple_variable = (item1, item2, item3)
Example:
coordinates = (10, 20, 30)
print(coordinates[1]) # Access second item

Output:
20

Set
 A set is an unordered collection of unique elements.
 Defined using curly braces { }.
 Automatically removes duplicates.

Syntax:
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 115 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

set_variable = {item1, item2, item3}


Example:
colors = {"red", "green", "blue", "red"}
print(colors) # Duplicate "red" removed

Output:
{'green', 'blue', 'red'}

Dictionary
 A dictionary stores data as key–value pairs inside { }.
 Keys must be unique, and values can be of any type.

Syntax:
dict_variable = {key1: value1, key2: value2}
Example:
student = {"name": "Rahul", "age": 20, "branch": "CSE"}
print(student["name"]) # Access value by key

Output:
Rahul

Example Program showing complex data types

# Different complex data types


text = "Hello" # String
marks = [85, 90, 95] # List
grades = ("A", "B", "A+") # Tuple
subjects = {"Math", "Science", "English"} # Set
student = {"name": "Rahul", "age": 20} # Dictionary

print(text)
print(marks)
print(grades)
print(subjects)
print(student)

Output:
Hello
[85, 90, 95]
('A', 'B', 'A+')
{'Math', 'Science', 'English'}
{'name': 'Rahul', 'age': 20}

Characteristics of Complex Data Types


Feature string list tuple set dict
Ordered Yes Yes Yes No Yes (Python 3.7+)
Mutable No Yes No Yes Yes
Allows Duplicates Yes Yes Yes No No (keys must be unique)
Indexing / Slicing Yes Yes Yes No No (access via keys)
Data Representation " " or ' ' [ ] ( ) { } {key: value}

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 116 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

b. Explain file handling modes in Python.

Solution:
File Modes in Python
 File modes in Python tell the program how a file should be opened and
what kind of operation can be performed on it such as reading, writing,
or appending data.
 When we open a file using the open() function, we specify the mode as a
string argument.

Syntax: open()
file_object = open("filename", "mode")
 Here, the file name is "[Link]" and the mode describes how the file will be
opened (read, write, append, etc.).
 After all operations, the file must be closed using the close() method.

Syntax: close()
file_object.close()

The best practice to open the file is with open statement so the file closes
automatically:

Syntax: with open


with open("filename", "mode") as file:
# file operations
Using with automatically closes the file when the block ends no need to call close()
manually.

Types of File Modes in Python:


Creates
Mode Operation Type Description
File?
'r' Read Opens file for reading only (file must exist). No
'w' Write Opens file for writing. Overwrites file if it exists. Yes
'a' Append Opens file for appending new data to the end. Yes
Creates a new file. Gives error if file already
'x' Create Yes
exists.
'r+' Read & Write Opens file for both reading and writing. No
'w+' Write & Read Overwrites existing file or creates new one. Yes
'a+' Append & Read Opens file for reading and appending data. Yes
'b' Binary Used for binary files (images, videos, etc.). -
't' Text Default mode for text files. -

1. Read Mode ('r'):


Used when you only want to read data from a file.
Example Program:
If [Link] file already contains: Hello Rahul
file = open("[Link]", "r")
print([Link]())
[Link]()
The file content of [Link] contains after running the program: Hello Rahul

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 117 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

Note: File must already exist, otherwise an error occurs.

2. Write Mode ('w'):


Used to create a new file or overwrite an existing one.
Example Program:
If [Link] file already contains: XXXXXX
file = open("[Link]", "w")
[Link]("Hello Rahul")
[Link]()
The file content of [Link] contains after running the program: Hello Rahul
Note: Existing content is erased.

3. Append Mode ('a'):


Used to add new data at the end of an existing file.
Example Program:
If [Link] file already contains: Hi
file = open("[Link]", "a")
[Link]("\nHello Rahul")
[Link]()
The file content of [Link] contains after running the program:
Hi
Hello Rahul
Note: Existing content is not erased.

4. Create Mode ('x'):


Used to create a new file. Gives an error if the file already exists.
Example Program:
If [Link] file already contains: Hi
file = open("[Link]", "x")
[Link]("Hello Rahul")
[Link]()
The file content of [Link] contains after running the program, file becomes:
FileExistsError
Note:
 If file already exists → ❌ FileExistsError.
 'x' mode fails if the file already exists.

5. Read + Write Mode ('r+'):


Used to both read and write data in the same file.
Example Program:
If [Link] file already contains: Hello Rahul
file = open("[Link]", "r+")
print("Before:", [Link]())
[Link]("\nHello Rahul")
[Link]()
Note: File must already exist.
(Assuming [Link] initially contains Hello Rahul.)

6. Write + Read Mode ('w+'):


Used to write and then read a file. It overwrites the existing file.

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 118 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

Example Program:
If [Link] file already contains: Hello Rahul
file = open("[Link]", "w+")
[Link]("Hello Rahul")
[Link](0)
print([Link]())
[Link]()
Output:
Hello Rahul
Note: seek(0) moves the file pointer to the beginning for reading.

7. Append + Read Mode ('a+'):


Used to append data and read from the same file.
Example Program:
file = open("[Link]", "a+")
[Link]("\nHello Rahul")
[Link](0)
print([Link]())
[Link]()
(Result in file will include one more “Hello Rahul” at the end.)

8. Binary Modes ('rb', 'wb'):


(Used for binary files like images, videos, or audio files.
Example Program:
# Write bytes
with open("[Link]", "wb") as f:
[Link](b"Hello Rahul")

# Read bytes
with open("[Link]", "rb") as f:
data = [Link]()
print(data)
Output:
b'Hello Rahul'
Note: Binary modes handle raw bytes. Typically used for images or media files.

9. Using with (Recommended Method):


Automatically closes the file after the block finishes.
Example Program:
with open("[Link]", "w") as f:
[Link]("Hello Rahul")
The file closes automatically after the block finishes.

Q.5. Attempt any one part of the following: (7M X 1 = 7M)


a. Write a program to read and write data from a text file. How do readline()
and readlines() work? Explain with examples.

Solution:

Method-1: Program to Read and Write Data from a Text File using with open

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 119 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

# ----- WRITE DATA TO FILE -----


with open("[Link]", "w") as f:
[Link]("Hello Rahul\n")
[Link]("Welcome to Python file handling.\n")
[Link]("Have a great day!")

# ----- READ DATA FROM FILE -----


with open("[Link]", "r") as f:
content = [Link]()
print("File Content:\n", content)

Output:
(File Content)
Hello Rahul
Welcome to Python file handling.
Have a great day!

Explanation
 open("[Link]", "w")
Opens the file in write mode.
 If [Link] does not exist → it will be created.
 If it already exists → its old content will be erased and replaced.
 [Link](...)
Writes lines of text into the file.
\n is used to move to the next line.
 open("[Link]", "r")
Opens the same file in read mode.
 [Link]()
Reads the entire file content as one string.
 with open(...) as f:
This is the with statement.
It automatically closes the file after the block finishes.
You do not need to call close() manually.

Method-2: Program to Write and Read from a Text File

# Step 1: Write data to a file


file = open("[Link]", "w") # open file in write mode
[Link]("Hello Rahul\n")
[Link]("Welcome to Python file handling.\n")
[Link]("Have a great day!")
[Link]() # always close the file

# Step 2: Read data from the same file


file = open("[Link]", "r") # open file in read mode
content = [Link]() # read entire file content
print("File Content:\n")
print(content)
[Link]() # close after reading

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 120 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

Output:
(File Content)

Hello Rahul
Welcome to Python file handling.
Have a great day!

Explanation:
1. open("[Link]", "w")
 Opens (or creates) the file [Link] in write mode.
 "w" will overwrite the file if it already exists.
2. [Link](...)
 Writes text into the file.
 \n is a newline (go to next line).
3. [Link]()
 Saves the file and releases it. Always close after writing.
4. open("[Link]", "r")
 Opens the same file again, but this time in read mode.
5. [Link]()
 Reads the entire file as one string.
6. print(content)
 Displays the file content on the screen.
7. Close again after reading.

readline() and readlines() in python:


Both methods are used to read data from a text file, but they behave differently:

readline() Method
 Reads one line at a time from the file.
 Each call returns the next line as a string.
 Useful when reading large files line-by-line.

Syntax:
[Link]()

Example: Program to Read using readline()

# Create and write to file


with open("[Link]", "w") as f:
[Link]("Hello Rahul\n")
[Link]("Welcome to Python\n")
[Link]("Have a great day!\n")

# Read using readline()


with open("[Link]", "r") as f:
print([Link]()) # Reads first line
print([Link]()) # Reads second line

Output:
Hello Rahul
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 121 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

Welcome to Python

Explanation:
 The first readline() reads "Hello Rahul".
 The second readline() reads "Welcome to Python".
 Each call reads only one line until the end of file.

readlines() Method:
 Reads all lines at once and returns them as a list of strings.
 Each line is an element in the list.
 Useful when you want to process the entire file at once.

Example: Program using readlines()


# Create and write to file
with open("[Link]", "w") as f:
[Link]("Hello Rahul\n")
[Link]("Welcome to Python\n")
[Link]("Have a great day!\n")

# Read using readlines()


with open("[Link]", "r") as f:
lines = [Link]() # Reads all lines into a list
print(lines)

Output:
['Hello Rahul\n', 'Welcome to Python\n', 'Have a great day!\n']

Explanation:
1. The file [Link] is created and three lines are written to it.
2. [Link]() reads all lines at once and stores them in a list.
3. Each element in the list is one line from the file.
4. The \n shows the newline character (end of each line).

b. What is the purpose of the seek() method in file handling? Demonstrate a


program that copies content from one file to another.

Solution:
 The purpose of the seek() method in file handling in Python is to move
the file pointer (cursor) to a specific position within a file.
 It allows the program to read or write data from any desired location
instead of only starting from the beginning of the file.

Syntax
[Link](offset, whence)

 offset: Number of bytes to move the pointer.


 whence (optional): Reference point for movement.
 0 → from the beginning of the file (default)
 1 → from the current position
 2 → from the end of the file

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 122 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

Example: Program demonstrating seek() operation

# Create and write to a file


with open("[Link]", "w") as f:
[Link]("Hello Rahul, Welcome to Python!")

# Read first 5 characters, then move back and read again


with open("[Link]", "r") as f:
print([Link](5)) # Reads first 5 characters
[Link](0) # Moves cursor to beginning
print([Link](10)) # Reads first 10 characters again

Output:
Hello
Hello Rahu

Explanation:
 When a file is opened, the cursor starts at position 0 (beginning).
 read(5) → reads first 5 characters and moves the cursor forward.
 seek(0) → moves the cursor back to the start.
 The next read(10) starts reading again from the beginning.

Program that copies content from one file to another.

Example 1:
# Step 1: Create [Link] and write some text into it
with open("[Link]", "w") as f1:
[Link]("Hello Students!\n")
[Link]("Welcome to ECE department JSSATE Noida\n")

# Step 2: Copy content from [Link] to [Link]


with open("[Link]", "r") as f1, open("[Link]", "w") as f2:
data = [Link]() # Read everything from [Link]
[Link](data) # Write that data into [Link]

print("Copy done!")

Output:
Copy done!

And the content of [Link] will be:


Hello Students!
Welcome to ECE department JSSATE Noida

Explanation
 [Link] is created and two lines are written:
 "Hello Students!"
 "Welcome to ECE department JSSATE Noida"
 We open [Link] (read mode "r") and [Link] (write mode "w").
 We read all text from [Link] into data.
 We write data into [Link].
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 123 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

 Then we print Copy done! to show the task is finished.

Example 2: Program using seek() while copying file content

# Step 1: Create [Link] and write some content


with open("[Link]", "w") as f1:
[Link]("Hello Students!\n")
[Link]("Welcome to ECE department JSSATE Noida\n")

# Step 2: Open the same file for reading and another for writing
with open("[Link]", "r") as f1, open("[Link]", "w") as f2:
[Link](0) # Move the file pointer to the beginning
data = [Link]() # Read content from start
[Link](data) # Write to new file

print("File copied successfully using seek()!")

Output:
File copied successfully using seek()!

Content of [Link]
Hello Students!
Welcome to ECE department JSSATE Noida

Explanation:
 The file [Link] is created and text is written.
 seek(0) moves the file pointer back to the beginning of the file before
reading.
 The entire content is then read and written into [Link].
 The message confirms that copying was successful.

Q.6. Attempt any one part of the following: (7M X 1 = 7M)


a. Write a Python program using numpy to perform matrix operations.
Solution:

Example 1: Matrix Operations Using NumPy (2×2)

import numpy as np

# Create two matrices


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

y = [Link]([ [1, 2],


[3, 4]])

print("Matrix x:\n", x)
print("Matrix y:\n", y)

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 124 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

# Matrix Addition
add = x + y
print("\nAddition of x and y:\n", add)

# Matrix Subtraction
sub = x - y
print("\nSubtraction of x and y:\n", sub)

# Matrix Multiplication (element-wise)


mul = x * y
print("\nElement-wise Multiplication of x and y:\n", mul)

# Matrix Division (element-wise)


divide = x / y
print("\nElement-wise Division of x and y:\n", divide)

# Transpose of a Matrix
trans = x.T
print("\nTranspose of Matrix x:\n", trans)

Output:
Matrix x:
[[1 2]
[3 4]]
Matrix y:
[[1 2]
[3 4]]

Addition of x and y:
[[ 2 4]
[ 6 8]]

Subtraction of x and y:
[[0 0]
[0 0]]

Element-wise Multiplication of x and y:


[[ 1 4]
[ 9 16]]

Element-wise Division of x and y:


[[1. 1.]
[1. 1.]]

Transpose of Matrix x:
[[1 3]
[2 4]]

Explanation:
1. [Link]() creates 2×2 matrices.
2. x + y adds elements of both matrices.
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 125 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

3. x - y subtracts elements of y from x.


4. x * y multiplies corresponding elements (not matrix multiplication).
5. x / y divides corresponding elements.
6. x.T gives the transpose of x (rows become columns).

OR

Example 2: Matrix Operations Using NumPy (3×3)

import numpy as np

# ----- CREATE MATRICES -----


X = [Link]([[2, 4, 6], [1, 3, 5], [7, 8, 9]])

Y = [Link]([[9, 8, 7], [6, 5, 4], [3, 2, 1]])

print("Matrix X:\n", X)
print("Matrix Y:\n", Y)

# ----- ELEMENT-WISE MULTIPLICATION -----


elementwise = X * Y
print("\nElement-wise Multiplication (X * Y):\n", elementwise)

# ----- MATRIX MULTIPLICATION -----


matrix_mul = [Link](X, Y)
print("\nMatrix Multiplication (X @ Y):\n", matrix_mul)

# ----- TRANSPOSE -----


transpose_Y = Y.T
print("\nTranspose of Y:\n", transpose_Y)

# ----- DETERMINANT -----


det_X = [Link](X)
print("\nDeterminant of X:", round(det_X, 2))

Output:

Matrix X:
[[2 4 6]
[1 3 5]
[7 8 9]]
Matrix Y:
[[9 8 7]
[6 5 4]
[3 2 1]]

Element-wise Multiplication (X * Y):


[[18 32 42]
[6 15 20]
[21 16 9]]

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 126 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

Matrix Multiplication (X @ Y):


[[60 48 36]
[42 33 24]
[150 126 102]]

Transpose of Y:
[[9 6 3]
[8 5 2]
[7 4 1]]

Determinant of X: 6.0

Explanation
 X * Y → Element-wise multiplication.
 [Link](X, Y) → Matrix multiplication.
 Y.T → Transpose of matrix Y.
 [Link](X) → Determinant of matrix X.

b. Explain the use of matplotlib for data visualization. Write a program to


visualize Line plots using these data:
x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 40]
Solution:

import [Link] as plt

# Given data
x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 40]

# Plot line graph


[Link](x, y)

# Add labels and title


[Link]("X values")
[Link]("Y values")
[Link]("Simple Line Plot")

# Show the graph


[Link]()

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 127 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

Q.7. Attempt any one part of the following: (7M X 1 = 7M)

a. What is GUI programming in Python? Write a GUI-based Python program


using Tkinter to accept and display student data.

Solution:

GUI programming:
 GUI stands for Graphical User Interface.
 GUI programming in Python means creating windows, buttons, labels,
text boxes, menus, and other visual elements that allow users to
interact with a program easily instead of typing commands in the
console.

Purpose of GUI:
 The main purpose of GUI programming is to make applications user-
friendly and interactive.
It allows users to input data, click buttons, view messages, and perform
tasks visually.

Python GUI Library:


Python provides a built-in module called Tkinter for GUI programming.
It is one of the simplest and most commonly used libraries for building desktop
applications.
Other Popular GUI Libraries in Python:
Library Description
Advanced GUI toolkit based on Qt framework; supports
PyQt
complex interfaces
Used for multi-touch applications and mobile-friendly
Kivy
GUIs
wxPython Native-looking GUI toolkit for desktop apps

Key Features of GUI Applications:


 User-friendly interface
 Interactive components (buttons, forms, sliders)
 Event-driven (responds to user actions like clicks or typing)
 Used in desktop apps, tools, and educational software

GUI-based Python program using Tkinter to accept and display student data

# GUI Program to accept and display student data


from tkinter import *

def display_data():
name = name_entry.get()
roll = roll_entry.get()
branch = branch_entry.get()
result_label.config(text=f"Name: {name}\nRoll No: {roll}\nBranch: {branch}")

# Create main window


AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 128 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

root = Tk()
[Link]("Student Data Entry")
[Link]("300x250")

# Labels and Entry widgets


Label(root, text="Enter Student Details", font=("Arial", 14,
"bold")).pack(pady=10)

Label(root, text="Name:").pack()
name_entry = Entry(root)
name_entry.pack()

Label(root, text="Roll No:").pack()


roll_entry = Entry(root)
roll_entry.pack()

Label(root, text="Branch:").pack()
branch_entry = Entry(root)
branch_entry.pack()

# Button to display data


Button(root, text="Display Data", command=display_data,
bg="lightblue").pack(pady=10)

# Label to show the output


result_label = Label(root, text="", font=("Arial", 12))
result_label.pack()

[Link]()

Output:

b. How do we use packages in Python programming? Explain the use of pandas.


Solution:

Packages in Python:

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 129 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

A package in Python is a collection of modules (Python files) that are grouped


together to organize related functions, classes, and variables.
Packages help to:
 Reuse code easily
 Keep programs organized
 Avoid name conflicts

A package usually contains a special file named __init__.py, which tells Python that
this directory is a package.

Using Packages
To use a package in Python, we import it using the import statement.

Syntax:
import package_name
or
from package_name import module_name

Example:
import math
print([Link](25))

This imports the math package and uses its sqrt() function to find the square root
of 25.

Pandas:
Pandas is a powerful Python package used for data handling, data analysis, and
data manipulation. It is widely used in data science and machine learning.
Pandas provides two main data structures:
1. Series – one-dimensional (like a list or column)
2. DataFrame – two-dimensional (like a table with rows and columns)

Applications of Pandas:
 To handle large data sets easily
 To perform operations like filtering, sorting, merging, and grouping
 To read and write data from files like CSV, Excel, or SQL

Example 1: Program to Create and Display a DataFrame using pandas in


Python

import pandas as pd

# Create a DataFrame
data = {
'Name': ['Rahul', 'Vimal', 'Rakesh'],
'Age': [35, 48, 37],
'Branch': ['ECE', 'CSE', 'ECE']
}

df = [Link](data)

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 130 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

# Display the DataFrame


print(df)

Output:
Name Age Branch
0 Rahul 35 ECE
1 Vimal 48 CSE
2 Rakesh 37 ECE

OR

Example 2: Program Demonstrating pandas Operations in Python

import pandas as pd
# Create a DataFrame
data = {
'Name': ['Rahul', 'Vimal', 'Rakesh'],
'Age': [35, 48, 37],
'Branch': ['ECE', 'CSE', 'ECE']
}

df = [Link](data)

# Display the original DataFrame


print("Original DataFrame:\n", df)

# 1. Display only one column (Age)


print("\n 1 Display Age column:")
print(df['Age'])

# 2. Display multiple columns (Name and Branch)


print("\n 2 Display Name and Branch columns:")
print(df[['Name', 'Branch']])

# 3. Filter rows where Branch is 'ECE'


print("\n 3 Students from ECE branch:")
print(df[df['Branch'] == 'ECE'])

# 4. Add a new row to the DataFrame


new_row = {'Name': 'Suresh', 'Age': 42, 'Branch': 'EEE'}
df = [Link]([df, [Link]([new_row])], ignore_index=True)
print("\n 4 After adding a new student record:")
print(df)

# 5. Sort data by Age


sorted_df = df.sort_values(by='Age')
print("\n 5 Data sorted by Age:")
print(sorted_df)

# 6. Display basic information about the DataFrame


print("\n 6 DataFrame Information:")
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 131 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

print([Link]())

Output
Original DataFrame:
Name Age Branch
0 Rahul 35 ECE
1 Vimal 48 CSE
2 Rakesh 37 ECE

1 Display Age column:


0 35
1 48
2 37
Name: Age, dtype: int64

2 Display Name and Branch columns:


Name Branch
0 Rahul ECE
1 Vimal CSE
2 Rakesh ECE

3 Students from ECE branch:


Name Age Branch
0 Rahul 35 ECE
2 Rakesh 37 ECE

4 After adding a new student record:


Name Age Branch
0 Rahul 35 ECE
1 Vimal 48 CSE
2 Rakesh 37 ECE
3 Suresh 42 EEE
5 Data sorted by Age:
Name Age Branch
0 Rahul 35 ECE
2 Rakesh 37 ECE
3 Suresh 42 EEE
1 Vimal 48 CSE

6 DataFrame Information:
<class '[Link]'>
RangeIndex: 4 entries, 0 to 3
Data columns (total: 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Name 4 non-null object
1 Age 4 non-null int64
2 Branch 4 non-null object
dtypes: int64(1), object(2)
memory usage: 224.0 bytes
None
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 132 of 133
Success Mantra for Python Programming BCC-301 & BCC-401

Explanation:
 [Link]() → creates a table from dictionary data
 df['Age'] → displays one column
 df[['Name','Branch']] → shows specific columns
 df[df['Branch']=='ECE'] → filters only ECE students
 [Link]() → adds new rows
 df.sort_values(by='Age') → sorts records
 [Link]() → shows structure and data types

AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 133 of 133

You might also like