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 Object-Oriented Python Instant Objects Methods

random.ranint

what does //return bool(random.ranint(0,1))// do i know it gives out a random integer of 0 to 1 but why are we using it

1 Answer

Hey! So,

random.randint(0, 1)

Uses the random package to generate a random whole number. We then pass the values of 0 and 1 in to generate an integer between 0 and 1. Which is 0 or 1.

Then we take this result, and run the bool function on it. This function will take a value, and will evaluate whether it is true or false. So, this will return the either True or False depending on what our random int is. In this case, 0 is False and 1 is True. This is as any non-zero number is true to the bool function.

So overall, we generate a random integer between 1 and 0, of which there is a 50/50 chance of either. Then we take that number and if its a one, we return True. If its a zero, we return false.

Hope this helps! :)