Understanding the logic behind modulo function %

Hello,

This might be extremely simple but would love some clear explanation. I want to clarify that I know how to apply the formula as it is fairly straightforward, but I am trying to understand the reasoning behind. Here’s the code:

even_or_odd = lambda num: "odd" if num%2 else "even"
print even_or_odd(5)
print even_or_odd(10)

And here’s the question:

So when num=5 and num%2 results in 1, does the program consider 1 as True and therefore 0 as False?

In a sense, yes. In Python, 0 equates to a falsy value, that is, if you run code like this:

if 0:
  print "hi"

“hi” will not be printed, as 0 is falsy, and therefore equates to false. 1, however, is a truthy value, and thus equates to true, take this code:

if 1:
  print "hi"

“hi” will be printed, since 1 is truthy, and thus equates to true. Other falsy values include empty strings, empty lists, empty dictionaries and None.
I hope this helps!

2 Likes

That being said, just because you can write your code one way doesn’t mean you should.

I would actually argue against using lambda num: "odd" if num%2 else "even" outside of trying to solve a coding exercise.

If you were debugging a larger program, it may not be immediately apparent how this lambda function chooses the value to return. You would probably have to stop and think about it for a second. I think generally the couple of extra keystrokes (and maybe a few extra milliseconds of runtime) would be worth it for the added readability of this:

even_or_odd = lambda num: "even" if num % 2 == 0 else "odd"
2 Likes

Hi guys, I’m gonna ask something a little off topic here.
seeing in the code the following functionality:
even_or_odd = lambda num: "even" if num % 2 == 0 else "odd"

I would like to ask, what is a lambda? I know what it is in ruby, would that work the same exact way in python? are there any differences?
thanks!

Hello @thunder_coder. A lambda function is an unnamed function. It is used as a one off, or to store to a variable. As well, there can only be one expression used:

1 Like

Thank you for the answer guys. They make absolute sense. Loved the technical explanation @codeneutrino and the practical one from @el_cocodrilo.

I think the code below makes a lot of sense for simplicity’s sake.

even_or_odd = lambda num: "even" if num % 2 == 0 else "odd"

2 Likes

thanks @codeneutrino.

1 Like