Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Basics (2015) Letter Game App Even or Odd Loop

nicholasdevereaux
nicholasdevereaux
16,353 Points

How does python know if the number is even or odd by this IF statement: if even_odd(number):

import random

start = 5

def even_odd(num): return not num % 2

while start: number = random.randint(1, 99) if even_odd(number): print("{} is even".format(number)) else: print("{} is odd".format(number)) start -= 1

2 Answers

Martin Cornejo Saavedra
Martin Cornejo Saavedra
18,132 Points

even_odd(number) is a function that uses the modulo operator '%' to calculate the residual of the number. It is well know that even numbers have residual equal to 0, and odd numbers don't. That's why when the remainder is 0, the 'not' operator negates the 0, thus returning a 'True'(true, it is even) statement (oposite of 0 is 1 or True in python). Else, it returns a 'False' statement.

nicholasdevereaux
nicholasdevereaux
16,353 Points

Okay thank you! I didn't know even_odd is a built in function. I thought it was just a random name given to the function.

even_odd isn't a built-in function. It's a function that you write. The modulo operator % is how you can tell if a number is odd or even and that is built into python.

def divide(num1, num2):  # you define a function called "divide"
  return num1 / num2  # behind the scenes you call python's built-in / operator

# almost the same logic for even_odd
def is_even(num1):
  return num1 % 2 == 0 # in math, a number is even if it is divisible by 2 and has no remainder.
  # for example, 8 / 2 equals 4 remainder 0 so it is even. 
  # 10 / 2 is 5 remainder 0 so it is even. 
  # 11 / 2 is 5 remainder 1 so NOT even.
Martin Cornejo Saavedra
Martin Cornejo Saavedra
18,132 Points

nicholas, as lambda says, it isn't a built-in function, it is a custom one, the code that defines the function is the one you posted:

def even_odd(num): return not num % 2