那是因为你正在检查int with string
即)
1=="1"
Out[10]: False
修改:
import random
n = int(raw_input("How many IP addresses need to be generated \n"))
x1 = random.choice(["172","192","10"])
for i in range (0,n):
if (int(x1) == 10 ):
x2 = random.randint(0,255)
x3 = random.randint(0,255)
x4 = random.randint(0,255)
print ".".join(map(str,([x1,x2,x3,x4])))
elif (int(x1) == 172):
x2 = random.randint(16,31)
x3 = random.randint(0,255)
x4 = random.randint(0,255)
print ".".join(map(str,([x1,x2,x3,x4])))
else:
x2 = random.randint(0,255)
x3 = random.randint(0,255)
x4 = random.randint(0,255)
print ".".join(map(str,([x1,x2,x3,x4])))
编辑:
import random
n = int(raw_input("How many IP addresses need to be generated \n"))
x1 = random.choice([172,192,10])
for i in range (0,n):
if (int(x1) == 10 ):
x2 = random.randint(0,255)
x3 = random.randint(0,255)
x4 = random.randint(0,255)
print ".".join(map(str,([x1,x2,x3,x4])))
elif (int(x1) == 172):
x2 = random.randint(16,31)
x3 = random.randint(0,255)
x4 = random.randint(0,255)
print ".".join(map(str,([x1,x2,x3,x4])))
else:
x2 = random.randint(0,255)
x3 = random.randint(0,255)
x4 = random.randint(0,255)
print ".".join(map(str,([x1,x2,x3,x4])))
edit2:
由于if and else 或做同样的事情,你可以将它们合并为else
import random
n = int(raw_input("How many IP addresses need to be generated \n"))
x1 = random.choice([172,192,10])
for i in range (0,n):
if (int(x1) == 172):
x2 = random.randint(16,31)
x3 = random.randint(0,255)
x4 = random.randint(0,255)
print ".".join(map(str,([x1,x2,x3,x4])))
else:
x2 = random.randint(0,255)
x3 = random.randint(0,255)
x4 = random.randint(0,255)
print ".".join(map(str,([x1,x2,x3,x4])))
输出:
How many IP addresses need to be generated
20
10.88.254.205
10.205.49.201
10.67.147.81
10.10.75.63
10.136.166.197
10.241.237.2
10.33.204.114
10.10.190.132
10.11.72.207
10.24.178.32
10.215.156.125
10.75.79.15
10.47.159.174
10.177.12.191
10.96.189.105
10.141.216.118
10.99.138.176
10.92.138.176
10.81.147.16
10.246.147.4
edit3:
我个人认为x1 that is ip first segment should change randomly when looping
因此编辑代码:
import random
n = int(raw_input("How many IP addresses need to be generated \n"))
for i in range (0,n):
x1 = random.choice([172,192,10]) #moved inside loop
if (int(x1) == 172):
x2 = random.randint(16,31)
x3 = random.randint(0,255)
x4 = random.randint(0,255)
print ".".join(map(str,([x1,x2,x3,x4])))
else:
x2 = random.randint(0,255)
x3 = random.randint(0,255)
x4 = random.randint(0,255)
print ".".join(map(str,([x1,x2,x3,x4])))
输出:
How many IP addresses need to be generated
20
192.178.231.68
192.253.233.190
192.114.158.193
192.196.30.127
172.22.44.3
172.23.180.6
10.69.55.105
10.105.63.195
172.21.0.195
192.83.125.135
10.36.196.137
10.8.251.102
192.38.130.4
172.22.21.131
10.204.243.231
192.136.121.203
172.30.89.149
192.40.178.100
192.155.127.75
172.23.97.228