0% found this document useful (0 votes)
6 views5 pages

Python Exam Answers

The document is a complete answer key for a Python programming course (CS-3510) for T.Y.B.Sc. (Computer Science) students. It includes questions and answers on various Python topics such as functions, loops, data structures, exception handling, and sample code snippets. The answer key is structured into multiple sections, with questions categorized by difficulty and point value.

Uploaded by

mohitnikam07
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)
6 views5 pages

Python Exam Answers

The document is a complete answer key for a Python programming course (CS-3510) for T.Y.B.Sc. (Computer Science) students. It includes questions and answers on various Python topics such as functions, loops, data structures, exception handling, and sample code snippets. The answer key is structured into multiple sections, with questions categorized by difficulty and point value.

Uploaded by

mohitnikam07
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

CS-3510: Python Programming

[Link]. (Computer Science) | Semester V | Complete Answer Key

Q1) Attempt any Eight of the following: [8×1=8]


a) Which function is used to take user input in Python?
The input() function is used to take user input in Python. It reads a line from standard input and returns it
as a string.
Example: name = input("Enter your name: ")

b) Explain the range() function in Python.


The range() function generates a sequence of numbers. Syntax: range(start, stop, step)
• range(5) → 0,1,2,3,4
• range(1,6) → 1,2,3,4,5
• range(0,10,2) → 0,2,4,6,8

c) What is the use of the continue statement?


The continue statement skips the rest of the current loop iteration and jumps to the next iteration. It does
not terminate the loop.
Example: In a loop printing 1-5, continue on 3 skips printing 3 but continues to 4 and 5.

d) What is the difference between a list and a tuple?


List: Mutable (can be changed), defined with square brackets [ ], slower.
Tuple: Immutable (cannot be changed after creation), defined with parentheses ( ), faster and
memory-efficient.

e) How do you import a module in Python?


Using the import keyword:
• import math — imports the whole module
• from math import sqrt — imports a specific function
• import math as m — imports with an alias

f) What is a dry run in programming?


A dry run is the process of manually tracing through a program's code step by step without actually
executing it on a computer, to verify its logic and predict the output.

g) Explain the use of the pop() methods in lists.


The pop() method removes and returns an element from a list.
• [Link]() — removes and returns the last element
• [Link](i) — removes and returns the element at index i

h) Explain the difference between reading and writing files in Python.


Reading: Opens a file to retrieve its content. Mode: 'r'
Example: f = open('[Link]', 'r')
Writing: Opens a file to write data (overwrites existing content). Mode: 'w'
Example: f = open('[Link]', 'w')
i) Define identifiers.
An identifier is a name used to identify a variable, function, class, module, or other object in Python.
Rules: Must start with a letter or underscore (_), cannot be a keyword, case-sensitive, can contain letters,
digits, and underscores.

j) Give the syntax for declaring a function in Python.


def function_name(parameters):
"""docstring"""
# body of function
return value

Q2) Attempt any Four of the following: [4×2=8]


a) What are the basic arithmetic operators in Python? Give examples.
Python supports the following arithmetic operators:
• + Addition: 5+3 = 8
• - Subtraction: 5-3 = 2
• * Multiplication: 5*3 = 15
• / Division: 5/2 = 2.5
• // Floor Division: 5//2 = 2
• % Modulus: 5%2 = 1
• ** Exponentiation: 2**3 = 8

b) Explain the working of the while loop with an example.


A while loop repeatedly executes a block of code as long as the given condition is True. The condition is
checked before each iteration.
i = 1
while i <= 5:
print(i)
i += 1
# Output: 1 2 3 4 5

c) What are lambda functions? Give an example.


A lambda function is an anonymous (nameless) function defined using the lambda keyword. It can take
any number of arguments but can only have one expression.
square = lambda x: x * x
print(square(5)) # Output: 25

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

d) What is the difference between a module and a package in Python?


Module: A single Python file (.py) containing functions, classes, and variables that can be imported.
Example: math, os

Package: A directory/folder containing multiple modules along with a special __init__.py file. It
organises related modules into a hierarchical structure.
Example: numpy, pandas

e) What is the role of the try-except block in exception handling?


The try-except block is used to handle runtime errors (exceptions) gracefully.
• try: The code that might raise an exception is placed here.
• except: If an exception occurs, this block is executed.
try:
x = int(input("Enter a number: "))
result = 10 / x
print(result)
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Invalid input!")

Q3) Attempt any Two of the following: [2×4=8]


a) Accept a number from user, store in list numbers < 5, print them.
numbers = []
n = int(input("How many numbers? "))
for i in range(n):
num = int(input("Enter a number: "))
[Link](num)

print("Numbers less than 5:")


for x in numbers:
if x < 5:
print(x)

b) Accept string and remove duplicate characters.


s = input("Enter a string: ")
unique = ""
for ch in s:
if ch not in unique:
unique += ch
print("String without duplicates:", unique)

# Example: input 'hello' -> output 'helo'

c) Access array element out of bound and handle the exception.


arr = [10, 20, 30, 40, 50]
try:
index = int(input("Enter index to access: "))
print("Element:", arr[index])
except IndexError:
print("Error: Index is out of bound!")
except ValueError:
print("Error: Please enter a valid integer index.")

Q4) Attempt any Two of the following: [2×4=8]


a) Write python program to check whether a number is Armstrong or not.
An Armstrong number is a number where the sum of its digits each raised to the power of the number of
digits equals the number itself. E.g. 153 = 1³+5³+3³ = 153
num = int(input("Enter a number: "))
digits = str(num)
n = len(digits)
total = sum(int(d) ** n for d in digits)

if total == num:
print(num, "is an Armstrong number.")
else:
print(num, "is NOT an Armstrong number.")

# Output for 153: 153 is an Armstrong number.

b) Print a dictionary where keys are numbers 1 to n and values are cubes of keys.
n = int(input("Enter n: "))
cube_dict = {i: i**3 for i in range(1, n+1)}
print("Dictionary:", cube_dict)

# Example output for n=5:


# {1: 1, 2: 8, 3: 27, 4: 64, 5: 125}

c) Define function all_even(tup) that returns True if all elements are even.
def all_even(tup):
for element in tup:
if element % 2 != 0:
return False
return True

# Test the function


t1 = (2, 4, 6, 8)
t2 = (2, 3, 6, 8)

print(all_even(t1)) # Output: True


print(all_even(t2)) # Output: False

Q5) Attempt any One of the following: [1×3=3]


a) Trace the output of the given program:
def sum_even(lst):
return sum(x for x in lst if x % 2 == 0)

numbers = [1, 2, 3, 4, 5, 6]
even_sum = sum_even(numbers)
print("Sum of Even Numbers:", even_sum)

Trace / Dry Run:


• numbers = [1, 2, 3, 4, 5, 6]
• sum_even() iterates over each element:
- 1 % 2 = 1 → skip
- 2 % 2 = 0 → include (2)
- 3 % 2 = 1 → skip
- 4 % 2 = 0 → include (4)
- 5 % 2 = 1 → skip
- 6 % 2 = 0 → include (6)
• sum = 2 + 4 + 6 = 12
Output: Sum of Even Numbers: 12
b) Trace the output of the given program:
numbers = (10, 20, 30, 40, 50, 60, 70, 80, 90, 100)
slice1 = numbers[2:6]
slice2 = numbers[:4]
slice3 = numbers[5:]
print("Original Tuple:", numbers)
print("Slice 1:", slice1)
print("Slice 2:", slice2)
print("Slice 3:", slice3)

Trace / Output:
• numbers[2:6] → indices 2,3,4,5 → (30, 40, 50, 60)
• numbers[:4] → indices 0,1,2,3 → (10, 20, 30, 40)
• numbers[5:] → indices 5 to end → (60, 70, 80, 90, 100)

Original Tuple: (10, 20, 30, 40, 50, 60, 70, 80, 90, 100)
Slice 1: (30, 40, 50, 60)
Slice 2: (10, 20, 30, 40)
Slice 3: (60, 70, 80, 90, 100)

— End of Answer Key —

You might also like