1

Why am getting NameError for "If" condition?

NameError

for i in range(int(n)):
        for j in range(int(k)):
            res = a1[i] + a2[j]
            if(res<=num and ((res-num)<(prev-num))):
                r1,r2 = a1[i],a2[j]
                prev = res

    print(r1,r2)

Running code snippet:

for i in range(int(n)):
        for j in range(int(k)):
            res = a1[i] + a2[j]

            if(res<=num):
                r1,r2 = a1[i],a2[j]
                prev = res

    print(r1,r2)

If I add "AND" in "IF" condition it gives NameError for variables defined under if statement. Could someone help on this ?

Thank you.

2 Answers 2

3

That is because you cannot guarantee that an if statement will be always true (that would be useless indeed). So the variable might not be initialized, in that case you cannot print the value outside the if statement. If you want to use it you have two choices. 1) initialize the variable outside the if with a default value 2) add and else statement , in that case you will have to create the variable again

The option 1) is the most common

Sign up to request clarification or add additional context in comments.

Comments

1

Inside both if statements, you have set the variable prev = res, but in the first snippet of your code, you tried to use the prev without initializing the value of prev within if statement. In this case, you will get the error with the message:

if(res<=num and ((res-num)<(prev-num))):

NameError: name 'prev' is not defined

Solution: Initialize the value of prev before if statement in order to use "and" in if statement.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.