Reputation: 9
Could someone help me understand how the 'if' statements are being used in this bit of code? This is an exercise from the LearnStreet series of Python lessons: http://www.learnstreet.com/lessons/study/python#get-hint
I thought 'if' statements required a Boolean condition: if X < Y, then do Z. But I don't see how Booleans are a part of these 'if' statements.
def run():
smiths = {"father": "Mike", "ex-wife" : "Mary", "children" : ["Bobby", "Susan"] }
jones = {"mother": "Lucy", "ex-husband": "Peter", "children": ["Michelle", "Jeff", "Evan"]}
family = {}
for key in smiths:
if key in family:
family[key]+=smiths[key]
else:
family[key]=smiths[key]
for key in jones:
if key in family:
family[key]+=jones[key]
else:
family[key]=jones[key]
keysToDel = []
for key in family:
if 'ex' in key:
keysToDel.append(key)
print keysToDel
for key in keysToDel:
del family[key]
return family
Upvotes: 0
Views: 140
Reputation: 947
if key in family:
Here the key is an element
and the family
is an container
or sequence
and you are trying to find the existence of the key
in the family
this if
statement returns True
if the key
is found in the container
otherwise returns False
Upvotes: 1
Reputation: 35901
These are boolean expressions, as in
is a Python keyword returning True
or False
depending on whether left operand is contained in the collection denoted by the right operand. From the documentation:
The operators in and not in test for collection membership. x in s evaluates to true if x is a member of the collection s, and false otherwise. x not in s returns the negation of x in s. The collection membership test has traditionally been bound to sequences; an object is a member of a collection if the collection is a sequence and contains an element equal to that object. However, it make sense for many other object types to support membership tests without being a sequence. In particular, dictionaries (for keys) and sets support membership testing.
Upvotes: 1
Reputation: 2122
if key in family
means
if the container "family" contains "key"
In C-like languages it could be written something like
if( family.contains(key) )
Either family will contain key, or it won't. So it's a boolean expression
Upvotes: 0
Reputation: 2698
They are boolean conditions. Boolean conditions don't have to look like "if X < Y", that's just an example. A boolean condition is simply anything that evaluates to true or false. "key in family" evaluates to true if the value of "key" is in the list "family", and false otherwise.
Upvotes: 0