Class - 12 CBSE Computer Science Important Output Questions 2025
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)
Python
Python Dictionaries
4 Likes
Answer
15@
7@
9@
Working
Initialization:
- A dictionary
d
is created with three key-value pairs. - An empty string
str1
is initialized.
- A dictionary
Iteration:
Thefor
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).
- For "apple":
- The line
str2 = str1[:-1]
removes the last newline character fromstr1
, resulting instr2
being "15@\n7@\n9@". - Finally,
print(str2)
outputs the content ofstr2
.
Answered By
1 Like