Does this:
if key == "name" and item:
mean the same as this:
if key == "name" and if key == "item":
If so, I'm totally confused about example 5.14 in Dive Into Python. How can key be equal to both "name" and item? On the other hand, does "and item" simply ask whether or not item exists as a variable?
Equal to - True if both operands are equal. x == y. != Not equal to - True if operands are not equal. x != y.
Use the == operator to test if two variables are equal.
a() == b() == c() is functionally equivalent to a() == b() and b() == c() whenever consecutive calls to b return the same value and have the same aggregate side effects as a single call to b . For instance, there is no difference between the two expressions whenever b is a pure function with no side-effects.
The % symbol in Python is called the Modulo Operator. It returns the remainder of dividing the left hand operand by right hand operand. It's used to get the remainder of a division problem.
if key == "name" and item:
means if (key == "name") and (item evaluates to True)
.
Keep in mind that (item evaluates to True)
is possible in several ways. For example if (key == "name") and []
will evaluate to False
.
Manoj explained it well. Here goes some complementary notes.
The pseudocode
if key == "name" or if key == "item":
should be this way:
if key == "name" or key == "item":
An interesting idiom to do it is:
if key in ("name", "item"):
but it is more useful for really large conditions where you just want to know if some value is equal to any other value from a list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With