0067NEWT
0067NEWT

Reputation: 3

Can't find a way to exit loop and keep the currently entered variable

def active_check(active):
    for i in range(0, (len(active_data)-1)):
        if active == active_data[i][0]:
            raise active_Cert
            break
        else:
            print("TTTTTTTTTTTTTTTTTTTT")
    return active

try:
    while True:
        active = active_check(input("Enter state"))
except active_Cert:
    pass
print(active)

I have this set up, where the user enters a number and then it scans through a CSV to find if that number matches any of the data in the 1st 'column'. If it finds one then it should raise an exception which quits the while loop the function is in - and it does. The problem is that the final print statement prints the second to last entered variable (given that there were multiple incorrect entries)

I can see why this is, although I can't find a good way to get around it

Upvotes: 0

Views: 49

Answers (1)

Teoretic
Teoretic

Reputation: 2533

Possible solution is to return some variable with active variable instead of throwing an exception.

Consider this code, I added to_continue variable and removed an exception part:

def active_check(active):
    for i in range(0, (len(active_data)-1)):
        if active == active_data[i][0]:
            return active, False
        else:
            print("TTTTTTTTTTTTTTTTTTTT")
    return active, True

to_continue = True
while to_continue:
    active, to_continue = active_check(input("Enter state"))
print(active)

Upvotes: 2

Related Questions