2

Okay, so here is a piece of code. The function of the code is to take a value and determine whether or not it is odd or even.

def isEvenOrOdd(num):
    return 'odd' if num % 2 else 'even'

Now my question lies in why this works. The way I am currently looking at this, is that --

num%2 returns a value. If num is 3, then num%2 = 1. Why would the value of '1' satisfy the 'if' condition?

I assumed this was a matter of 1 and 0, but I tried the same code with %4, and if 3 is returned, it still satisfies the if statement.

I understand this may be a basic question for some, so my apologies for perhaps being slow in understanding this. Thank you!


Thank you for your help ! I actually understand it now

imanidiot
  • 37
  • 4
  • 1
    Related: [What is Truthy and Falsy? How is it different from True and False?](https://stackoverflow.com/q/39983695/4518341), [Truth value of a string in python](https://stackoverflow.com/q/18491777/4518341) – wjandrea Jul 05 '20 at 01:43
  • Even though the underlying mechanism is more general, are you aware that ``True == 1`` and ``False == 0``? – MisterMiyagi Jul 05 '20 at 20:39
  • @MisterMiyagi Yep! I was aware that True is 1 and False is 0. But what confused me was that when using modulus 4, that the values 2 and 3 were considered to be True as well. The idea of "truthy" and "falsy" kind of cleared that up for me – imanidiot Jul 05 '20 at 22:01

2 Answers2

2

The reason has to do with the "truthy-ness" of objects in Python. Every object in Python, even if it's not a boolean value, is considered "truthy" or "falsy". In this case, an integer is considered "truthy" if and only if it is not zero.

Therefore, if the number is odd, its modulus will be 1 which is considered true. Otherwise, the modulus will be 0 which is considered false.

If you switch the modulus to 4, the result will be truthy iff the remainder is not zero (i.e., if the number isn't a multiple of 4).

MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119
Daniel Walker
  • 6,380
  • 5
  • 22
  • 45
  • 2
    Additionally, the built-in function bool(Object) can be used to evaluate falsy/truthy value for any python object; in your case bool(num%n) would give you the considered boolean value for the condition, num and n being the two numbers evaluated. – cdesir Jul 05 '20 at 00:32
2

in python the, some data types has a true value or a false value, it doesn't have to be a boolean. for example

test = None
if test:
  print("working")
else:
  print("Not working")

you will notice you get an ouput of Not working the reason is for object None is regarded as False same applies for some other data type , for integer, as long as a value is zero (0) it will take it as False

So in your case, if num % 2 return 0 then you will have

'odd' if 0 else 'even' # will will return 'even'
Ibukun Muyide
  • 1,294
  • 1
  • 15
  • 23