CBSE Class 12 Computer Science Question 37 of 44

Solved 2025 Sample Question Paper CBSE Class 12 Computer Science (083) — Question 5

Back to all questions
5
Question

Question 31(a)

Predict the output of the following code:

d = {"apple": 15, "banana": 7, "cherry": 9} 
str1 = "" 
for key in d: 
    str1 = str1 + str(d[key]) + "@" + "\n"
str2 = str1[:-1] 
print(str2) 
Answer
Output
15@
7@
9@
Explanation
  1. Initialization:
  • A dictionary d is created with three key-value pairs.
  • An empty string str1 is initialized.
  1. Iteration:

    The for loop iterates over each key in the dictionary:

  • For "apple": str1 becomes "15@\n" (value 15 followed by "@" and a newline).
  • For "banana": str1 becomes "15@\n7@\n" (adding value 7 followed by "@" and a newline).
  • For "cherry": str1 becomes "15@\n7@\n9@\n" (adding value 9 followed by "@" and a newline).
  1. The line str2 = str1[:-1] removes the last newline character from str1, resulting in str2 being "15@\n7@\n9@".

  2. Finally, print(str2) outputs the content of str2.