This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 7 years ago.
checking whether a key is present or not but it even though the key doesnt exist the below code evaluates to True.What is the correct and pythonic way of doing this
a={u'is_l': 0, u'importance': 1, u'release_id': u'12345', u'company': 1 }
if 'verision' and 'importance' in a:
//evaluates to True why ?
Because the grouping of expressions would be like -
if ('verision') and ('importance' in a):
And 'version' string is True in boolean context (Only empty string is False in boolean context, all other non-empty strings are True, read more about it here). , so it short circuits the and condition and returns True. You want -
if 'verision' in a and 'importance' in a:
For only 2 keys i would suggest the above version , but if you have more than 2 keys , you can create a set of those keys as suggested in the comments by #Duncan and check if that set is a subset of the dictionary keys. Example -
needs = set(['version','importance','otherkeys'..]) #set of keys to check
if needs.issubset(a): #This can be written as a single line, but that would make the line very long and unreadable.
Demo -
>>> a={u'is_l': 0, u'importance': 1, u'notes': u'12345', u'created_by': 1 }
>>> needs=set(['verision','importance'])
>>> needs.issubset(a)
False
Python adds parentheses for you like this:
if 'verision' and ('importance' in a):
Since all non-empty strings are truthy, this evaluates to True.
If you have more than two elements, it might be better to use all with a list:
if all(el in a for el in ['verision', 'importance', ...]):
Related
This question already has answers here:
How do "and" and "or" act with non-boolean values?
(8 answers)
Closed 5 months ago.
Can someone please explain why the following code comes out as "geeks" in the console?
def check():
return "geeks"
print(0 or check() or 1)
I'm assuming that Python recognizes the boolean operator, thus treating 0 == False?
So does that mean every time boolean operators are used, the arguments are treated as True/False values?
The reason that "geeks" will be printed is that or is defined as follows:
The Python or operator returns the first object that evaluates to true
or the last object in the expression, regardless of its truth value.
When check() returns the string "geeks", that value evaluates to True because it is a non-empty string. That value is then the first term in the or expression that evaluates to True, so that value is the result of the entire expression, and so is what gets printed.
This question already has answers here:
Python's Logical Operator AND [duplicate]
(7 answers)
Closed last year.
So I came across the following syntax for a coding-game solution:
.
.
n and 9
and I didn't knew how to interpret it, thus I tried
2 and 3 #3
3 and 2 #2
.
Why does x and y (seems to) equal y i.e how is this calculated/understood?
This is called short-circuiting in boolean expressions if the first is true(non zero considered as true) it goes to 2nd if this was or if the first was false(0 is considered false) it goes to 2nd try it or as or integers hope this clears stuff up
Chain of logical operators returns the first (counting from left-most value) item that lets you know the logical value of the whole statement. So, in case of and, there are 2 options - one of the values is False, at which point you know that whole statement is False and you return that value without checking anything further on the right, or all of them are True and you return the last one, as only then you know that it will be True.
This question already has answers here:
Python list - True/False first two elements? [duplicate]
(2 answers)
Closed 2 years ago.
In a Clash of Code, I've seen this interesting operator thing:
print(["false","true"][i == n])
I haven't seen this before. What's the name of this and what does it do?
It's not exactly an operator but rather the second condition is being used as an index for the ["false", "true"] list.
In case i == n this will be true. Let me remind you that true in python equals to 1
int(True) // = 1
Therefore if i == n, it will be equal to one and will print the element with index one from the list which is "true".
In case i != n, it will be False, equals to 0 which will print the first element from the array which is "false".
This a comparison Operator,
it compares the value or equality of two objects, whereas the Python is operator checks whether two variables point to the same object in memory. In the vast majority of cases, this means you should use the equality operators == and != , except when you're comparing to None.
Output: True or False
Usage: Is used to check whether 2 expressions give the same value.
This question already has answers here:
How does Python 2 compare string and int? Why do lists compare as greater than numbers, and tuples greater than lists?
(2 answers)
Closed 3 years ago.
I wish to understand,
"apple" > 10 return True always.
I have mistakenly compared string with integer. instead of raising error it returns boolean.
I want to reason behind it..
When checking string with greater than Number it always return True.
eg 1: '' > 0 = True
eg 2: 'something' > 10 = True
etc, etc.
what it means actually?
I have tried, bytes of string, id etc. i am not sure what it means.
i can understand when if its string > string
here will get result based on sorting order something like below,
>>> 'a' >= 'a'
True
>>> 'apple' >= 'a'
True
>>> 'apple' > 'a'
True
>>> 'apple' > 'b'
Note: in Python 3 it will raises an error. what about python 2.x?
I know its sorting based. number has less precedence than string.
but, is that precedence is based on memory consumption?
I found this definition:
For python2:
"If the comparison is between numeric and non-numeric, the numeric (int, float) is always less than non-numeric and if the comparison is between two non-numeric it's done by lexicographical ordering(str) or alphabetical order of their type-names(list, dict, tuple)."
For python3:
It will return TypeError.
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 years ago.
I know there are a few ways to remove vowels, but when I try the method below, the output I get is the string just being printed len(string) times. For example:
s="Labido Labidi"
for i in s:
if i.lower()=='a' or 'e' or 'i' or 'o' or 'u':
s=s.replace(i,"")
print(s)
The resultant output is:
Labido Labidi
Labido Labidi
...and so on
What's going on inside the loop ? It isn't even going through the if statement.
You are using the or statement incorrectly:
s="Labido Labidi"
for i in s:
if i.lower()=='a' or i.lower()=='e' or i.lower()=='i' or i.lower()=='o' or i.lower()=='u':
s=s.replace(i,"")
print(s)
You need to put your full evaluational statement after the or
The problem is your if logic.
After the first or you have to repeat i.lower() == 'e', etc.
Try this:
s="Labido Labidi"
for i in s:
if i.lower() in 'aeiou':
s=s.replace(i,"")
print(s)
The problem is your if condition. or connects two boolean expressions; it doesn't work the same as in English. What you need to check is
if i.lower()=='a' or
i.lower()=='e' or
...
Better yet, just make a single check on a list of vowels this way:
if lower() in "aeiou":
DETAILS
Any expression used as a Boolean value is evaluated according to whether it is "truthy" or "falsey". Non-Boolean data types are sometimes not obvious. In general, zero and `None` values are "falsey", and everything else is "truthy".
Thus, each of the single letters is "truthy", so the Python interpreter regards your if statement as if it says
if i.lower()=='a' or True or True or True or True:
In short, this is always True; your program thinks that everything is a vowel.