Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python "if X == Y and Z" syntax

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?

like image 750
bsamek Avatar asked Sep 02 '10 17:09

bsamek


People also ask

What does x == Y mean in Python?

Equal to - True if both operands are equal. x == y. != Not equal to - True if operands are not equal. x != y.

How do you check if two variables are equal in Python?

Use the == operator to test if two variables are equal.

How do you check if 3 values are the same in Python?

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.

What does %% mean in Python?

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.


2 Answers

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.

like image 148
Manoj Govindan Avatar answered Sep 17 '22 18:09

Manoj Govindan


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.

like image 23
brandizzi Avatar answered Sep 21 '22 18:09

brandizzi