对于IP地址段长度的循环计数器不计算最后一个段

时间:2019-02-08 22:38:40

标签: python-3.x for-loop counter

请输入IP地址1012.321.32.21 段#1的segmentLength为4 段#2的segmentLength为3 segment#3的segmentLength为2 segmentCount为4

我的Python程序没有计算最后一段的段长度,在这种情况下为2。为什么?

address = input("Please enter an IP address ")

segmentCount = 0
segmentLength = 0

for char in address:
    if char in "0123456789":
        segmentLength += 1

elif char not in "0123456789":
    segmentCount += 1
    print("segmentLength of segment #", segmentCount, "is   {}".format(segmentLength))
    segmentLength = 0


#Adding 1 to segmentCount to account for segment after last dot.
print("segmentCount is {}".format(segmentCount + 1))

预期结果: 请输入IP地址1012.321.32.21 段#1的segmentLength为4 段#2的segmentLength为3 segment#3的segmentLength为2 segment#4的segmentLength为2 segmentCount为4

实际结果: 请输入IP地址1012.321.32.21 段#1的segmentLength为4 段#2的segmentLength为3 segment#3的segmentLength为2 segmentCount为4

1 个答案:

答案 0 :(得分:0)

您正在打印不在数字列表中的字符。列表的末尾不会进入for循环以到达最后一个打印结果。

address = input("Please enter an IP address ")

segmentCount = 1
segmentLength = 0

for char in address:
    if char in "0123456789":
        segmentLength += 1

    elif char not in "0123456789":

        print("segmentLength of segment #", segmentCount, "is   {}".format(segmentLength))
        segmentCount += 1
        segmentLength = 0


#NO LONGER-- Adding 1 to segmentCount to account for segment after last dot.
print("segmentLength of segment #", segmentCount, "is   {}".format(segmentLength))
print("segmentCount is {}".format(segmentCount ))

现在,这不是最好的代码,因为您不想拥有其他print语句,但是它应该可以说明问题所在。