2

I want to get a list IP addresses from the user that match with my regex using a for loop. This is my code.

count=input('Enter number of machines:')
usrip=re.compile("^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}")
for i in range(1,count):
        user=raw_input('Enter the ip_address of machine '+str(i)+':')
        if (usrip.match(user)):
            mac_list.append(user)
        else:
            print("Enter a valid user name and ip address")

This works like this,

Enter number of machines: 3
Enter the ip_address of machine 1: not an ip
Enter a valid user name and ip address
Enter the ip_address of machine 2: 12345
Enter a valid user name and ip address

But I want to repeat the particular iteration which fails the if condition, so that the prompt for the input works as expected. Like this,

Enter number of machines: 3
Enter the ip_address of machine 1: not an ip
Enter a valid user name and ip address
Enter the ip_address of machine 1: 12345
Enter a valid user name and ip address
Enter the ip_address of machine 1: 192.168.1.1
Enter the ip_address of machine 2:

Any help would be appreciated. Thanks in advance.

  • I don't think this is a duplicate, but the solution is similar to the one in the other question: Make an infinite loop, asking the user for ips, adding them to a list if they're valid, and exiting when you have enough. – L3viathan Dec 13 '17 at 13:20

1 Answers1

0

Try this

count=input('Enter number of machines:')
usrip=re.compile("^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}")
for i in range(1,int(count)):

        user=input('Enter the ip_address of machine '+str(i)+':')
        while not (usrip.match(user)):
            print("Enter a valid user name and ip address")

            user=input('Enter the ip_address of machine '+str(i)+':')

        if (usrip.match(user)):
            mac_list.append(user)
Artier
  • 1,648
  • 2
  • 8
  • 22