2014-02-26 14 views
0

我對Python非常陌生。當條件不滿足時,我需要循環回代碼中的特定點。Python while循環回代碼中的特定點

下面是代碼:

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

所以我需要發生的是,當「goodtogo」不等於肯定,循環回到代碼的開始。真的不知道該怎麼辦在這裏...

+0

這種行爲通常被稱爲封裝和函數調用 –

回答

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

會做

+0

感謝的一種方式,行之有效但是我得到的錯誤後,現在當我運行腳本:Traceback(最近呼叫最後): 文件「autovlan2.py」,第38行,在 switch.runCmds(1,「啓用」,「配置終端」,「vlan」 + vlan,「interface」+ iface,「switchport mode access」,「switchport access vlan」+ vlan,「end」) TypeError:無法連接'str'和'tuple'對象。它是指最後一行代碼,我在哪裏做switch.runCmds – Luca

+0

他們都應該是字符串...嘗試打印vlan和iface ... –

+0

啊,是啊有一個胭脂,在vlan = raw_input末尾線。當打印VLAN時,它成爲('1111'),我刪除了它,現在它可以工作。再次感謝 – Luca