我的代码告诉Python骰子的价值有什么问题?

时间:2016-09-13 14:48:04

标签: python function if-statement return dice

以下是我的代码。这基本上就是玫瑰花瓣周围的花瓣。 如果你不熟悉这个游戏,它基本上预测了x量骰子的值,其中值为1,2,4,6 = 0的骰子和值为3 = 2的骰子和值为5 = 4的骰子 这是我的代码。

 die1 = random.randint(1,6)
    die2 = random.randint(1,6)
    die3 = random.randint(1,6)
    die4 = random.randint(1,6)
    die5 = random.randint(1,6)
    result = display_dice(die1, die2, die3, die4, die5)
    roll_guess = int(input("please enter your guess for the roll:"))
    def dicevalue(die1):

        if die1 == 1 or die1 == 2 or die1 == 4 or die1 == 6:
            die1 == 0
        elif die1 == 3:
            die1 == 2
        elif die1 ==5:
            die1 == 4
        return die1
print(dicevalue(die1))

我也尝试了这个,但我收到了错误

for values in die1:
    if die1 == 1 or die1 == 2 or die1 == 4 or die1 == 6:
        die1 == 0
    elif die1 == 3:
        die1 == 2
    elif die1 ==5:
        die1 == 4

正如你所看到的,我想用骰子[i]来总结这段代码来计算所有这些代码,但我不知道该怎么做。所以我采用了很长的方法来告诉python我在第一段中告诉你的内容。  我是python的新手,所以如果错误看起来很愚蠢请原谅我的愚蠢。 thanksss

1 个答案:

答案 0 :(得分:1)

你有:

die1 = random.randint(1,6)
die2 = random.randint(1,6)
die3 = random.randint(1,6)
die4 = random.randint(1,6)
die5 = random.randint(1,6)
result = display_dice(die1, die2, die3, die4, die5)
roll_guess = int(input("please enter your guess for the roll:"))
def dicevalue(die1):

    if die1 == 1 or die1 == 2 or die1 == 4 or die1 == 6:
        die1 == 0
    elif die1 == 3:
        die1 == 2
    elif die1 ==5:
        die1 == 4
    return die1
print(dicevalue(die1))

问题是你不能使用die1 == 4来设置一个值,它只会返回一个真值。你想要:

die1 = random.randint(1,6)
die2 = random.randint(1,6)
die3 = random.randint(1,6)
die4 = random.randint(1,6)
die5 = random.randint(1,6)
result = display_dice(die1, die2, die3, die4, die5)
roll_guess = int(input("please enter your guess for the roll:"))
def dicevalue(die1):

    if die1 == 1 or die1 == 2 or die1 == 4 or die1 == 6:
        die1 = 0
    elif die1 == 3:
        die1 = 2
    elif die1 ==5:
        die1 = 4
    return die1
print(dicevalue(die1))

在if语句下看到值从==更改为=。第二组代码不起作用,因为die1是一个int值,因此不可迭代(它不是一组值而是一个单独的值)如果你想让这段代码更简洁你就可以制作这样的骰子: / p>

dice = []
for i in range(5):
    dies.append(random.randint(1,6))

然后你可以检查所有骰子:

for die1 in dice:
    if die1 == 1 or die1 == 2 or die1 == 4 or die1 == 6:
        die1 == 0
    elif die1 == 3:
        die1 == 2
    elif die1 ==5:
        die1 == 4