【问题标题】:How can I adjust my code to allow it to loop back with multiple conditions?如何调整我的代码以允许它在多个条件下循环?
【发布时间】:2017-03-02 21:43:36
【问题描述】:

我看过教程,但不是特别了解这个概念。

我正在尝试让我的 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

但是,我收到一个错误:

UnboundLocalError: local variable 'check_input' referenced before assignment

...由于正则表达式模式不匹配时它不会循环。

只需 1 个条件,它就可以完美运行。

提前致谢。

【问题讨论】:

    标签: python regex python-2.7 if-statement conditional


    【解决方案1】:

    您有几个选项,但问题是check_input 不会被分配,除非有正则表达式匹配。您可以在循环外将check_input 初始化为False 或添加else 子句。我会展示后者

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-22
      • 2019-03-31
      • 2016-05-08
      • 2011-04-22
      • 2023-03-25
      • 2013-02-23
      相关资源
      最近更新 更多