ThatOnePythonGuy ThatOnePythonGuy - 1 month ago 9
Python Question

How can I adjust my code to allow it to loop back with multiple conditions?

I've looked over tutorials but don't particularly understand the concept.

I'm trying to get my while loop work with multiple conditions/if statements:

while True:
user_input = raw_input('\n: ').upper()
if user_input == 'NORMAL':
user_input = 'Normal'
if re.match('(ABC|Normal|XY)', user_input):
check_input = cleaned_dict.get(user_input)
if not check_input:
print 'Nope'
if check_input:
print 'Yep...'
etc...
break


However, I receive an error:

UnboundLocalError: local variable 'check_input' referenced before assignment


...Due to it not looping when the regex pattern does not match.

With only 1 condition it works perfectly.

Thanks in advance.

Answer

You have a few options, but the issue is that check_input is not assigned unless there is a regex match. You can either initialize check_input to False outside the loop or add an else clause. I'll show the latter

while True:
    user_input = raw_input('\n: ').upper()
    if user_input == 'NORMAL':
        user_input = 'Normal'
    if re.match('(ABC|Normal|XY)', user_input):
        check_input = cleaned_dict.get(user_input)
    else:
        check_input = False
    if not check_input:
        print 'Nope'
    if check_input:
        print 'Yep...'
    etc...
    break
Comments