Damon
Damon

Reputation: 89

Python - Looping through list and modifying variable

I have a small script that I need help with. Basically it is a script that logins to Cisco switch and suggests what vlan is available to use. For example, if user wants to add vlan 10. The script will look at vlan table and determine if vlan 10 is available, if it is then it succeeds. If not, the first iteration it will append 1 to 10 and will make it 101. It then goes through and checks if 101 is available, and if it is also already in use, this time it increments by 1 so 101 will become 102, 103 and so on until it has a vlan thats not in use (in the list).

My issue is I am getting this" 10, 101, 1012, 10123, and so on ..

It should be like this: 10, 101, 102, 103, and so on ...

I hard coded some variables to make the script simple, please take a look:

# Hard coded vlan and vlan_list for testing     
vlan_list = ["1","11", "10", "20", "30", "101", "102", "103", "1011", "1012", "10123", "10111"]
vlan = "10"
# Print what first vlan user has chosen       
print "Vlan is: " + vlan
# If vlan is already in list, append 1. Example: if vlan 10 is already in list, the new vlan would be 101.
#and if 101 is also in vlan_lits, this time increment the newly added 1 like, 102, 103 and so on until it finds a # thats not in vlan_list     
initial = 0
while vlan in vlan_list:
    print "Vlan " + vlan + " is already in use, creating new vlan ..."
    initial = initial + 1
    str_initial = str(initial)
    vlan = vlan  + str_initial  
    print "Vlan chosen is: " + vlan

print "Vlan " + vlan + " is available to use"

I know what I am doing wrong but I can't find a way to fix it so it works as described above. How do I edit the loop to get desired results?

Thanks Zohaib

Upvotes: 0

Views: 120

Answers (2)

John Gordon
John Gordon

Reputation: 33359

You only want to append "1" once, so that part shouldn't be in a loop.

if vlan in vlan_list:
    print "Vlan " + vlan + " is already in use, creating new vlan ..."
    vlan = vlan + "1"
    print "Vlan chosen is: " + vlan
    while vlan in vlan_list:
        print "Vlan " + vlan + " is already in use, creating new vlan ..."
        vlan = str(int(vlan) + 1)
        print "Vlan chosen is: " + vlan

Upvotes: 1

Maarten-vd-Sande
Maarten-vd-Sande

Reputation: 3711

Quick and dirty:

while vlan in vlan_list:
    print "Vlan " + vlan + " is already in use, creating new vlan ..."
    initial = initial + 1
    if initial <= 1:
        str_initial = str(initial)
        vlan = vlan  + str_initial
    else:
        vlan = str(int(vlan) + 1)
    print "Vlan chosen is: " + vlan

The problem is that the first time you should append the number, the other times you shouldn't. By adding the check it should work, since initial is only one the first time it passes through.

With values over 9 (2 digits) it 'overflows' into the rest of the number! What is the desired behaviour after that?

Upvotes: 1

Related Questions