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

Even or odd loop code

How are these two codes different, and why is the top code accepted while the bottom is not?

import random

start = 5

def even_odd(num): return not num % 2

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

import random

def start(): 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

1 Answer

First of all, i would suggest to try Markdown Cheatsheet when you post anything on the forum, it would help you a lot by giving a better presentation to what you are writing.

So your code is:

Code 1:

import random
start = 5

def even_odd(num): 
    return not num % 2

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

Code 2:

import random
def start(): 
    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

Simply, start is a global variable in code-1 whereas its defined inside the start() in code-2 so you cannot use it anywhere else outside start() unless you define it again.