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

Need some HELP, please!

Hello. I have some problems with a small peace of code. And I can't figure out what is wrong. Can someone explain to me why this code is not returning the write 'answers'.

import random

def num():
    return random.choice(range(7, 9))

def game():
    if num() == 8:
        print(num(), "==", 8)
    else:
        print(num(), "!=", 8)

x = 0
while x <= 20:
    x += 1
    game()

The output is all messed up. I get something like: 7 == 8 8 == 8 8 != 8 and so on...

I want to know what I did wrong.

Afloarei Andrei

I deleted your answer as requested. You should be able to delete your own answers should you need to again in the future.

At the bottom of your answer you should see a drop down menu indicated by 3 dots. There should be an option in there to delete.

2 Answers

Hi Afloarei,

You're sometimes seeing incorrect output because you're calling the num() function multiple times in your game() function. You're calling it inside your if condition and then calling it again inside your print calls. It's generating a new random number each time you call it. So your print statements aren't necessarily using the same number as what was used to check your if condition.

I recommend that you call the num() function one time at the top of your game() function and store it in a variable.

Something like this:

random_num = num()

Then use that variable in both your if condition and your print statements. That way you guarantee that all parts of the code are using the same random number.

So obvious and I didn't see it...Thanks for the help! :)