bream bream -5 years ago 134
Python Question

Python function doesn't seem to terminate after return

At least that's the most that I can make sense of it, and I've been tracing over the flow of execution for hours. Here's the relevant snippet of the code:

def check_list(inputList):
'''checks if list is composed of numbers, and, if so, returns a new list of purely integers'''
VerifiedDataSet = []
for i in inputList:
print("Value in", inputList.index(i) + 1, "position isn't a number!")
return "not approved"
return ("approved", VerifiedDataSet)

print("This program will make your data set into a color coded bar graph (eventually)!")

listStatus = "not approved"

while listStatus == "not approved":
dataSet = ["1", "2", "foo"] #for illustration of behavior
result = check_list(dataSet)
listStatus = result[0]
if listStatus == 'approved':
dataSet = result[1]

print("You should not see this.")

The idea was to have the function
iterate through an inputted list and try converting each element into an integer. If there was an exception, it would print the position of the value that couldn't be converted into an integer and return that the list was not approved, which should 1) terminate the function, and 2) cause the
loop below to continue.

Only if there were no exceptions should the iterator complete and the function return both the string "approved" (to terminate the
loop) and the new list of integers. However, from what I can gather,
is set to "approved" somehow anyway, as the last
is executed when it never should be.

Any ideas what might be causing this behavior?

Answer Source

The value being returned from the function is a string. Hence result will have the value "not approved".

listStatus = result[0]

This will make listStatus = 'n' and not "not approved".

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download