随机回报与结果要求不符

时间:2018-10-19 22:11:01

标签: python random

python3.7

我正在尝试使用一个简单的“骰子”代码来(最初)允许两个结果之间有50/50的机会。但是,我已经注意到,此代码与滚动数始终不符合我期望的结果。 例如,我可以掷1并得到“此值应等于或小于3”,然后再直接掷1并得到“此值应等于或大于4”。 谁能知道是什么原因造成的?

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()

编辑: 我意识到我可能会分别调用dice()并尝试了该方法,效果很好。

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()

3 个答案:

答案 0 :(得分:1)

您正在生成两个不同的随机数,因为您两次调用了dice()。一次要打印,然后再一次用于该条件。

存储骰子的返回值,如 Rolled_number = dice()

答案 1 :(得分:1)

以下代码行称为dice函数:

print(dice())

然后此代码再次调用dice函数:

if dice() <= 3:
    print("This should be 3 or less")
else:
    print("This should be 4 or more")

这两个调用无关。第一个调用可能返回1,而下一个调用可能返回6。

如果要在两个地方使用相同的值,请只调用一次dice函数并将其结果保存在单独的变量中:

result = dice()
print(result)
if result <= 3:
    print("This should be 3 or less")
else:
    print("This should be 4 or more")

答案 2 :(得分:0)

您要两次调用函数dice(这是dice(),后面加上括号)。第一次打印结果,第二次打印结果的文本描述。为确保它们引用的是同一事物,只需调用一次函数,然后将其值分配给变量-例如:

def count():
    result = dice()
    print(result)
    if result <= 3:
        print("This should be 3 or less")
    else:
        print("This should be 4 or more")