for循环连接 - 初学者python练习

时间:2016-12-30 08:06:16

标签: python python-3.x if-statement for-loop break

大家好,我正在写作,因为我坚持练习,我只应该使用for循环和if / else语句。我找到了一种方法,但实际上我正在迭代相同的代码块四次,我真的在寻找一种自动化方法。 我知道这可能不是解决练习的最好方法,但现在我不是在寻找最有效的方法(我已经在练习的解决方案中找到了),我问你怎么用来迭代代码块

练习告诉我创建一个从键盘获取IP地址并验证它可以被解释为有效IP地址的程序。 IP地址由4个数字组成,它们以句号分隔。每个号码不能超过3位数。 (例子:127.0.0.1) 重要 这个挑战是为了练习循环和if / else语句,所以尽管它可能是使用正则表达式编写的,但我们不希望你在这里使用它们,即使你知道它们是什么。

这就是我所做的:

# ipAddress = input("please enter an ipAddress: ")
ipAddress = "192.168.7.7"  #test ip address


# check if number of dots is 3
numberOfDot = 0
for char in ipAddress:
    if char == '.':
        numberOfDot += 1
totNumbOfDot = numberOfDot  # output of this section is totNumberOfDot, to be checked at the end
if totNumbOfDot != 3:
    print("You inserted a wrong ip address")


# first number check            # THIS IS THE BLOCK OF CODE I WANT TO 
number1 = ''                    # ITERATE WITH FOR IF POSSIBLE
for char in ipAddress:
    if char in "0123456789":
        number1 += char
    if char == '.':
        break
if 1 <= len(number1) <= 3:
    print("First number:   OK")
else:
    print("First number:   Fail")
digitN1 = len(number1) + 1
print(number1)


# second number check
numberMinus2 = ipAddress[digitN1:]
number2 = ''
for char in numberMinus2:
    if char in "0123456789":
        number2 += char
    if char == '.':
        break
if 1 <= len(number2) <= 3:
    print("Second number:  OK")
else:
    print("Second number: Fail")
digitN2 = len(number2) + digitN1 +1
print(number2)


# third number check
numberMinus3 = ipAddress[digitN2:]
number3 = ''
for char in numberMinus3:
    if char in "0123456789":
        number3 += char
    if char == '.':
        break
if 1 <= len(number3) <= 3:
    print("Third number:   OK")
else:
    print("Third number:   Fail")
digitN3 = len(number3) + digitN2 + 1
print(number3)


# fourth number check
numberMinus4 = ipAddress[digitN3:]
number4 = ''
for char in numberMinus4:
    if char in "0123456789":
        number4 += char
    if char == '.':
        break
if 0 < len(number4) <= 3:
    print("Fourth number:  OK")
else:
    print("Fourth number:  Fail")
digitN4 = len(number4) + digitN3 + 1
print(number4)

3 个答案:

答案 0 :(得分:0)

嗯,你必须问自己一个正确的问题:&#34;我能做得更好吗?&#34;。请始终这样做。是的,事实上,你可以。处理点之间的数字验证的代码基本相同。因此,您应该将字符串拆分为点并使用for循环来验证每个组:

for str in ipAddress.split("."):
    your validation here

答案 1 :(得分:0)

那怎么样?将字符串分割为点.并检查点之间是否有有效范围内的数字(也接受'255.255.255.255'

def valid(ipaddress):
    # we need 3 dots; otherwise this is no ipaddress.
    if not ipaddress.count('.') == 3:
        return False

    # check what is before, between and after the dots
    for byte in ipaddress.split('.'):
        # if byte can not be interpreted as an integer -> no good!
        try:
            i = int(byte)
        except ValueError:
            return False
        # now check if byte is in the valid range
        if i < 0:
            return False
        if i > 255:
            return False

    return True


print(valid(ipaddress='192.168.7.7'))  # -> True
print(valid(ipaddress='.168.7.7'))     # -> False
print(valid(ipaddress='721.168.7.7'))  # -> False

答案 2 :(得分:0)

我也会说,split()是要走的路。你的问题是,是否有一种方法可以使用你的逻辑,但仍然不需要重复代码4次。要做到这一点,你可以做这样的事情:

numberOfDot=0
number=""
for char in ip+'.':
    if char=='.':
        numberOfDot+=1
        if len(number) in [1,2,3]:
            print("number %d OK"%numberOfDot)

        else:
            print("number %d not OK"%numberOfDot)
        print(number)
        number=""
    elif char in '1234567890':
        number+=char
    else:
        print("character not valid")
if numberOfDot!=4:
    print("you inserted a wrong ip")

正如我所说的,我还建议使用split() - 这只是为了尝试提供更接近你的问题的答案。另请注意,此代码(与您的代码相同)将标记包含字母的ip地址,而不仅仅是数字,以确定。