Python bootcamp · Lab 08

Squares with a comprehension

easyList Comprehension10 minLesson: List Comprehension

Read the question, write Python on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

Read n and print the squares of 1 through n on one line, separated by single spaces.

This is the perfect first taste of a list comprehension — build the list in one expression, then print it.

Input. One line: an integer n ≥ 1.

Output. Space-separated squares, e.g. 1 4 9 16 25 for n = 5.

Constraints

  • 1 ≤ n ≤ 20

Examples

Example 1
Input
5
Output
1 4 9 16 25
Hint
  1. A comprehension: [i * i for i in range(1, n + 1)].
  2. print(*seq) unpacks the list so the numbers print with spaces, not brackets.
Show correct code

Peek only after you have tried. You can still Check your own version.

n = int(input())
print(*[i * i for i in range(1, n + 1)])
main.pyPython · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.