0

I have a function which returns either True or False. I'm trying to perform a loop where that function is called several times until it returns False, and count how many times it ran.

import random as rand

def test_function():
   return rand.random > 0.5

count = 0 

while test_function():
   count += 1

print count

All this is doing is running it once though, and holding whatever value it got.

2
  • Short version of your program: python -c "from random import randint as r; print r(0,1)" or even print "mean count: 0.5" :-) Commented Feb 14, 2014 at 18:35
  • Thanks but this isn't actually my code, it was just easier to follow than what I'm really doing. Commented Feb 14, 2014 at 19:07

2 Answers 2

4

You forgot to actually call rand.random. Add () after it to do this:

return rand.random() > 0.5

Below is a demonstration:

>>> import random as rand
>>> rand.random
<built-in method random of Random object at 0x01DC02A8>
>>> rand.random()
0.4878133430124779
>>>

Right now, your code is testing if the function object itself is greater than 0.5.

Sign up to request clarification or add additional context in comments.

1 Comment

Actually, it appears it evaluates to True: >>> import random; >>> random.random > 0.5; True
3

You have to call the function with ().

return rand.random() > 0.5

1 Comment

Oh jeez. I had that part right in the code I copied this from, but this helped me realize the problem I was having was in a different part of the script. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.