Module: (Python) Loops. Loop with counter - for


Problem

8/15

Repeat N times

Theory Click to read/hide

Repeat N times

All programs with a for loop that we have written so far cannot be called universal. Because we ourselves set the number of repetitions of the loop body. 
But what if the number of repetitions depends on some other value? For example, the user himself wants to set the number of repetitions of the cycle.
What to do in this case?
Everything is very simple. Instead of numeric start and end values, we can use any variables that can be calculated or set by the user.

For example, we need to display the squares of numbers from 1 to N, where the value of the variable N is entered from the keyboard by the user.
The program will look like this:
N = int(input()) # input N from the keyboard
for i in range(1, N+1): # loop: for all i from 1 to N  - variable i
                           # will sequentially take values ​​from 1 to N
  print("square", i, "=", i*i)  # print the square of a number

When entering the loop, the assignment statement i = 1 is executed, and then the variable i is incremented by one with each step (i += 1). The loop is executed while the condition i <= N is true. In the body of the loop, the only output statement prints the number itself and its square on the screen according to the specified format.
For squaring or other low exponents, it's better to use multiplication.

Run the program and see the result of its work with different values ​​of the variable N.
 
 

Problem

Run the program for execution, see the result of its work with different values ​​of the variable N.
Analyze the output in the program test result window.

Notice that with N=0 (test #1) the program doesn't output anything. Think why?