0

I'm very new to python. I need to loop back to a specific point in my code when a condition is not met.

Here is the code:

# Get user input on VLANs and interfaces to change
print ("what VLAN ID do you want to add? "),
vlan = raw_input()

print ("what interface do you want to add the VLAN to? (e.g. eth10)"),
interface = raw_input()

# Confirm details
print "So we are adding VLAN %r to interface %r" % (vlan, interface)

print ("Are the details above correct? (Yes/No)")
goodtogo = raw_input("> ")

if goodtogo == "yes":
    print "Configuring now...."

else:
    print "Please fix your error"

while goodtogo != "yes":
    print ("Starting again...")
    # Some type of code to loop back to start goes here!!

# Runs commands to add gathered config to switch
switch.runCmds(1, ["enable", "configure terminal", "vlan " + vlan, "interface " +     interface, "switchport mode access", "switchport access vlan " + vlan, "end" ])

print ("Change completed")

So what I need to happen is that when 'goodtogo' does not equal yes, to loop back to the start of the code. Really not sure what to do here...

1
  • this behaviour is typically referred to as encapsulation and function calling Commented Feb 26, 2014 at 22:57

1 Answer 1

1
def get_vlan_iface():
    while True:
        vlan = raw_input ("what VLAN ID do you want to add? "),
        iface = raw_input("what interface do you want to add the VLAN to? (e.g. eth10)")
        print "So we are adding VLAN %r to interface %r" % (vlan, interface)

        if raw_input("Are the details above correct? (Yes/No)>")[0].lower() == "y":
             return vlan,iface
        print "Please Fix Your Entries!"

vlan,iface = get_vlan_iface()

would be one way of doing it

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, that works well however i'm getting an error after that now when i run the script: Traceback (most recent call last): File "autovlan2.py", line 38, in <module> switch.runCmds(1, "enable", "configure terminal", "vlan " + vlan, "interface " + iface, "switchport mode access", "switchport access vlan " + vlan, "end" ) TypeError: cannot concatenate 'str' and 'tuple' objects. It is refering to the last line of code where I do the switch.runCmds
Ah, yeah there was a rouge , at the end of the vlan = raw_input line. when printing vlan it came up as ('1111',) I removed the , and it works a treat now. thanks again

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.