Reputation: 49
python3.7
I am trying to use a simple "dice" code to (originally) allow for a 50/50 chance between two outcomes. However I have noticed that this code does not consistently match the outcome I expect with the number rolled. For example, I can roll a 1 and get "This should be 3 or less" and then roll a 1 again directly after and get "This should be 4 or more". Can anyone see what is causing this?
import random
def dice():
roll = random.randint(1,6)
return roll
def count():
print(dice())
if dice() <= 3:
print("This should be 3 or less")
else:
print("This should be 4 or more")
count()
edit: I realized that I may be calling dice() separately and tried this, which worked.
import random
def dice():
roll = random.randint(1,6)
return roll
def count():
x = dice()
print(x)
if x <= 3:
print("This should be 3 or less")
else:
print("This should be 4 or more")
count()
Upvotes: 0
Views: 51
Reputation: 33275
This line of code calls the dice function:
print(dice())
And then this code calls the dice function again:
if dice() <= 3:
print("This should be 3 or less")
else:
print("This should be 4 or more")
The two calls are not related. The first call might return 1, while the next one might return 6.
If you want the same value to be used in both places, call the dice function only once and save its result in a separate variable:
result = dice()
print(result)
if result <= 3:
print("This should be 3 or less")
else:
print("This should be 4 or more")
Upvotes: 1
Reputation: 18249
You're calling the function dice
twice (this is what dice()
, with the parentheses afterwards, does). The first time when you print the result, the second time when you print the text description of the outcome. To make sure they're referring to the same thing, just call the function once but assign its value to a variable - eg:
def count():
result = dice()
print(result)
if result <= 3:
print("This should be 3 or less")
else:
print("This should be 4 or more")
Upvotes: 0
Reputation: 469
You are generating two different random numbers, because you're calling dice() twice. Once for printing then another time for the condition.
Store the return value of dice, as in rolled_number = dice()
Upvotes: 1