【问题标题】:Value is not updated in the IF statementIF 语句中的值未更新
【发布时间】:2021-12-27 17:19:07
【问题描述】:

我知道这是一个愚蠢的问题,但我想知道为什么 dictx 没有更新?函数返回 dictx 值,忽略 if 块 谢谢

def testing_func(num):
    if num == 5:
       dictx = {'var1':'val1',
                'var2': num}
    dictx = {'var':'val1',
             'var2':'not five'}
    return dictx

【问题讨论】:

  • 第二个赋值替换第一个赋值,它们没有合并。
  • 如果要合并字典,请使用dictx.update(...)
  • 你的意思是在第二部分使用else语句吗?
  • 您是否打算将第二个放在else 语句中?

标签: python if-statement scope


【解决方案1】:

如果你写一个如下格式的函数:

if statement:
    //first action
//second action

无论 if 语句是否为真,都会运行第二个操作。

如果您想让第二个动作只在 if 语句不为真时运行,那么您必须将它放在 else 语句中。

if statement:
    //first action
else:
    //second action

在您的情况下,即使使用 num 更新了字典,之后它也总是会被 'not 五' 覆盖。

【讨论】:

    【解决方案2】:

    你的问题是因为你在 If 语句之后在 dicx 中分配了你的值。 你可以像这样改变你的代码:

    def testing_func(num):
        if num == 5:
           dictx = ({'var1':'val1','var2': num})
        else:
           dictx = {'hello':'goodbye','hello2':'not five'}
        return dictx
    

    【讨论】:

      【解决方案3】:

      这是因为,一旦你通过 if 语句并且条件被评估为真。并且 dictx 变量已更改。但在下一行它被dictx = {'hello':'goodbye','hello2':'not five'} 覆盖。它始终是相同的值(无论 num 是什么)。要解决此问题,您可以使用 else 语句并将 dictx = {'hello':'goodbye','hello2':'not five'} 行嵌套在其中。

      最终结果:

      def testing_func(num):
          if num == 5:
             dictx = ({'var1':'val1',
                      'var2': num})
          else:
             dictx = {'hello':'goodbye',
                   'hello2':'not five'}
          return dictx
      

      【讨论】:

        猜你喜欢
        • 2020-07-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-09
        • 1970-01-01
        • 1970-01-01
        • 2012-08-29
        • 2018-11-14
        相关资源
        最近更新 更多