Home > Enterprise >  Value is not updated in the IF statement
Value is not updated in the IF statement

Time:12-28

I know this is a silly question, but I would like to know why dictx is not being updated? The functions returns dictx value ignoring the if block Thanks

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

CodePudding user response:

If you write a function in the following format:

if statement:
    //first action
//second action

the second action will be run regardless of whether the if statement is true or not.

If you want to make the second action only run if the if statement is not true then you must place it in an else statement.

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

In your case, even if the dictionary is updated with num, it will always get overwritten with 'not five' afterwards.

CodePudding user response:

It is because, once you go through the if statement and the condition is evaluated to true. And the dictx variable is changed. But on the next line it gets overwritten by dictx = {'hello':'goodbye','hello2':'not five'}. It is always the same value (no matter what the num is). To fix this you can use an else statement and put the dictx = {'hello':'goodbye','hello2':'not five'} line nested in it.

Final result:

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

CodePudding user response:

you problem is because of you assign your value in dicx after If statement. you can change your code like this:

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