1. (a) Which of the following is not a valid variable name in Python ? Justify reason for it not being a valid name.
(i) 5Radius
(ii) Radius_
(iii) _Radius
(iv) Radius
Ans: option (i) "5Radius" is not a valid variable name because it violates the rule that variable names cannot start with a number.
(b) Which of the following are keywords in Python ?
(i) break
(ii) check
(iii) range
(iv) while
Ans: Python keywords are reserved words that have special meanings in the language and cannot be used as variable names. So, the keywords in Python among the given options are (i) break, (iii) range, and (iv) while.
(c) Name the Python Library modules which need to be imported to invoke the following functions :
(i) cos()
(ii) randint()
Ans: To use the cos() function, you need to import the math module.
To use the randint() function, you need to import the random module.
(d) Rewrite the following code in Python after removing all syntax error(s). Underline each correction done in the code.
input('Enter a word',W)
if W = 'Hello'
print('Ok')
else:
print('Not Ok')
Ans: W = input('Enter a word: ') # Removed the incorrect variable assignment and added a colon after the input statement.
if W == 'Hello': # Replaced a single equals sign with a double equals sign for comparison.
print('Ok') # Indented the print statement properly.
else:
print('Not Ok') # Indented the print statement properly.
(e) Find and write the output of the following Python code :
def ChangeVal(M,N):
for i in range(N):
if M[i]%5 == 0:
M[i] //= 5
if M[i]%3 == 0:
M[i] //= 3
L=[25,8,75,12]
ChangeVal(L,4)
for i in L :
print(i, end='#')
Ans: The output of the code is: 5#8#5#4#
(f) Find and write the output of the following Python code:
def Call(P=40,Q=20):
P=P+Q
Q=P–Q
print(P,'@',Q)
return P
R=200
S=100
R=Call(R,S)
print (R,'@',S)
S=Call(S)
print(R,'@',S)
Ans: The output of the code is:
300 @ 200
120 @ 100
300 @ 120
(g) What possible output(s) are expected to be displayed on screen at the time of execution of the program from the following code ? Also specify the minimum and maximum values that can be assigned to the variable End.
import random
Colours = ["VIOLET","INDIGO","BLUE","GREEN", "YELLOW","ORANGE","RED"]
End = randrange(2)+3
Begin = randrange(End)+1
for i in range(Begin,End):
print(Colours[i],end="&")
(i) INDIGO&BLUE&GREEN&
(ii) VIOLET&INDIGO&BLUE&
(iii) BLUE&GREEN&YELLOW&
(iv) GREEN&YELLOW&ORANGE&
2. (a) Write the names of the immutable data objects from the following:
(i) List
(ii) Tuple
(iii) String
(iv) Dictionary
Ans: Immutable data objects are data types in Python that cannot be changed after they are created. Here are the immutable data objects from the above: (i) Tuple (ii) String
(b) Write a Python statement to declare a Dictionary named ClassRoll with Keys as 1, 2, 3 and corresponding values as ‘Reena‘, ‘Rakesh‘, ‘Zareen‘ respectively.
Ans: ClassRoll = {1: 'Reena', 2: 'Rakesh', 3: 'Zareen'}
(c) Which of the options out of (i) to (iv) is the correct data type for the variable Vowels as defined in the following Python statement?
Vowels = ('A', 'E', 'I', 'O', 'U')
(i) List
(ii) Dictionary
(iii) Tuple
(iv) Array
(d) Write the output of the following Python code :
for i in range(2,7,2):
print(i * '$')
Ans: The output of the code is:
$$
$$$$
$$$$$$
(e) Write the output of the following Python code :
def Update(X=10):
X += 15
print('X = ', X)
X=20
Update()
print('X = ', X)
Ans: The output of the code is:
X = 25
X = 20
(f) Differentiate between ‘‘w’’ and ‘‘r’’ file modes used in Python. Illustrate the difference using suitable examples.
Ans: In Python, the file modes 'w' and 'r' are used to open files for writing and reading, respectively.
#Opening a file in 'w' mode and writing to it with open('example.txt', 'w') as file:
file.write('This is a sample text written to the file.')
# Opening a file in 'r' mode and reading from it with open('example.txt', 'r') as file:
content = file.read()
print(content)
(g) A pie chart is to be drawn (using python) to represent Pollution Level of Cities. Write appropriate statements in Python to provide labels for the pie slices as the names of the Cities and the size of each pie slice representing the corresponding Pollution of the Cities as per the following table:
| Cities | Pollution |
|---|
| Mumbai | 350 |
| Delhi | 475 |
| Chennai | 315 |
| Bangalore | 390 |
Ans:
import matplotlib.pyplot as plt
# Data
cities = ['Mumbai', 'Delhi', 'Chennai', 'Bangalore']
pollution = [350, 475, 315, 390]
# Create a pie chart
plt.figure(figsize=(8, 8))
plt.pie(pollution, labels=cities, autopct='%1.1f%%', startangle=140)
# Set the aspect ratio to be equal so that it looks like a circle
plt.axis('equal')
# Add a title
plt.title('Pollution Level of Cities')
# Show the pie chart
plt.show()
OR
Write the output from the given Python code:
import matplotlib.pyplot as plt
Months = ['Dec','Jan','Feb','Mar']
Marks = [70, 90, 75, 95]
plt.bar(Months, Marks)
plt.show()
Ans: -----graph
(h) Write a function Show_words() in Python to read the content of a text file ‘NOTES.TXT’ and display the entire content in capital letters. Example, if the file contains:
"This is a test file"
Then the function should display the output as :
THIS IS A TEST FILE
Ans:
def Show_words(file_name):
try:
# Open the file in read mode
with open(file_name, 'r') as file:
# Read the content of the file
file_content = file.read()
# Convert the content to uppercase
file_content_upper = file_content.upper()
# Display the content in uppercase
print(file_content_upper)
except FileNotFoundError:
print(f"File '{file_name}' not found.")
except Exception as e:
print(f"An error occurred: {str(e)}")
# Example usage
Show_words('NOTES.TXT')
OR
Write a function Show_words() in Python to read the content of a text file 'NOTES.TXT' and display only such lines of the file which have exactly 5 words in them. Example, if the file contains:
This is a sample file.
The file contains many sentences.
But needs only sentences which have only 5 words.
Then the function should display the output as:
This is a sample file.
The file contains many sentences:
Ans:
def Show_words(file_name):
try:
# Open the file in read mode
with open(file_name, 'r') as file:
# Read the content of the file line by line
lines = file.readlines()
# Iterate through each line
for line in lines:
# Split the line into words and count them
words = line.split()
word_count = len(words)
# Check if the line has exactly 5 words
if word_count == 5:
print(line.strip()) # Display the line without leading/trailing whitespace
except FileNotFoundError:
print(f"File '{file_name}' not found.")
except Exception as e:
print(f"An error occurred: {str(e)}")
# Example usage
Show_words('NOTES.TXT')
(i) Write a Recursive function in Python RecsumNat(N), to return the sum of the first N natural numbers. For example, if N is 10 then the function should return (1 + 2 + 3 + … + 10 = 55).
Ans:
def RecsumNat(N):
# Base case: If N is 1, return 1 (the sum of the first natural number)
if N == 1:
return 1
# Recursive case: Add N to the sum of the first N-1 natural numbers
else:
return N + RecsumNat(N - 1)
# Example usage
N = 10
result = RecsumNat(N)
print(f"The sum of the first {N} natural numbers is {result}.")
OR
Write a Recursive function in Python Power(X,N), to return the result of X raised to the power N where X and N are non-negative integers. For example, if X is 5 and N is 3 then the function should return the result of (5)3 i.e. 125.
Ans:
def Power(X, N):
# Base case: X^0 is 1 for any positive X
if N == 0:
return 1
# Recursive case: X^N = X * X^(N-1)
else:
return X * Power(X, N - 1)
# Example usage
X = 5
N = 3
result = Power(X, N)
print(f"{X}^{N} is {result}.")
(j) Write functions in Python for PushS(List) and for PopS(List) for performing Push and Pop operations with a stack of List containing integers.
Ans:
#Here is the Python code for the 'PushS' function:
def PopS(stack, List):
if stack: # if the stack is not empty
for i in range(len(stack)):
List.append(stack.pop()) # pop an element from the stack and add it to the list
return List
#Here is the Python code for the 'PopS' function:
stack = []
list1 = ['1', '2', '3']
list2 = []
stack = PushS(stack, list1)
print(stack) # Output: [3, 2, 1]
list2 = PopS(stack, list2)
print(list2) # Output: [1, 2, 3]
OR
Write functions in Python for InsertQ(Names) and for RemoveQ(Names) for performing insertion and removal operations with a queue of List which contains names of students.
Ans:
#Here is the Python code for the InsertQ function:
from collections import deque
def InsertQ(Names):
queue = deque()
for name in Names:
queue.append(name)
return queue
#Here is the Python code for the RemoveQ function:
def RemoveQ(Names):
queue = InsertQ(Names)
for name in Names:
if name in queue:
queue.remove(name)
return queue