简体   繁体   English

如何调整代码以使其在多个条件下循环返回?

[英]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循环使用多个条件/ if语句:

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. 仅需1个条件即可完美运行。

Thanks in advance. 提前致谢。

You have a few options, but the issue is that check_input is not assigned unless there is a regex match. 您有几个选择,但是问题是除非存在正则表达式匹配项,否则不会分配check_input You can either initialize check_input to False outside the loop or add an else clause. 您可以在循环外部将check_input初始化为False或添加else子句。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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