Why in JavaScript and so in other programming languages is not possible to do if (a==b==c) to compare 3 variable at once? [closed] - programming-languages

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 months ago.
Improve this question
Why, objectively, in programming languages in general, as far as I know, isn't possibile to compare 3 variable at once doing something like this:
if(a == b == c)
{
do something;
}
but it is necessary to do something like:
if(a == b && b == c)
{
do something;
}
why it is necessary to repeat twice the b variable?
Why the simplified way isn't implemented as well to compare multiple variables but is is necessary to use logic operators to make the comparison work?
The same question can be raised inequalities as a > b > c etc...

It has to do with the way the language evaluates boolean values. There are two different ways it could evaluate a == b == c: (a == b) == c, or a == (b == c).
In the first case, (a == b) == c, we start by evaluating a == b, which will return either true or false. The problem comes in when we try to do the next step. After evaluating what was in the parentheses, we could have either true == c or false == c, and unless c was equal to either true or false, the result of that (and the entire expression) would be false.
Hopefully you can see how this also applies to both ways of evaluating the expression, as well as with any other comparison operators you may use. Comparison operators simply return true or false based on the values directly to either side of them, and scripting languages run expressions in order, not all at once.
Another way to see it is if you rewrote the == operator as a function:
function isEqual(a, b):
if a == b:
return true
else:
return false
That is pretty much exactly what the == operator does. It simply returns true or false based on the values of its two arguments. Writing a == b == c would be the same as writing either isEqual(isEqual(a, b), c) or isEqual(a, isEqual(b, c)). Either way, you would be comparing a boolean to a potentially other type of value.

Related

Python going through all if statements even if the if doesn’t match [duplicate]

This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 5 months ago.
I have a calculator script, and I have a variable for the operator, number 1 and number 2, this is what it looks like
Operator = input(“operator: “)
Num1 = input(“num1 here: “)
Num2 = input(“num2 here: “)
If Operator == “x” or “*”:
#code
I have one of these for all four main math equations but it’s goes through all the ifs and elifs in order even if the ‘operator’ input doesn’t match. Note I have pyttsx3 installed and a text to speech is in the code. Any help would be appreciated.
Your comparison needs to check both conditions.
It should look like:
If Operator=='x' or Operator=='*'
Right now it's evaluating like:
If (Operator=='x') or ('*'==True)
In python a string (like '*') will evaluate as 'True', so your code is always being executed.
The or operator returns the first element if it is truthy, else the second element. Then if looks at what it gets. In this case (Operator == "x") or "*" evaluates to "*", which in turn is truthy. So the if block is entered.
What you would like to do is probably something like
if ( Operator == "x" ) or ( Operator == "*" ):
# code
To back my claim, you can find the definition of or here.
The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.
The string "*" is not empty, so it evaluates to true. See here.

Why were Logical Operators created?

Almost all programming languages are having the concept of logical operator
I am having a query why logical operators were created. I googled and found its created for condition based operation, but that's a kind of usage i think.
I am interested in the answer that what are the challenges people faced without this operator. Please explain with example if possible.
I am interested in the answer that what are the challenges people faced without this operator.
Super-verbose deeply nested if() conditions, and especially loop conditions.
while (a && b) {
a = something;
b = something_else;
}
written without logical operators becomes:
while (a) {
if (!b) break; // or if(b){} else break; if you want to avoid logical ! as well
a = something;
b = something_else;
}
Of if you don't want a loop, do you want to write this?
if (c >= 'a') {
if (c <= 'z') {
stuff;
}
}
No, of course you don't because it's horrible compared to if (c >= 'a' && c <= 'z'), especially if there's an else, or this is inside another nesting. Especially if your coding-style rules require 8-space indentation for each level of nesting, or the { on its own line making each level of nesting eat up even more vertical space.
Note that a&b is not equivalent to a&&b: even apart from short-circuit evaluation. (Where b isn't even evaluated if a is false.) e.g. 2 & 1 is false, because their integer bit patterns don't have any of the same bits set.
Short-circuit evaluation allows loop conditions like while(p && p->data != 0) to check for a NULL pointer and then conditionally do something only on non-NULL.
Compact expressions were a big deal when computers were programmed over slow serial lines using paper teletypes.
Also note that these are purely high-level language-design considerations. CPU hardware doesn't have anything like logical operators; it usually takes multiple instructions to implement a ! on an integer (into a 0/1 integer, not when used as an if condition).
if (a && b) typically compiles to two test/branch instructions in a row.

Python operating on big numbers causes margin errors [duplicate]

This question's answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions.
My Google-fu has failed me.
In Python, are the following two tests for equality equivalent?
n = 5
# Test one.
if n == 5:
print 'Yay!'
# Test two.
if n is 5:
print 'Yay!'
Does this hold true for objects where you would be comparing instances (a list say)?
Okay, so this kind of answers my question:
L = []
L.append(1)
if L == [1]:
print 'Yay!'
# Holds true, but...
if L is [1]:
print 'Yay!'
# Doesn't.
So == tests value where is tests to see if they are the same object?
is will return True if two variables point to the same object (in memory), == if the objects referred to by the variables are equal.
>>> a = [1, 2, 3]
>>> b = a
>>> b is a
True
>>> b == a
True
# Make a new copy of list `a` via the slice operator,
# and assign it to variable `b`
>>> b = a[:]
>>> b is a
False
>>> b == a
True
In your case, the second test only works because Python caches small integer objects, which is an implementation detail. For larger integers, this does not work:
>>> 1000 is 10**3
False
>>> 1000 == 10**3
True
The same holds true for string literals:
>>> "a" is "a"
True
>>> "aa" is "a" * 2
True
>>> x = "a"
>>> "aa" is x * 2
False
>>> "aa" is intern(x*2)
True
Please see this question as well.
There is a simple rule of thumb to tell you when to use == or is.
== is for value equality. Use it when you would like to know if two objects have the same value.
is is for reference equality. Use it when you would like to know if two references refer to the same object.
In general, when you are comparing something to a simple type, you are usually checking for value equality, so you should use ==. For example, the intention of your example is probably to check whether x has a value equal to 2 (==), not whether x is literally referring to the same object as 2.
Something else to note: because of the way the CPython reference implementation works, you'll get unexpected and inconsistent results if you mistakenly use is to compare for reference equality on integers:
>>> a = 500
>>> b = 500
>>> a == b
True
>>> a is b
False
That's pretty much what we expected: a and b have the same value, but are distinct entities. But what about this?
>>> c = 200
>>> d = 200
>>> c == d
True
>>> c is d
True
This is inconsistent with the earlier result. What's going on here? It turns out the reference implementation of Python caches integer objects in the range -5..256 as singleton instances for performance reasons. Here's an example demonstrating this:
>>> for i in range(250, 260): a = i; print "%i: %s" % (i, a is int(str(i)));
...
250: True
251: True
252: True
253: True
254: True
255: True
256: True
257: False
258: False
259: False
This is another obvious reason not to use is: the behavior is left up to implementations when you're erroneously using it for value equality.
Is there a difference between == and is in Python?
Yes, they have a very important difference.
==: check for equality - the semantics are that equivalent objects (that aren't necessarily the same object) will test as equal. As the documentation says:
The operators <, >, ==, >=, <=, and != compare the values of two objects.
is: check for identity - the semantics are that the object (as held in memory) is the object. Again, the documentation says:
The operators is and is not test for object identity: x is y is true
if and only if x and y are the same object. Object identity is
determined using the id() function. x is not y yields the inverse
truth value.
Thus, the check for identity is the same as checking for the equality of the IDs of the objects. That is,
a is b
is the same as:
id(a) == id(b)
where id is the builtin function that returns an integer that "is guaranteed to be unique among simultaneously existing objects" (see help(id)) and where a and b are any arbitrary objects.
Other Usage Directions
You should use these comparisons for their semantics. Use is to check identity and == to check equality.
So in general, we use is to check for identity. This is usually useful when we are checking for an object that should only exist once in memory, referred to as a "singleton" in the documentation.
Use cases for is include:
None
enum values (when using Enums from the enum module)
usually modules
usually class objects resulting from class definitions
usually function objects resulting from function definitions
anything else that should only exist once in memory (all singletons, generally)
a specific object that you want by identity
Usual use cases for == include:
numbers, including integers
strings
lists
sets
dictionaries
custom mutable objects
other builtin immutable objects, in most cases
The general use case, again, for ==, is the object you want may not be the same object, instead it may be an equivalent one
PEP 8 directions
PEP 8, the official Python style guide for the standard library also mentions two use-cases for is:
Comparisons to singletons like None should always be done with is or
is not, never the equality operators.
Also, beware of writing if x when you really mean if x is not None --
e.g. when testing whether a variable or argument that defaults to None
was set to some other value. The other value might have a type (such
as a container) that could be false in a boolean context!
Inferring equality from identity
If is is true, equality can usually be inferred - logically, if an object is itself, then it should test as equivalent to itself.
In most cases this logic is true, but it relies on the implementation of the __eq__ special method. As the docs say,
The default behavior for equality comparison (== and !=) is based on
the identity of the objects. Hence, equality comparison of instances
with the same identity results in equality, and equality comparison of
instances with different identities results in inequality. A
motivation for this default behavior is the desire that all objects
should be reflexive (i.e. x is y implies x == y).
and in the interests of consistency, recommends:
Equality comparison should be reflexive. In other words, identical
objects should compare equal:
x is y implies x == y
We can see that this is the default behavior for custom objects:
>>> class Object(object): pass
>>> obj = Object()
>>> obj2 = Object()
>>> obj == obj, obj is obj
(True, True)
>>> obj == obj2, obj is obj2
(False, False)
The contrapositive is also usually true - if somethings test as not equal, you can usually infer that they are not the same object.
Since tests for equality can be customized, this inference does not always hold true for all types.
An exception
A notable exception is nan - it always tests as not equal to itself:
>>> nan = float('nan')
>>> nan
nan
>>> nan is nan
True
>>> nan == nan # !!!!!
False
Checking for identity can be much a much quicker check than checking for equality (which might require recursively checking members).
But it cannot be substituted for equality where you may find more than one object as equivalent.
Note that comparing equality of lists and tuples will assume that identity of objects are equal (because this is a fast check). This can create contradictions if the logic is inconsistent - as it is for nan:
>>> [nan] == [nan]
True
>>> (nan,) == (nan,)
True
A Cautionary Tale:
The question is attempting to use is to compare integers. You shouldn't assume that an instance of an integer is the same instance as one obtained by another reference. This story explains why.
A commenter had code that relied on the fact that small integers (-5 to 256 inclusive) are singletons in Python, instead of checking for equality.
Wow, this can lead to some insidious bugs. I had some code that checked if a is b, which worked as I wanted because a and b are typically small numbers. The bug only happened today, after six months in production, because a and b were finally large enough to not be cached. – gwg
It worked in development. It may have passed some unittests.
And it worked in production - until the code checked for an integer larger than 256, at which point it failed in production.
This is a production failure that could have been caught in code review or possibly with a style-checker.
Let me emphasize: do not use is to compare integers.
== determines if the values are equal, while is determines if they are the exact same object.
What's the difference between is and ==?
== and is are different comparison! As others already said:
== compares the values of the objects.
is compares the references of the objects.
In Python names refer to objects, for example in this case value1 and value2 refer to an int instance storing the value 1000:
value1 = 1000
value2 = value1
Because value2 refers to the same object is and == will give True:
>>> value1 == value2
True
>>> value1 is value2
True
In the following example the names value1 and value2 refer to different int instances, even if both store the same integer:
>>> value1 = 1000
>>> value2 = 1000
Because the same value (integer) is stored == will be True, that's why it's often called "value comparison". However is will return False because these are different objects:
>>> value1 == value2
True
>>> value1 is value2
False
When to use which?
Generally is is a much faster comparison. That's why CPython caches (or maybe reuses would be the better term) certain objects like small integers, some strings, etc. But this should be treated as implementation detail that could (even if unlikely) change at any point without warning.
You should only use is if you:
want to check if two objects are really the same object (not just the same "value"). One example can be if you use a singleton object as constant.
want to compare a value to a Python constant. The constants in Python are:
None
True1
False1
NotImplemented
Ellipsis
__debug__
classes (for example int is int or int is float)
there could be additional constants in built-in modules or 3rd party modules. For example np.ma.masked from the NumPy module)
In every other case you should use == to check for equality.
Can I customize the behavior?
There is some aspect to == that hasn't been mentioned already in the other answers: It's part of Pythons "Data model". That means its behavior can be customized using the __eq__ method. For example:
class MyClass(object):
def __init__(self, val):
self._value = val
def __eq__(self, other):
print('__eq__ method called')
try:
return self._value == other._value
except AttributeError:
raise TypeError('Cannot compare {0} to objects of type {1}'
.format(type(self), type(other)))
This is just an artificial example to illustrate that the method is really called:
>>> MyClass(10) == MyClass(10)
__eq__ method called
True
Note that by default (if no other implementation of __eq__ can be found in the class or the superclasses) __eq__ uses is:
class AClass(object):
def __init__(self, value):
self._value = value
>>> a = AClass(10)
>>> b = AClass(10)
>>> a == b
False
>>> a == a
So it's actually important to implement __eq__ if you want "more" than just reference-comparison for custom classes!
On the other hand you cannot customize is checks. It will always compare just if you have the same reference.
Will these comparisons always return a boolean?
Because __eq__ can be re-implemented or overridden, it's not limited to return True or False. It could return anything (but in most cases it should return a boolean!).
For example with NumPy arrays the == will return an array:
>>> import numpy as np
>>> np.arange(10) == 2
array([False, False, True, False, False, False, False, False, False, False], dtype=bool)
But is checks will always return True or False!
1 As Aaron Hall mentioned in the comments:
Generally you shouldn't do any is True or is False checks because one normally uses these "checks" in a context that implicitly converts the condition to a boolean (for example in an if statement). So doing the is True comparison and the implicit boolean cast is doing more work than just doing the boolean cast - and you limit yourself to booleans (which isn't considered pythonic).
Like PEP8 mentions:
Don't compare boolean values to True or False using ==.
Yes: if greeting:
No: if greeting == True:
Worse: if greeting is True:
They are completely different. is checks for object identity, while == checks for equality (a notion that depends on the two operands' types).
It is only a lucky coincidence that "is" seems to work correctly with small integers (e.g. 5 == 4+1). That is because CPython optimizes the storage of integers in the range (-5 to 256) by making them singletons. This behavior is totally implementation-dependent and not guaranteed to be preserved under all manner of minor transformative operations.
For example, Python 3.5 also makes short strings singletons, but slicing them disrupts this behavior:
>>> "foo" + "bar" == "foobar"
True
>>> "foo" + "bar" is "foobar"
True
>>> "foo"[:] + "bar" == "foobar"
True
>>> "foo"[:] + "bar" is "foobar"
False
https://docs.python.org/library/stdtypes.html#comparisons
is tests for identity
== tests for equality
Each (small) integer value is mapped to a single value, so every 3 is identical and equal. This is an implementation detail, not part of the language spec though
Your answer is correct. The is operator compares the identity of two objects. The == operator compares the values of two objects.
An object's identity never changes once it has been created; you may think of it as the object's address in memory.
You can control comparison behaviour of object values by defining a __cmp__ method or a rich comparison method like __eq__.
Have a look at Stack Overflow question Python's “is” operator behaves unexpectedly with integers.
What it mostly boils down to is that "is" checks to see if they are the same object, not just equal to each other (the numbers below 256 are a special case).
In a nutshell, is checks whether two references point to the same object or not.== checks whether two objects have the same value or not.
a=[1,2,3]
b=a #a and b point to the same object
c=list(a) #c points to different object
if a==b:
print('#') #output:#
if a is b:
print('##') #output:##
if a==c:
print('###') #output:##
if a is c:
print('####') #no output as c and a point to different object
As the other people in this post answer the question in details the difference between == and is for comparing Objects or variables, I would emphasize mainly the comparison between is and == for strings which can give different results and I would urge programmers to carefully use them.
For string comparison, make sure to use == instead of is:
str = 'hello'
if (str is 'hello'):
print ('str is hello')
if (str == 'hello'):
print ('str == hello')
Out:
str is hello
str == hello
But in the below example == and is will get different results:
str2 = 'hello sam'
if (str2 is 'hello sam'):
print ('str2 is hello sam')
if (str2 == 'hello sam'):
print ('str2 == hello sam')
Out:
str2 == hello sam
Conclusion and Analysis:
Use is carefully to compare between strings.
Since is for comparing objects and since in Python 3+ every variable such as string interpret as an object, let's see what happened in above paragraphs.
In python there is id function that shows a unique constant of an object during its lifetime. This id is using in back-end of Python interpreter to compare two objects using is keyword.
str = 'hello'
id('hello')
> 140039832615152
id(str)
> 140039832615152
But
str2 = 'hello sam'
id('hello sam')
> 140039832615536
id(str2)
> 140039832615792
As John Feminella said, most of the time you will use == and != because your objective is to compare values. I'd just like to categorise what you would do the rest of the time:
There is one and only one instance of NoneType i.e. None is a singleton. Consequently foo == None and foo is None mean the same. However the is test is faster and the Pythonic convention is to use foo is None.
If you are doing some introspection or mucking about with garbage collection or checking whether your custom-built string interning gadget is working or suchlike, then you probably have a use-case for foo is bar.
True and False are also (now) singletons, but there is no use-case for foo == True and no use case for foo is True.
Most of them already answered to the point. Just as an additional note (based on my understanding and experimenting but not from a documented source), the statement
== if the objects referred to by the variables are equal
from above answers should be read as
== if the objects referred to by the variables are equal and objects belonging to the same type/class
. I arrived at this conclusion based on the below test:
list1 = [1,2,3,4]
tuple1 = (1,2,3,4)
print(list1)
print(tuple1)
print(id(list1))
print(id(tuple1))
print(list1 == tuple1)
print(list1 is tuple1)
Here the contents of the list and tuple are same but the type/class are different.

2 possible outputs for 1 if statement python 3.x [duplicate]

This question already has answers here:
if statement with two conditions in Python
(2 answers)
Closed 5 years ago.
I am new to python and I am just figuring out the basics. I was just wondering how to have two possible choices in one if statement from one input.
q2 = input("What is the capital of Brazil? ")
if q2 == 'Brasilia' or 'brazilia':
print("Correct!")
else:
print("Wrong! The answer was Brasilia.")
However this does not work as when you put in a wrong answer, it says that it is "Correct!"
There are a number of ways of getting the desired result here:
if q2 == 'Brasilia' or q2 == 'brasilia':
if q2.lower() == 'brasilia':
if q2 in ('Brasilia', 'brasilia')
if q2.lower() in ('brasilia',)
Option #1 is just a correction for what you have. If you have only one real option that is just case sensitive, option #2 is a simple way to go. If you have many options, #3 and #4 are the way to go.
Theor does not work like you're trying to use it; think of it as bool(q2 == 'Brasilia') or bool('brasilia'); bool('brasilia') is True, so it will always be true.
You would need to use "q2 == 'Brasilia' or q2 == 'brasilia'", although q2.lower() == 'brasilia' is more idiomatic and more forgiving, unless it is important that it be strict.
If capitalization is not important then you could do:
if q2.lower() == 'brazilia':
or, if only first letter can be like this then:
if q2[0].lower() == 'b' and q[1:] == 'razilia':
Also, if you have more different words that fit the answer then use Python's in statement to check if the world belongs to a list of possible choices:
if q2 in ['Brazilia', 'Brasilia']:
etc. You can combine str.lower() and/or str.upper() with in statement if necessary.

Why doesn't Kotlin support "ternary operator" [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
Explain: This question is more about the design intentions of Kotlin. Many expression languages support both Ternary operator and if expression [e.g., Ruby, Groovy.]
First of all, I know Groovy supports both Ternary operator and Elvis operator: Ternary operator in Groovy. So I don't think it's a syntax problem.
Then the official documents said:
In Kotlin, if is an expression, i.e. it returns a value. Therefore there is no ternary operator (condition ? then : else), because ordinary if works fine in this role.
And this doesn't convince me. Because Kotlin support Elvis operator which ordinary if works just fine in that role either.
I think ternary operator is sometimes better than ordinary if, though I wonder why doesn't Kotlin just support ternary operator?
In languages which have ternary operator you use it like this
String value = condition ? foo : bar;
In Kotlin you can do the same thing using if and else
var value = if(condition) foo else bar;
Its bit verbose than the ternary operator. But designers of Kotlin have thought it is ok. You can use if-else like this because in Kotlin if is an expression and returns a value
Elvis operator is essentially a compressed version of ternary conditional statement and equivalent to following in Kotlin.
var value = if(foo != null) foo else bar;
But if Elvis operator is used it simplify as follows
var value = foo ?: bar;
This is considerable simplification and Kotlin decided to keep it.
Because if .. else .. works fine. Take a look:
fun main(args: Array<String>) {
var i = 2
println("i ${ if(i == 1) "equals 1" else "not equals 1" }")
}
Ternary operator has its problems, for example it is hard to read with big expressions. Here is a line from my C++ project where I used ternary operator:
const long offset = (comm_rank > 0) ? task_size_mod + (comm_rank - 1) * task_size : 0;
I would rather use an if else expression here since it is so much more visible.
Answering you question, I am aware of two reasons why ternary operator was not implemented in Kotlin:
1) Since if else is an expression anyway, it can replace ? :
2) Experience from other languages (C++) shows that ? : provokes hard-to-read code, so it is better to be left out
Programmers at some point, have to make a decision to execute a block of code, this is known as Control Flow. If statement is most basic way to control flow in Kotlin. Important point to note that in Kotlin, If is an expression not a statement as it is Java.
Statement: A statement is an executed line which does not return a
value. As a result, statement cannot sit right side of an equal
sign.
Expression: An expression returns a value.So the result of a Kolin
If expression can be assigned to a variable.
Because of this the ternary expression would be redundant and does not exists in Kotlin. In Java we would write (Here is the answer of your question)
For Example
Ternary Operator in Java
int lowest = (a < b) ? a : b;
In Kotlin we can write something similar using the if expression.
val lowest = if(a < b) a else b
NOTE:
When If is used as an expression it must contain an else clause. The expression must have a value in all case.
Because if-else is an expression in Kotlin :
String check = number % 2 == 0 ? "even" : "odd" // Java
if (number % 2 == 0) "even else "odd" // Kotlin
So that's why there are no ternary operator in Kotlin, Moreover you can use when expressions too, it's so handy if you want to provide a lot of possible execution paths

Resources