0
sum, Nr = 0, 12
i = Nr
while i:
    sum += i
    i -= 1
print ('The sum of all natural numbers up to (and inclusive of) ' + repr(Nr) +
' is ' + repr(sum))

So this is a very simple while loop in python 3 which returns "The sum of all natural numbers up to (and inclusive of) 12 is 78" as expected.

What I am confused about is that why this condition "while i:" works here when "i" is not subjected to any comparison operator.

Thanks!

DHH
  • 97
  • 6
  • 1
    Note that negative numbers are also truthy... so don't change that `i -= 1` to anything that isn't going to exactly match `0` and end the loop... eg: `i -= 7` will never end... – Jon Clements Jul 31 '17 at 13:38
  • Thanks! I just started programming and truthy falsy helps a lot! – DHH Jul 31 '17 at 13:38

6 Answers6

1

In conditional statements, the input is implicitly cast to boolean, hence the loop is equivalent to

while bool(i):
    ...

bool(i) is True as long as i != 0, and False if i == 0, so the loop goes until i becomes zero.

Jonas Adler
  • 10,365
  • 5
  • 46
  • 73
1

It seems that Python does an implicit replacement with i not equals zero (pseudo code). See documentation.

Xvolks
  • 2,065
  • 1
  • 21
  • 32
1

While expect the expression and if it is true is runs the loop.

while_stmt ::= "while" expression ":" suite ["else" ":" suite]

In [38]: bool(Nr)
Out[38]: True
Vishnu Upadhyay
  • 5,043
  • 1
  • 13
  • 24
1

while loop expects any condition either True or False. When you write while i (suppose i = 5) it is evaluated as True, so the loop continues but when it encounters i=0 it is evaluated as False and the loop breaks.

ksai
  • 987
  • 6
  • 18
0

Python automatically computes the truthy value of the variable passed to it by converting it into boolean. Since i being a non-zero positive integer is considered true in Python, that's why it's working, till it finally becomes 0 which is considered false.

>>> print(bool(3))
True
>>> print(bool(0))
False
hspandher
  • 15,934
  • 2
  • 32
  • 45
0

In python, values are duck typed - what this means is that the interpreter can try to fit the value into whatever context you have put it. All numbers other than zero are 'truthy', so for instance

if 3:  # True

Whereas zero is falsy:

if 0:  # False
Barnabus
  • 376
  • 3
  • 14