O.rka
O.rka

Reputation: 30687

Range(0,30) does not start with 0 if using while . Python

First of all, I would like to apologize if the title of the question is confusing

for i in range(0,30):
    while i:
        print i           
        break 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

why doesn't it start with 0? if i don't use the 'while i'and just print i . . . it starts with 0 as expected. the while loop does something weird. what is happening? why is it not printing 0

Upvotes: 0

Views: 1522

Answers (4)

evuez
evuez

Reputation: 3387

while 0 is equivalency to while False. So it won't go with that one:

for i in range(0,30):
    while i: # while 0 == while False, so it just skips to next value
        print i           
        break 

If you want to print the 0, check if it is actually a 0:

for i in range(0,30):
    while i is not False: # False == 0 but False is not 0
        print i           
        break 

Upvotes: 4

VIKASH JAISWAL
VIKASH JAISWAL

Reputation: 838

because of this:

while 0:
    print 'hello'

won't print anything.

if you really want to print at 0 as well you can instead check if it's int:

for i in range(0,30):
    while isinstance(i,int):
        print i         
        break 

Upvotes: 0

paxdiablo
paxdiablo

Reputation: 881403

range(0,30) does start with zero, it's just that because you have used, for some bizarre reason known only to yourself, the line while i:, it will result in falsity when i is zero. Hence, while the range itself produces that value, you choose to ignore it.

If, instead, you use:

for i in range(0,30):
    while True:
        print i           
        break 

or, better yet, without the while altogether:

for i in range(30):
    print i           

you'll find it works as expected.

Upvotes: 2

SQB
SQB

Reputation: 4078

Perhaps because while expects a boolean. 0 evaluates to false, so the while condition is not met.

Upvotes: 0

Related Questions