简体   繁体   中英

Python Function does not return as expected

I am trying to create a simple function to run through a while loop and append the entered IP addresses into a list for other uses. What I can see with my print statements is I only append to the list variable the IP most recently entered and the last print of the list returns a blank list.

def IP_Range():
    while True:
        ipLIST = []
        IP = raw_input('Please enter IP or Network, enter "end" to break: ')
        if IP == 'end':
            break
        else:
            ipLIST.append(IP)
            print ipLIST
    print ipLIST

IP_Range()

Thank you in advance I know this is really simple and I am overlooking something obvious. As you can tell I am new to Python and programming in general.

At a glance, looks like you should put the list initialization outside the loop. If you do ipLIST = [] inside the loop, then it will get reset to an empty list after every iteration.

def IP_Range():
    ipLIST = []
    while True:
        IP = raw_input('Please enter IP or Network, enter "end" to break: ')
        if IP == 'end':
            break
        else:
            ipLIST.append(IP)
            print ipLIST
    print ipLIST

IP_Range()

Result:

Please enter IP or Network, enter "end" to break: 123.45
['123.45']
Please enter IP or Network, enter "end" to break: 678.90
['123.45', '678.90']
Please enter IP or Network, enter "end" to break: 1.2.3.4
['123.45', '678.90', '1.2.3.4']
Please enter IP or Network, enter "end" to break: end
['123.45', '678.90', '1.2.3.4']

If you just want to collect a range of ips you can use iter and a list comp:

def ip_range():
    return [ip for ip in iter(lambda:
        raw_input('Please enter IP or Network, enter "end" to break: '),"end")]

It will keep looping until "end" is the sentinel value is entered by the user.

If you really want to print the ip's you can use a normal for loop:

def ip_range():
    ips = [] # create outside the loop
    for ip in iter(lambda:
        raw_input('Please enter IP or Network, enter "end" to break: '), "end"):
        ips.append(ip)
        print(ip)
    print(ip)
    return ips

printing and returning are two very different things so if you want to use the list elsewhere make sure you return it, you should also use lowercase and underscores for variable names.

problem is : loop every time initialize new empty list in while loop. you can initialize list at outside of the while loop. try to this :

def IP_Range():
    ipLIST = []
    while True:
        IP = raw_input('Please enter IP or Network, enter "end" to break: ')
        if IP == 'end':
            break
        else:
            ipLIST.append(IP)
            IP = ""
            print ipLIST
    print ipLIST

IP_Range()

The solution proposed by Kevin is probably the best (it got my vote, it's the way I'd usually do it, and it would get my "Accept," if I were the OP). However, if you've got a compelling reason that you absolutely must declare ipLIST inside your while loop (I can't think of one in this case, but that doesn't mean that you don't have one), then you can do it as follows:

def IP_Range():
    while True:
        IP = raw_input('Please enter IP or Network, enter "end" to break: ')
        if IP == 'end':
            break
        else:
            try:
                ipLIST.append(IP)  # Append the IP to the list.
            except NameError:
                ipLIST = [IP,]  # Create the list, if it doesn't already exist.
            print ipLIST
    print ipLIST

IP_Range()

Results are:

Please enter IP or Network, enter "end" to break: 1.2.3.4
['1.2.3.4']
Please enter IP or Network, enter "end" to break: 2.3.4.5
['1.2.3.4', '2.3.4.5']
Please enter IP or Network, enter "end" to break: 3.4.5.6
['1.2.3.4', '2.3.4.5', '3.4.5.6']
Please enter IP or Network, enter "end" to break: end
['1.2.3.4', '2.3.4.5', '3.4.5.6']
>>>

This works because, although you're creating the list inside the while loop (the try ... except ), you're not reinitializing it every time you go through the loop, as you did in your original code ( ipLIST = [] ).

I've done this from time to time when I've needed to avoid initializing an empty list , dict , or whatever. It's something you should have in your toolbox, just in case the need comes up.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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