For loops concatenated – beginner python exercise

153 Views Asked by At

Hi everyone I’m writing because I’m stuck with an exercise in which I should only use for loops and if/else statements. I found a way but practically I’m iterating the same block of code four times and I’m really looking for a way to automate it. I know that probably this is not the best way to solve the exercise but now I’m not looking for the most efficient way (I already found on the solutions of the exercise), I’m asking you how can I use for to iterate the block of code

The exercise tells me to create a program that takes an IP address from the keyboard and validates that it can be interpreted as a valid IP address. An IP address consists of 4 numbers, separated from each other with a full stop. Each number can have no more than 3 digits. (Examples: 127.0.0.1) Important This challenge is intended to practise for loops, and if/else statements, so although it would probably be written for real using regular expressions we don't want you to use them here even if you know what they are.

This is what I made:

# 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

There are 3 best solutions below

0
On BEST ANSWER

I would also say, split() is the way to go. Your question was if there was a way to use your logic and still not have to repeat code 4 times. To achieve that you could do something like this:

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")

As i said, i would also recommend using split() - this is just to try and provide an answer closer to your question. Also please note that this code (same as yours) will mark ip adresses containing letters, not only numbers, as OK.

0
On

Well, you have to ask yourself the right question: "can I do better?". Please always do that. Yes, in fact, you can. The code that deals with numbers validation between dots is essentially the same. So you should split the string on dots and use for loop to validate each group:

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

how about that? split the string at the dots . and check if between the dots there are numbers in the valid range (that would also accept '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