Eitan K
Eitan K

Reputation: 837

How do I structure this nested for loop?

I am trying to use a nested for loop to print the values 192.168.42.0-255 and 192.168.43.0-255.

for i in range(42, 43):
    for y in range(0, 255):
        ip = "192.168." + str(i) + "." + str(y)
        print ip

All that is printing is the values 192.168.42.0-255. It doesn't seem to be changing to 192.168.43.

Upvotes: 2

Views: 60

Answers (4)

Mike Müller
Mike Müller

Reputation: 85442

You can use itertools.product() to combine the number groups in a single loop:

from itertools import product

ips = ('192.168.{}.{}'.format(*pair) for pair in product((42, 43), range(256)))
for ip in ips:
    print(ip)

Upvotes: 1

LunaHK
LunaHK

Reputation: 13

if you want to use range(a,b), then it should be range(42,44) instead of 43.

Upvotes: 0

aneroid
aneroid

Reputation: 15962

range(42,43) gives only [42]. Change that to only for i in (42,43):.

And as @timgeb pointed out, your 2nd loop should be range(0, 256) or just range(256); not 255.

Upvotes: 1

timgeb
timgeb

Reputation: 78680

range(x,y) does not include y.

>>> range(42,43)
[42]

Your code can be fixed by changing the first one to range(42,44) and the second one to range(0,256) (or just range(256)).

If you want to get rid of the nested loops altogether, you can use a generator expression:

for ip in ('192.168.{}.{}'.format(i,j) for i in (42,43) for j in range(256)):
    print(ip)

Upvotes: 7

Related Questions