Python Programming Success Mantra Guide
Python Programming Success Mantra Guide
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]
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 2 of 133
Success Mantra for Python Programming BCC-301 & BCC-401
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.
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 3 of 133
Success Mantra for Python Programming BCC-301 & BCC-401
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
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 5 of 133
Success Mantra for Python Programming BCC-301 & BCC-401
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
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()
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 9 of 133
Success Mantra for Python Programming BCC-301 & BCC-401
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
This single line [x**2 for x in numbers] replaces the 3 lines of the for loop.
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
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&.
File 1: [Link]
# [Link]
# This file contains some useful functions
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 12 of 133
Success Mantra for Python Programming BCC-301 & BCC-401
File 2: [Link]
# [Link]
# This file uses the functions from [Link]
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.
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 13 of 133
Success Mantra for Python Programming BCC-301 & BCC-401
Purpose
Matplotlib (Visualization) Pandas (Data Manipulation)
Creates visual representations of data Organizes, cleans, and analyzes tabular data
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
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.
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 14 of 133
Success Mantra for Python Programming BCC-301 & BCC-401
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.
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.
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]
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.
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
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.
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
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,!,!
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.
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 20 of 133
Success Mantra for Python Programming BCC-301 & BCC-401
Solution:
# 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
# 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
SECTION C
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 22 of 133
Success Mantra for Python Programming BCC-301 & BCC-401
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"
Solution:
METHOD-1: Sort words even if separated by commas and/or spaces
text = input("Enter words (use commas and/or spaces): ")
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
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
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.
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.
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 26 of 133
Success Mantra for Python Programming BCC-301 & BCC-401
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
Solution:
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 28 of 133
Success Mantra for Python Programming BCC-301 & BCC-401
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']
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:
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.
Solution:
Print Words Made of Digits Only from a File (Methos-1: Using .txt file)
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 32 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.
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
[Link](figsize=(8, 5))
[Link](population, temperature, color='blue', s=100,
edgecolors='black')
[Link]('Population vs Temperature')
[Link]('Population')
[Link]('Temperature (°C)')
[Link](True, alpha=0.5)
plt.tight_layout()
[Link]()
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.
b. Design a calculator with the following buttons and functionalities like addition,
subtraction, multiplication, division and clear.
Solution:
import tkinter as tk
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 37 of 133
Success Mantra for Python Programming BCC-301 & BCC-401
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
[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.
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
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.
Syntax:
def function_name(parameters):
# block of code
return value
Example
def greet():
print("Hello, welcome to Python!")
Output:
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")
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.
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:
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.
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.
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 48 of 133
Success Mantra for Python Programming BCC-301 & BCC-401
𝒂×𝒃
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
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.
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.
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
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.
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.
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:
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
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
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)
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()
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.
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.
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.
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
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.
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
def count_up_to(n):
for i in range(1, n + 1):
yield i # yields one value at a time
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
Solution:
Example:
[Link](10, 51, size=5) generates 5 random integers between 10
and 50 (since upper limit 51 is exclusive).
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 60 of 133
Success Mantra for Python Programming BCC-301 & BCC-401
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.
Solution:
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 61 of 133
Success Mantra for Python Programming BCC-301 & BCC-401
OR
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)
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
Solution:
Flow diagram:
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
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).
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.
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
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
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.
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).
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.
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
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
# 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.
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
SECTION B
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
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
def calculator():
print("Basic Calculator")
print("Operations: + - * /")
# 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")
calculator()
OUTPUT:
Basic Calculator
Operations: + - * /
Enter first number: 10
Enter operator (+, -, *, /): *
Enter second number: 5
Result: 50.0
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.
Syntax:
value in sequence
value not in sequence
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
a == b → Compares values.
3 == 3 → True
However, for larger numbers or objects, this may differ and is shown in below
example
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 72 of 133
Success Mantra for Python Programming BCC-301 & BCC-401
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.
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.
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
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
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 75 of 133
Success Mantra for Python Programming BCC-301 & BCC-401
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.
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')
Output:
[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
[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
Example:
print(2 + 3 * 4) # 14 (multiplication first)
print((2 + 3) * 4) # 20 (parentheses first)
Output:
14
20
Example:
if True:
print("Indented block") # This line is inside the if-block
print("Outside block") # This line is outside the if-block
Type conversion refers to changing a value from one data type to another.
Solution:
Method-1: User Input–based Email Validation (Regex)
import re # Import regular expression module
Note:
The part [a-zA-Z]{2,} means the domain extension (like .com, .org, .in, .edu) must have
at least two letters.
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]):
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.
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.
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 83 of 133
Success Mantra for Python Programming BCC-301 & BCC-401
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.
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 84 of 133
Success Mantra for Python Programming BCC-301 & BCC-401
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.
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):
# 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
Example: tuple
my_tuple = (10, 20, 30)
print("Tuple:", my_tuple)
Example Dictionary
student = {"name": "Rahul", "age": 20, "branch": "ECE"}
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 87 of 133
Success Mantra for Python Programming BCC-301 & BCC-401
# 1. len()
print("1. Length:", len(d))
# 2. sorted()
print("2. Sorted keys:", sorted(d))
# 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
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:
print("Before:", [Link]())
[Link]("\nHello Rahul")
[Link]()
Note: File must already exist.
(Assuming [Link] initially contains Hello Rahul.)
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.
# 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.
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
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
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 92 of 133
Success Mantra for Python Programming BCC-301 & BCC-401
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.
Syntax:
[Link]("<event>", handler_function)
Example:
[Link]()
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
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).
print("Student Averages:")
for row in reader:
name = row["Name"]
# Calculate average
avg = (math + sci + eng) / 3
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.
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
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
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
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
Example Program:
a, b = 10, 5
print(a + b) # 15
print(a > b) # True
print(a != b) # True
Output:
15
True
True
Example:
# Numeric data types
a=5 # Integer data type
b = 4.5 # Float data type
c = 1 + 2j # Complex data type
print(a)
print(b)
print(c)
print("String:", name)
Output:
5
4.5
(1+2j)
String: Python
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).
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:
if condition1:
# code if condition1 is true
elif condition2:
# code if condition2 is true
else:
# code if none of the conditions are true
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.
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.
SECTION B
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
while condition:
pass # Placeholder for future logic
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
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.
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).
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:
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 105 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 (''' ''' 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]
text = "PYTHON"
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"
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.
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.
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.
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
Syntax:
variable = (item1, item2, item3)
Example:
my_tuple= (35, 45, 55)
# Modifying list
my_list[2] = 99
print("Modified List:", my_list)
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.
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
SECTION C
Dictionaries store data in key–value pairs and allow all these operations easily.
Example Program 1:
# Program: Demonstrate CRUD operations on a dictionary
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 111 of 133
Success Mantra for Python Programming BCC-301 & BCC-401
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.
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.
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
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
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.
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
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
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}
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 116 of 133
Success Mantra for Python Programming BCC-301 & BCC-401
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:
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 117 of 133
Success Mantra for Python Programming BCC-301 & BCC-401
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.
# 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.
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
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.
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() 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]()
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.
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).
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)
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 122 of 133
Success Mantra for Python Programming BCC-301 & BCC-401
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.
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")
print("Copy done!")
Output:
Copy done!
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
# 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
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.
import numpy as np
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)
# 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]]
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
OR
import numpy as np
print("Matrix X:\n", X)
print("Matrix Y:\n", Y)
Output:
Matrix X:
[[2 4 6]
[1 3 5]
[7 8 9]]
Matrix Y:
[[9 8 7]
[6 5 4]
[3 2 1]]
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 126 of 133
Success Mantra for Python Programming BCC-301 & BCC-401
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.
# Given data
x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 40]
AKTU Previous Year Question Paper Solution: 2023-24 Odd Semester Page 127 of 133
Success Mantra for Python Programming BCC-301 & BCC-401
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.
GUI-based Python program using Tkinter to accept and display student data
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}")
root = Tk()
[Link]("Student Data Entry")
[Link]("300x250")
Label(root, text="Name:").pack()
name_entry = Entry(root)
name_entry.pack()
Label(root, text="Branch:").pack()
branch_entry = Entry(root)
branch_entry.pack()
[Link]()
Output:
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 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
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
Output:
Name Age Branch
0 Rahul 35 ECE
1 Vimal 48 CSE
2 Rakesh 37 ECE
OR
import pandas as pd
# Create a DataFrame
data = {
'Name': ['Rahul', 'Vimal', 'Rakesh'],
'Age': [35, 48, 37],
'Branch': ['ECE', 'CSE', 'ECE']
}
df = [Link](data)
print([Link]())
Output
Original DataFrame:
Name Age Branch
0 Rahul 35 ECE
1 Vimal 48 CSE
2 Rakesh 37 ECE
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