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

Python Programming Test Solutions

The document outlines the B. Tech Odd Semester Sessional Test-2 for Python Programming at ABES Engineering College, detailing the structure, instructions, and various questions related to Python concepts such as sets, strings, lists, and loops. It includes programming tasks requiring students to demonstrate their understanding of Python through coding examples and explanations. The test is divided into sections with specific marks allocated for each question, focusing on both theoretical and practical aspects of Python programming.

Uploaded by

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

Python Programming Test Solutions

The document outlines the B. Tech Odd Semester Sessional Test-2 for Python Programming at ABES Engineering College, detailing the structure, instructions, and various questions related to Python concepts such as sets, strings, lists, and loops. It includes programming tasks requiring students to demonstrate their understanding of Python through coding examples and explanations. The test is divided into sections with specific marks allocated for each question, focusing on both theoretical and practical aspects of Python programming.

Uploaded by

SONU KUMAR.
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

ABES Engineering College, Ghaziabad

B. Tech Odd Semester Sessional Test-2 Solution


Printed Pages:
Session: 2023-24
Semester: 3
Course Code: BCC302 Roll No.:
Course Name: Python Programming Time: 1.15 Hrs.
Maximum Marks: 30
Instructions:
1. Attempt All sections.
2. If require any missing data, then choose suitably.

Q. No. Question Ma CO KL PI
rks
Section-A Total Marks : 20
Same K Levels
1 Attempt ANY ONE part from the following
Questions
Explain the Set-in python. Elaborate the various built-in functions used
in set.
ANSWER
1. Set stores the unique values as data collection
2. Set is mutable (changeable)
3. Set is unordered
4. Set elements are enclosed in brackets { }
5. Set not allows duplicate elements.
6. Set can contain elements of different data types.
There are more than 15 Python set of built-in methods that can be used
on sets.
[Link]() Method
Python set add () method is used to add an element to the given input
a) set. If the element already exists, then the add () method does not add 2+3 CO3 K2 2.1.2
the element.
set. Add(element)
[Link]() Method
Python set update () method is used to update the current set by adding
items to it from another set. If an item is present in both sets then only
one appearance of this item will be present in the updated set.
set. Update(element)
3. Clear () method
Python set clear () method is used to remove all the elements in the given
input set.
set. clear ()
[Link] () method
Python set copy () method is used to copy the given input set.
set. copy ()
[Link] () method
Python Set pop () Method in python set is an inbuilt method which is
used to removes a random element from the set and returns the popped
(removed) elements.
set. Pop ()
[Link] () method
Python Set remove () Method in python set is used to remove the
specified element from the given set. This method will raise an error if
element does not exist in the set.
set. Remove(item)
7. Discard () method
Python set discard () method is used to remove the specified item from
the given input set. It is different from the remove () method because the
remove () method will give an error if the specified item does not exist
but this method will not.
set. Discard(value)
8. Len () method
The set Len is one of the set methods used to find the length of a set
(total number of items).

Explain the concept of string. Write a program to print number of


alphabets and digits in a given string.
ANSWER
[Link] is a sequence of alphanumeric and special character
2. Strings are created in many ways using single quotes or double-
quotes.
[Link] is immutable (changeable)
4. Strings element can be accessed using square [] brackets.
5. Single character is simply a string with a length of 1.

b) 2+3 CO3 K2 2.1.2


Same K Levels
2 Attempt ANY ONE part from the following
Questions
When to Use Python Lists. Write Python program to swap elements in
the list.
ANSWER
[Link] elements are enclosed in square brackets [] and are comma
separated.
[Link] is the sequence of class type ‘list’.
[Link] can contain elements of different data types.
[Link] is a mutable(changeable)
5. List allows duplicate elements.
[Link] elements are ordered, it means it give specific order to the
elements, if new element is added, by default it comes at the end of the
list.

a) 2+3 CO3 K2 1.3.1


Differentiate between mutable and immutable objects in Python
language with example.
ANSWER
mutable
[Link] object that allows you to change its values without
changing its identity is a mutable object.
[Link] objects are easy to change.
[Link] is More efficient
[Link] allocations of the object can change during its lifetime
[Link] a method to add or remove element
[Link] mutable data Types List, Set and Dictionary
Immutable
[Link] object that doesn’t allow changes in its value is
b) an immutable object 5 CO3 K2 1.3.1

[Link] objects are quicker to access


[Link] is Less efficient
[Link] allocations of the object remains Constant during its
lifetime
5. Does Not Provides a method to add or remove element
[Link] immutable data Types String, Tuples, Float and
Frozen set

Same K Levels
3 Attempt ANY ONE part from the following
Questions
(i) Write a program that merges two dictionaries and handles
duplicate keys intelligently.
ANSWER
d1 = {'k1': 1, 'k2': 2}
d2 = {'k1': 5, 'k3': 3, 'k4': 4}
d = d1 | d2
print(d)
d = d2 | d1
print(d)
Output
{'k1': 5, 'k2': 2, 'k3': 3, 'k4': 4}

{'k1': 1, 'k3': 3, 'k4': 4, 'k2': 2}

(ii) Write Python program to join two input tuples, if their first
5+
a) element is common. CO3 K3 3.2.2
5
ANSWER

Elaborate the importance of slicing in python. Provide the outputof


below code snippet:
S = 'ABCDEFGHI'
print(S[2:7])
print(S[-7:-2])
print(S[2:-5])
Soln:
In Python, slicing is a powerful feature that allows you to extract a
5+
b) portion of a sequence (like a string, list, or tuple). Slicing is done using CO3 K3 3.2.2
5
the syntax start:stop, where start is the index of the first element you
want to include, and stop is the index of the first element you want to
exclude. If start or stop is not specified, it defaults to the beginning or
end of the sequence, respectively. Additionally, you can use negative
indices to count from the end of the sequence.
Now, let's analyze the given code snippet:
S = 'ABCDEFGHI'
print(S[2:7]) # Extract elements from index 2 to 6 (7-1)
print(S[-7:-2]) # Extract elements from index -7 to -3 (-2+1)
print(S[2:-5]) # Extract elements from index 2 to -6 (-5+1)
print(S[2:7]): This will extract the elements from index 2 to 6
(inclusive), so the output will be 'CDEFG'.

print(S[-7:-2]): This will extract the elements from index -7 to -3


(inclusive), counting from the end of the string. The output will be
'CDEFG'.

print(S[2:-5]): This will extract the elements from index 2 to -6


(inclusive), so the output will be 'CDE'.

Now, let's run the code and check the output:


S = 'ABCDEFGHI'
print(S[2:7]) # Output: 'CDEFG'
print(S[-7:-2]) # Output: 'CDEFG'
print(S[2:-5]) # Output: 'CD'

A string is said to be a palindrome if the reverse of the string is the


same as the string. Consider the below examples:

1. Input: malayalam Output: Yes 2. Input: Python Output: No


Write a python program to check whether a string is palindrome or
not.
Soln:
# Test case 1
input_string1 = "malayalam"
# Convert the string to lowercase
input_string1 = input_string1.lower()
# Remove spaces from the string
input_string1 = ''.join(input_string1.split())
# Check if the string is a palindrome
if input_string1 == input_string1[::-1]:
print(f"Input: {input_string1} Output: Yes")
else:
print(f"Input: {input_string1} Output: No")

# Test case 2
input_string2 = "Python"
# Convert the string to lowercase
input_string2 = input_string2.lower()
# Remove spaces from the string
input_string2 = ''.join(input_string2.split())
# Check if the string is a palindrome
if input_string2 == input_string2[::-1]:
print(f"Input: {input_string2} Output: Yes")
else:
print(f"Input: {input_string2} Output: No")
Section-B Total Marks : 10

4 Attempt ANY ONE part from the following Same K Levels


Questions

Write a program to check if given input number is Armstrong


number or not.
Soln:
# Convert the number to a string to determine the number of digits
num_str = str(input_number)

# Calculate the power (number of digits)


power = len(num_str)
a) 5 CO2 K3 2.1.3
# Calculate the sum of each digit raised to the power
armstrong_sum = sum(int(digit) ** power for digit in num_str)

# Check if the sum is equal to the original number


if armstrong_sum == input_number:
print(f"{input_number} is an Armstrong number.")
else:
print(f"{input_number} is not an Armstrong number.")

Implement a program that prints the following pattern

2.1.
b) 5 CO2 K3
Soln: 3
rows = 5

for i in range(1, rows + 1):


for j in range(i):
print(i, end="")
print()
5 Attempt ANY ONE part from the following Same K Levels
Questions
Write short Note on
(i) Break
(ii) Continue
(iii) Pass
Soln:
(i) Break: The break statement is used in Python to exit from a loop
prematurely. When the break statement is encountered within a loop
(for example, for or while), the loop is terminated, and the program
continues with the next statement after the loop. It is often used with
conditional statements to exit a loop based on certain conditions.
Example:
Python code
for i in range(1, 10): if i == 5: break print(i)
In this example, the loop will print numbers from 1 to 4, and when i
becomes 5, the break statement is encountered, and the loop is
terminated.
(ii) Continue: The continue statement is used to skip the rest of the
code inside a loop for the current iteration and jump to the next
iteration. When the continue statement is encountered, the remaining
code within the loop for the current iteration is skipped, and the loop
proceeds with the next iteration.
Example:
Python code
for i in range(1, 6): if i == 3: continue print(i)
In this example, the loop will print numbers from 1 to 5, but when i is
3, the continue statement is encountered, and the print statement for 2+2
a) CO2 K2 2.1.2
that iteration is skipped. +1
(iii) Pass: The pass statement in Python is a no-operation statement. It
is often used as a placeholder where syntactically some code is
required, but no action is desired. It is essentially a null operation and
does nothing.
Example:
Python code
for i in range(5): if i == 2: pass else: print(i)
In this example, when i is 2, the pass statement is encountered, and no
action is taken. For other values of i, the loop will print the value of i.
Discuss the basic structure of a for loop and While Loop in Python. Why
is there no "do while" loop in Python?
Soln:
For Loop: The basic structure of a for loop in Python is as follows:

Python code
for variable in iterable: # code to be executed in each iteration
• The for keyword is used to start the loop.
• variable is the loop variable that takes on the values of the
elements in the iterable.
• iterable is a sequence (such as a list, tuple, or string) that the
loop iterates over.
• The indented block of code under the for statement is executed
in each iteration.

Example:

Python code
for i in range(5): print(i)

While Loop: The basic structure of a while loop in Python is as


follows:

Python code
while condition: # code to be executed as long as the condition is True
• The while keyword is used to start the loop.
• condition is a boolean expression. The loop continues as long
as the condition is True. 2+
b) CO2 K2 2.1.2
• The indented block of code under the while statement is
3
executed as long as the condition is True.

Example:

Python code
count = 0 while count < 5: print(count) count += 1

No "do while" loop in Python: Python does not have a built-in "do
while" loop like some other programming languages. The "do while"
loop typically executes a block of code at least once before checking
the loop condition. In Python, the same behavior can be achieved using
a while loop with an initial condition that is always True, and then
using a break statement to exit the loop when a certain condition is
met.

Example:

Python code
while True: # code to be executed at least once if condition: break

The absence of a "do while" loop in Python is mainly a design choice


to promote code readability and simplicity. The alternative with while
True and break is considered more Pythonic and is seen as clear and
explicit in its intent.
CO Course Outcomes mapped with respective question
KL Bloom's knowledge Level (K1, K2, K3, K4, K5, K6)
K1-Remember, K2-Understand, K3-Apply, K4-Analyze, K5:Evaluate, K6-Create

You might also like