-6
votes
def is_odd(num):
    # Return True or False, depending on if the input number is odd. 
    # Odd numbers are 1, 3, 5, 7, and so on. 
    # Even numbers are 0, 2, 4, 6, and so on. 

I'm wondering what you would do from here to get those answers.

2
I'm wondering what you have tried so far - Anthony Forloney
You should really tell us what you've tried up until now. Even if what you tried hasn't worked it is better than nothing. Playing around with the language is what is going to make you better, not asking the internet. - JonathanV
Clue: How do you do it without a computer? - martineau

2 Answers

29
votes
def is_odd(num):
    return num & 0x1

It is not the most readable, but it is quick:

In [11]: %timeit is_odd(123443112344312)
10000000 loops, best of 3: 164 ns per loop

versus

def is_odd2(num):
   return num % 2 != 0

In [10]: %timeit is_odd2(123443112344312)
1000000 loops, best of 3: 267 ns per loop

Or, to make the return values the same as is_odd:

def is_odd3(num):
   return num % 2

In [21]: %timeit is_odd3(123443112344312)
1000000 loops, best of 3: 205 ns per loop
8
votes
def is_odd(num):
   return num % 2 != 0

Symbol "%" is called modulo and returns the remainder of division of one number by another.