0

I have a code like below

a=25
b=20
#number=0
if a < b == True:
    number = 1
elif a >b == True:
    number = 2
print(number)

When i execute this i get the following error

NameError: name 'number' is not defined

When i initialize the number = 0 like below

a=25
b=20
number=0
if a < b == True:
    number = 1
elif a >b == True:
    number = 2
print(number)

then i am not getting the output as 2, i am getting 0 instead, what am i missing here

Chris
  • 183
  • 1
  • 2
  • 11

1 Answers1

3

Put a parenthesis around the condition.

Ex:

a=25
b=20
#number=0
if (a < b) == True:
    number = 1
elif (a > b) == True:
    number = 2
print(number)

or:

if a < b:
    number = 1
elif a > b:
    number = 2
print(number)
  • You are currently doing (a < b) and (b == True) & (a > b) and (b == 20)
Rakesh
  • 81,458
  • 17
  • 76
  • 113
  • 1
    This answer is correct but for safety you should either add a condition to assign number when a == b or set a default value for number above the if statements. – superbeck Jun 19 '18 at 17:08
  • 1
    @superbeck. You are right. – Rakesh Jun 19 '18 at 17:10
  • Nice answer. Will you give explanation about parenthesis of your first code please? – Taohidul Islam Jun 19 '18 at 17:14
  • Without the parenthesis the if statement is evaluating (a < (b == True)) because of the order python evaluations operations in expressions. Adding the parenthesis where @Rakesh put them specifies that you want to compare a and b, then compare the result of that comparison to 'True'. (edited for clarity) – superbeck Jun 19 '18 at 17:19
  • This solves the problem but the `== True` is still unnecessary, and if you remove the `== True` the parentheses are also unnecessary. – MoxieBall Jun 19 '18 at 17:24
  • Without the parenthesis, (b == True) evaluates to True since b is non-zero. After that a < True and a > True force the conversion of a to boolean (a is True since it is non-zero) and neither TrueTrue evaluates to True so neither path of the if/elif tree is taken. If you assign number=0 before the if statement, 0 gets printed, if you don't assign number to anything before the if statement then it is undefined when the print statement tries to evaluate it. – superbeck Jun 19 '18 at 17:25