Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does program count one extra value (cycle "while")?

Why the program count one more value? For example, I give him N = 50. It gives out:

1
4
9
16
25
36
49
64

Code:

N = int(input())

n = 1
 
k = 1

while n < N:

    n = k ** 2
    print(n)
    k = k + 1
like image 238
Дима Яновский Avatar asked Jun 29 '26 10:06

Дима Яновский


2 Answers

As explained, you're checking n then changing n, you want to change n then check before continuing.

You can use the walrus operator to assign n and check it's value all in the while statement. (requires Python 3.8+)

N = int(input())
n = 1
k = 1

while (n := k**2) < N:
    print(n)
    k += 1

This essentially assigns n to k**2 then checks if that result is <N before continuing.

1
4
9
16
25
36
49
like image 79
Jab Avatar answered Jun 30 '26 23:06

Jab


Your program outputs 1 4 9 16 25 36 49 64 if your input is 50 because the `while`` loop is checking the value before you increase it. Once in the loop, you increase it, calculate the square and then print.

If you want it to terminate, try setting calculating n as the last step in the loop:

N = int(input())

n = 1
 
k = 1

while n < N:

    
    print(n)
    k = k + 1
    n = k ** 2
like image 26
user1717828 Avatar answered Jun 30 '26 23:06

user1717828