Ask your own question, for FREE!
MIT 6.00 Intro Computer Science (OCW) 10 Online
OpenStudy (anonymous):

Function rand_divis_3 takes no parameters, generates & prints random number, returns True if the generated number is divisible by 3, and False otherwise. Here is my code: import random def rand_divis_3 (): print random.randint (0, 100) if random.randint (0, 100) % 3 == 0: print True else: print False print rand_divis_3 () so far the code prints out a number and a True or False statement, but when I did test runs I found that it would print False for statements that WERE divisible by 3 and True for some that weren't. Anybody see where I went wrong?

OpenStudy (turingtest):

Two things: first, the spec asks that you RETURN True or False based on divisibility by 3. Your program just prints True or False, and since it has no return statement it returns None. The issue that is confusing you is that you are calling random.randint(0, 100), printing it, then calling it *again* and testing for divisibility by 3. The second time you call random.randint(0, 100) you are generating a *different* random number from the one you see in your print statement above, as each time you call that function you get a new random number, so the number you see is not the number being tested for divisibility by 3. The solution should be obvious: call random.randint only once, store that value in a variable, and then perform your test. That, along with changing some print statements to return statements, should fix your program.

OpenStudy (anonymous):

thank you!

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!