Range

Range

range produces a sequence of numbers to loop over. With one argument it counts from 0 up to, but not including, that number:

for i in range(4):
    print(i)

Output:

0
1
2
3

With two arguments it counts from the first up to, but not including, the second:

for i in range(1, 5):
    print(i)

Output:

1
2
3
4

The stop value is excluded, the same rule as slicing. To print 1 through n, write range(1, n + 1).

range(len(items)) produces every valid index of a list — useful when the body needs the position, not only the element.

Exercise

  1. Define a function named print_squares with one parameter, n.
  2. For each number from 1 to n (inclusive), print <number> squared is <square>.

print_squares(3) prints:

1 squared is 1
2 squared is 4
3 squared is 9

Run your code to see the output, then press Submit.

Tests

import io
import unittest
from contextlib import redirect_stdout


def output_of(function, *args):
    captured = io.StringIO()
    with redirect_stdout(captured):
        function(*args)
    return captured.getvalue()


class TestPrintSquares(unittest.TestCase):
    def test_up_to_3(self):
        expected = "1 squared is 1\n2 squared is 4\n3 squared is 9\n"
        self.assertEqual(output_of(print_squares, 3), expected)

    def test_up_to_1(self):
        self.assertEqual(output_of(print_squares, 1), "1 squared is 1\n")

    def test_zero_prints_nothing(self):
        self.assertEqual(output_of(print_squares, 0), "")
def print_squares(n):
    for number in range(1, n + 1):
        print(f"{number} squared is {number ** 2}")


print_squares(3)
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.