Python interpreter evaluates expression 4 < 5 to True. Why then does 4 < 5 == True return False? - python-3.x

Was messing around with values and concept in interpreter and hit a logic stumbling block as 4 < 5 is True but this output is not considered equal to == True?

In Python3: 4 < 5 == True is equivalent to 4 < 5 and 5 == True, which evaluates to False because 5 != True.
Note that < and == have the same precedence.
Doc for reference https://docs.python.org/3/reference/expressions.html#comparisons

From Python documentation
Formally, if a, b, c, …, y, z are expressions and op1, op2, …, opN are
comparison operators, then a op1 b op2 c ... y opN z is equivalent to
a op1 b and b op2 c and ... y opN z, except that each expression is
evaluated at most once.
From this specification is 4 < 5 == True equal to 4 < 5 and 5 == True (and from operator precedence in Python it equals to (4 < 5) and (5 == True)) where 4 < 5 is True, but 5 == True is False. So True and False is False.

>>> 4<5
True
>>> 4<5 == True
False
>>> (4<5) == True
True
>>>
I hope this clears your doubt. 4<5 == True is evaluating as 4<5 and 5 == True which overall returns False as 4<5 is True, but, 5 == True is False. This is due to < and == having the same level of precedence.

Related

Why does a Python "x in xyz" comparison not yield equality when it returns True by itself? [duplicate]

This question already has answers here:
Why does the expression 0 < 0 == 0 return False in Python?
(9 answers)
Closed 7 days ago.
The following comparisons produce True:
>>> '1' in '11'
True
>>> ('1' in '11') == True
True
And with the parentheses the other way, I get a TypeError:
>>> '1' in ('11' == True)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: argument of type 'bool' is not iterable
So how do I get False with no parentheses?
>>> '1' in '11' == True
False
The Python manual says in and == are of equal precedence. Thus, they're evaluated from left to right by default, but there's also chaining to consider. The expression you put above ('1' in '11' == True) is actually being evaluated as...
('1' in '11') and ('11' == True)
which of course is False. If you don't know what chaining is, it's what allows you to do something like...
if 0 < a < 1:
in Python, and have that mean what you expect ("a is greater than 0 but less than 1").
It has nothing to do with precedence. In Python relational operators chain, and containment is considered a relational operator. Therefore:
'1' in '11' == True
is the same as:
('1' in '11') and ('11' == True)
which is false since True is not equal to "11".
Chaining allows you to write x < y < z, and mean x < y and y < z. Look at this interaction:
>>> (False == True) == False
True
>>> False == (True == False)
True
>>> False == True == False
False
>>>
So in your example, '1' in '11' == True is equivalent to ('1' in '11') and ('11' == True)

What is wrong with (a >=0) % 5 as it gives me 1 instead of 0

Doing a simple if elif program and I used (a>=0) % 5 were a is just an input however it doesn't work and always works out to equal 1. New to programming not sure what I'm doing wrong.
Considering the following expression:
(5 >= 0) % 5
The comparison (5 >= 0) is evaluated as True, which is then converted to 1.
Therefore you see the result of:
1 % 5
# 1
It's because a >= 0 evaluates to True if a is indeed superior or equal to 0.
True and False are subclasses of int, so True % 5 evaluates to 1 % 5 which gives 1.
Try with a negative a, and you will see that (a >= 0) % 5 will give you 0.
Examples:
>>> a = 3
>>> (a >= 0) % 5
1
>>> a = 0
>>> (a >= 0) % 5
1
>>> a = -3
>>> (a >= 0) % 5
0
If you wish to always have a positive a in input, you can do the following:
a = -1
while a < 0:
# ask for the input while a is stricly negative
a = int(input())
print(a)

if-else statement to increment or decrement inside for loop in python

I will take an input n and then print n number of lines.Every line i will input a string if this string is "++X" or "X++" then i will add 1 with 0(The initial value of X is 0). If my string is "--X" or "X--" then i will subtract 1 from 0.(If i already take another string then subtract from this string value).
Here is My code:
n = int(input())
c = 0
for x in range(n):
a = input()
if a == "X++" or "++X":
c = c + 1
elif a == "--X" or "X--":
c = c - 1
print(c)
My input:
2
X++
--X
My output:
2
Expected output:
0
Because,value will 1 for "X++" and 0 again for "--X". So,what is wrong in my code and how can i fix this?
Reference: https://docs.python.org/3/reference/expressions.html#operator-precedence
The order of precedence in the logic expression makes your expression equivalent to if (a == "X++") or "++X": which will always be True because bool("++X") == True. Any non-empty string will be True. So, as other answers suggest, you can use if a == "X++" or a == "++X": since or is evaluated last in the expression, the interp will evaluate the equality operations first, then apply or.
Another more shorthand way to test if a variable has a value that could be a few alternatives is to use the in operator.
n = int(input())
c = 0
for x in range(n):
a = input()
if a in ("X++", "++X"):
c = c + 1
elif a in ("--X", "X--"):
c = c - 1
print(c)
So you had a case where a non-empty string evaluated to True, there are other interesting cases that evaluate to either True or False in expressions. For instance, lists:
li1 = []
li2 = [1, 2]
if li1:
print("li1")
if li2:
print("li2")
Will output li2.
Bonus round - associating values with string input using a dict:
>>> def foo(n):
... d = {'X++': 1, '++X': 1, '--X': -1, 'X--': -1}
... c = 0
... for _ in range(n):
... a = input()
... c += d.get(a, 0)
... return c
...
>>> foo(3)
<-- X++
<-- ++X
<-- ++X
3
n = int(input())
c = 0
for x in range(n):
a = input()
if a == "X++" or a == "++X":
c = c + 1
elif a == "--X" or a == "X--":
c = c - 1
print(c)
:)
Change your condition from
if a == "X++" or "++X":
to
if a == "X++" or a == "++X":
or
if a in ("X++", "++X"):
You forgot to compare with a in every second operand of the ors. A non-empty string will evaluate to True.
n = int(input())
c = 0
for x in range(n):
a = input()
if a == "X++" or a == "++X":
c = c + 1
elif a == "--X" or a == "X--":
c = c - 1
print(c)

python if and else statements error

Please help me with if and else statements in python. I like to set b according to value of a.
a=5
b=0
def fname():
#less than 5
if (a < 5):
b=100
#greater than 5 or less than 10
elif (a >= 5) and (a <= 10):
b=200
#greater than 10 or less than 20
elif (a >10) and (a <= 20):
b=300
print (b)
fname()
Thanks
The b in fname is not the same b that is in the global/outer scope.
An ugly hack to make that work is to add global b inside fname.
A better way is to pass in the value for a to fname and have fname return the new value for b and assign it:
def fname(a_number):
#less than 5
if a_number < 5:
return 100
#greater than 5 or less than 10
elif 5 <= a_number <= 10:
return 200
#greater than 10 or less than 20
elif 10 < a_number <= 20:
return 300
b = fname(a)
See this question for more information about scoping and Python.
a = 5
b = 0
def fname():
# less than 5
if (a < 5):
b = 100
print(b)
# greater than 5 or less than 10
elif (a >= 5) and (a <= 10):
b = 200
print(b)
# greater than 10 or less than 20
elif (a > 10) and (a <= 20):
b = 300
print(b)
fname()
if u want to learn about if and else go to - https://youtu.be/no8c4KMYBdU

code printing wrong answer

Write a function first_last6(nums) that takes a list of ints nums and returns True if 6 appears as either the first or last element in the list. The list will be of length 1 or more.
My code:
def first_last6(nums):
if nums[0] or nums[-1] == "6":
return True
else:
return False
It is not returning the right answer for this test:
print(first_last6([3, 2, 1]))
its suppose to be False, while it prints True.
The original test checks if nums[0] is True or if nums[-1] is 6, to check if either is 6, should use:
if nums[0] == 6 or nums[-1] == 6:
Your code should be like this:
def first_last6(nums):
if (nums[0] == 6) or (nums[-1] == 6):
return True
else:
return False
In your original code, you check if the first element of the list evaluates to True (bool(1) is True in python). Instead, check if it is equal 6. And you check if the last element of the list is "6", instead of checking for 6.
A test in the interactive interpreter:
>>> 6 == "6"
False
>>> 6 == 6
True
>>> bool(1)
True

Resources