简体   繁体   English

For串联的循环–初学者python练习

[英]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. 大家好,我正在写这篇文章,因为我坚持练习,只应使用for循环和if / else语句。 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. 该练习告诉我创建一个程序,该程序从键盘上获取IP地址并验证它可以解释为有效IP地址。 An IP address consists of 4 numbers, separated from each other with a full stop. IP地址由4个数字组成,它们之间用句号分隔。 Each number can have no more than 3 digits. 每个数字不能超过3个数字。 (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. (示例:127.0.0.1)重要此挑战旨在练习循环和if / else语句,因此尽管它很可能是使用正则表达式编写的,但即使您知道什么,我们也不想在这里使用它们他们是。

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)

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循环来验证每个组:

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

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' ) 并检查点之间是否存在有效范围内的数字(也可以接受'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

I would also say, split() is the way to go. 我还要说,split()是必经之路。 Your question was if there was a way to use your logic and still not have to repeat code 4 times. 您的问题是是否有一种方法可以使用您的逻辑并且仍然不必重复执行4次代码。 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. 正如我所说,我也建议您使用split()-这只是为了尝试提供一个更接近您问题的答案。 Also please note that this code (same as yours) will mark ip adresses containing letters, not only numbers, as OK. 还请注意,此代码(与您的代码相同)会将包含字母(不仅是数字)的IP地址标记为OK。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM