Home > Mobile >  Python Exponentiating Operator
Python Exponentiating Operator

Time:11-28

Could someone help me to understand the following statement?

Why this is True:

3.0 == 3

but this one not?

4 ** 0.5 != 2 

(4**0.5 = 2.0, and according to above statement 2.0 is equal to 2), but I get False. WHy?

CodePudding user response:

The != operator does the opposite of ==.

(In your first example, you wrote = but I think you mean ==.)

With !=, it evaluates True if the two numbers are not equal to each other, otherwise it is False. (Here, "equal" can include an integer and a floating point number having the same numerical value.)

So here:

>>> 4 ** 0.5 != 2 
False
>>> 4 ** 0.5 == 2 
True

CodePudding user response:

Unlike some languages, Python does not care about floats and ints when it comes to comparing. It will treat 4 and 4.0 as the exact same when comparing them to other numbers. You can debate the reliability of this feature of Python, but for the purposes of answering this question this is relevant.

Now we know this, we can see that 4 * .5 is the same is 2.0 which is the same as 2. The actual reason the second argument is false has nothing to do with the number being a float or not, but actually to do with the operator you are using.

== will return true if both sides of the equation ARE equal, whereas != will return true if both sides of the equation ARE NOT equal.

The second statement is using the != operator and so is returning false because both sides are equal. If both sides where not equal, it would return false.

Hope this cleared things up!

  • Related