Anonymous Functions


#1



I am confused about the code in the instruction:


def by_three(x):
    return x % 3 == 0

Codeacademy never explicitly explained the "return if" structure, although I did come across one and get confused. In the code above, why does it return x? The way I read it is "return ??? if x is dividable by 3". How should I go about changing it if say I want it to return x ^ 2?


#2

This line is returning a boolean. The expression is evaluated before returning.

Assertion: x % 3 == 0

Outcome: True if is 0, else False.

The counterpart to that assertion would be,

return x % 3

which will return a number in the range, 0..2. Looking at this as a boolean on return to the caller.

if by_three(7): print "the number 7 is not evenly divisible by 3"

the return value will be 1 which is cast to True in a conditional. Read up on truthy and falsy values as they relate to coercion of a value or expression to a boolean.


#3

Not sure I see how that fits the problem, but it would be roughly the same thing:

def x_squared(x):
    return x ** 2

In Python, ** is exponentation operator. Most programmers will be familiar with ^ but in Python, that is the bitwise XOR operator.


#4

Oh if it's a boolean then it makes sense.


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.