vendredi 30 décembre 2016

For loops concatenated – beginner python exercise

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)

Aucun commentaire:

Enregistrer un commentaire