Bird
0
0

You want to write a method that returns a dictionary with keys as numbers from 1 to n and values as their squares. Which method below correctly does this?

hard📝 Application Q15 of 15
Python - Methods and Behavior Definition
You want to write a method that returns a dictionary with keys as numbers from 1 to n and values as their squares. Which method below correctly does this?
Adef squares(n): result = {} for i in range(1, n+1): result[i] = i * i return result
Bdef squares(n): result = [] for i in range(n): result.append(i * i) return result
Cdef squares(n): return {i: i + i for i in range(1, n)}
Ddef squares(n): for i in range(1, n+1): print(i * i)
Step-by-Step Solution
Solution:
  1. Step 1: Understand the requirement

    The method must return a dictionary with keys 1 to n and values as squares.
  2. Step 2: Check each option

    The loop building result = {}, setting result[i] = i * i for i in range(1, n+1), and returning result is correct. Returning a list fails. The comprehension {i: i + i for i in range(1, n)} uses doubles instead of squares and misses key n. Printing without returning fails.
  3. Final Answer:

    def squares(n): result = {} for i in range(1, n+1): result[i] = i * i return result -> Option A
  4. Quick Check:

    Return dict with squares = def squares(n): result = {} for i in range(1, n+1): result[i] = i * i return result [OK]
Quick Trick: Return dict with keys and squares using loop [OK]
Common Mistakes:
  • Returning list instead of dict
  • Using wrong range limits
  • Printing instead of returning

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes