range()函数连续列表生成(ip地址)
#define a variable to hold a string representing the base address
baseAddress = "192.168.0."
#next define a list of host addresses using the range
#standard library function(this will give us values of 1-19 host)
hostAddresses = range(20)
#define a list that will hold the result ip strings
#this starts out as a simple empty list
ipRange = []
#loop through the host addresses since the list host Addresses
#contains the integers from 0-19 and we can create
#a loop in Python that processes each of the list elements
#stored in hostAddresses,where i is the loop counter value
for i in hostAddresses:
#append the combined ipstrings to the ipRange list
#because ip Range is a list object,the object has a set of
#attributes and methods.We are going to invoke the append method
#each time through the loop and concatenate the base address
#string with the string value of the integer
ipRange.append(baseAddress + str(i))
# | | | | |_value of the host address
# | | | |_function to convert int to str
# | | |_The string '192.168.0'
# | |_The append method of the list ipRange
# |_The list object ipRange
#Once completed we want to print out the ip range list
#here we use the print function and instruct it to print out
#the ip Range list object,I wanted to print out each of the
#resulting ip address on a separate line,so I looped
#through the ip Range list object one entry at a time.
for ipAddr in ipRange:
print(ipAddr)
输出结果:
192.168.0.0
192.168.0.1
192.168.0.2
192.168.0.3
192.168.0.4
192.168.0.5
192.168.0.6
192.168.0.7
192.168.0.8
192.168.0.9
192.168.0.10
192.168.0.11
192.168.0.12
192.168.0.13
192.168.0.14
192.168.0.15
192.168.0.16
192.168.0.17
192.168.0.18
192.168.0.19