This question already has answers here:
What is the motivation for the "or" operator to not return a bool?
(6 answers)
Closed 5 years ago.
I've this code:
url='http://mybeautifulurl.com'
('h' or 'f') in url[0:4] #This is True
('f' or 'h') in url[0:4] #This is False
I'm just trying to understand why the 'or' operator seems to evaluate just the first condition.
This or returns the first element if it evaluates to true (as a bool) and the second one otherwise... it's is usually applied to set default values.
This way, 'h' or 'f' is simply 'h' and 'f' or 'h' is simply 'f'.
You can achieve what you want with something like:
any(x in url[:4] for x in ['h', 'f'])
Related
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 last year.
When I try this code:
a = ['b']
if 'i' or 'j' in a:
print('Yes!')
else:
print('No!')
The output is 'Yes!'. Flake8 and python do not complain about an error or bad form.
What exactly happens when the code runs? Why does 'i' or 'j' in a evaluate as true?
The problem is that in the statement i evaluates to True, which means that the statement is then: True or 'j' in a. This is always true and your result will be always 'Yes!'.
You can use something like this to check if one of the values is in your list:
a = ['b']
chars_to_check = ['i', 'j']
filtered_list = [i for i in a if i in chars_to_check]
if len(filtered_list)>0:
print('Yes!')
else:
print('No!')
The example is from this question, where people also posted more efficient or shorter solutions to your problem. The solution I like the most would be this one:
a = ['b']
if {'i','j'} & set(a):
print('Yes!')
else:
print('No!')
EDIT: I think now I understand the question.
First of all python sees that you have a or in your if statement. This means the first expression (in your case 'i') is evaluated first. If the first expression is True, the whole statement is True and the second expression is not even evaluated. The evaluation order of or is explained here for example.
Now to why the first expression is always True. Python automatically evaluates all objects not only boolean values. For this the objects can for example contain a function __bool__() that gives back the boolean value of an object. The object in your case is a single character 'i', which evaluates to True. The reason is that it is defined that the boolean value of a string is always True except for the empty string (''). Here you can see an example of the evaluation:
print(bool('i')) # True
print(bool('')) # False
An answer that shows which objects are considered False and which are considered True can you find here.
This question already has answers here:
Python ? (conditional/ternary) operator for assignments [duplicate]
(2 answers)
Closed 2 years ago.
This could obviously be done with an if-elif-else logic, but I wish to ask for a better - more pythonic way to implement it. eg.
a,b = 14,73
if a>b:
print('a')
elif a<b:
print('b')
else:
print('a=b') #not_required_though
You can do if else in one line
print('a' if a>b else 'b')
or you can also assign it to variable
res = 'a' if a>b else 'b' if b>a else 'a==b'
This question already has answers here:
How do "and" and "or" act with non-boolean values?
(8 answers)
How does the logical `and` operator work with integers? [duplicate]
(2 answers)
"4 and 5" is 5, while "4 or 5" is 4. Is there any reason? [duplicate]
(4 answers)
Closed 3 years ago.
What does 'a' and 'b' in Python mean and why does it equal 'b'? Why does it not equal 'a'?
>>> 'a' and 'b'
'b'
From the Pycharm docs:
The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.
Because 'a' is not False 'b' is evaluated and returned.
Also nice to know. What is evaluated as True and what as False:
the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true.
Either 'a' or 'b' would be an acceptable answer to 'a' and 'b' (since both are truthy), but only False would be an acceptable answer to 'a' and False, just as only 0 would be an acceptable answer to 'a' and 0 (since the result of this evaluation must be false-y to be logically correct).
Having a short-circuiting boolean evaluation follow the right-hand path when the left-hand is true allows there to be a single rule that applies in all cases.
This question already has answers here:
Is it possible to write single line return statement with if statement?
(4 answers)
Closed 6 years ago.
I know that the 'one line if statement' question has been asked multiple times already but I couldn't figure out what's wrong with my code. I want to convert
def has_no_e(word):
if 'e' not in word:
return True
to a one line function like:
def hasNoE(word):
return True if 'e' not in word
but I get a Syntax Error if I do so -why?
I think because you do not specify the else part. You should write it as:
return True if 'e' not in word else None
This is because Python sees it as:
return <expr>
and you specify a ternary condition operator as <expr> which has syntax:
<expr1> if <condition> else <expr2>
So Python is looking for your else part.
Return False?
Perhaps you want to return False in case the test fails. In that case you could thus write it like:
return True if 'e' not in word else False
but this can be shortened in:
return 'e' not in word
Ternary conditional statements require you to have an else in them as well. Thus, you must have:
def hasNoE(word):
return True if 'e' not in word else False
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 6 years ago.
Why does the following evaluates to False in Python?
6==(5 or 6)
False
'b'==('a' or 'b')
False
The first expression evaluates (5 or 6) first, which evaluates to 5 because 5 is truthy. 5 is NOT equal to 6 so it returns False.
The second expression evaluates ('a' or 'b') first, which evaluates to 'a' for the same reason as above. 'a' is NOT equal to 'b' so it returns False.
A good example to explain this would be to try to put a falsey value as the first part of the or expression like 6 == ([ ] or 6) or 6 == (None or 6). Both of these will return true because the or statement will evaluate to the truthy value (in each case it is 6).
There are a couple of ways to create the statement I think you want. The first would be to use in like 6 in (6,5). The second way would be to expand your boolean expression to read like this (6 == 5) or (6 == 6). Both of these will return True.
The condition within parentheses is evaluated first. So
6==(5 or 6)
evaluates to
6==(5) # since 5 != 0 (True), the second operand is not evaluated
which is False. Same goes for the second one. ('a' != None)
Try:
>>>6 == (6 or 5)
True
What's going on? Try:
>>5 or 6
5
I'm not totally sure why "5 or 6" evaluates to 5, but I would just try writing that expression differently.
But there is a caveat:
>> 5 == (0 or 5)
True
Because 0 is not truth-worthy, hence the bracket result in 5.