猿问

Elif 打印错误消息

我之前问过类似的问题,但解决方案似乎不起作用。我正在编写一款掷骰子游戏,如果任何一个玩家的数字与计算机的数字匹配,则玩家获胜,并打印一条消息“你赢了”。否则,elif 语句意味着计算机获胜并打印“你输了”。我的问题是 elif 语句不会打印“你输了”。它只是不断打印“你赢了”。


import random


die1 = 0

die2 = 0

die3 = 0

roll1 = 0

roll2 = 0

roll3 = 0


def dice_roll():

    dieroll = random.randint(1, 6)*2

    return dieroll


for die in range(12):

    die1 = int(input(f'Choose a number between 2 and 12: '))

    die2 = int(input(f'Choose a number between 2 and 12: '))

    die3 = int(input(f'Choose a number between 2 and 12: '))

    roll1 = dice_roll()

    roll2 = dice_roll()

    roll3 = dice_roll()

    if die1 or die2 or die3 == roll1 or roll2 or roll3:

        print(f'Roll # 1 was {roll1}')

        print(f'Roll # 2 was {roll2}')

        print(f'Roll # 3 was {roll3}')

        print(f'You Win! - Thanks for playing!')

    elif die1 or die2 or die3 != roll1 or roll2 or roll3:

        print(f'Roll # 1 was {roll1}')

        print(f'Roll # 2 was {roll2}')

        print(f'Roll # 3 was {roll3}')

        print(f'You Lose! - Thanks for playing!')


慕尼黑8549860
浏览 140回答 4
4回答

慕容3067478

在 for 循环内部,if 语句的参数声明不正确。这是一个帮助澄清这一点的示例:a=1b=3if a or b == 2:   print(True)else:   print(False)上面示例中的 if 语句将始终打印True,因为您询问以下问题:“如果a的值是 True/大于 0或如果b等于 2:打印 True” 在您的情况下:if die1 or die2 or die3 == roll1 or roll2 or roll3您将参数声明为“如果 die1、roll2 或 roll3 有任何 True/大于 0 值,或者如果 die3 等于 roll1:...”,因此只需将其更改为您希望它们与 Abhigyan 进行比较的实际值Jaiswal 的回答说它会正常工作。

Smart猫小萌

如果你想检查是否有任何die1, die2, die3匹配, roll1, roll2, roll3那么你可以使用:print(f'Roll # 1 was {roll1}')print(f'Roll # 2 was {roll2}')print(f'Roll # 3 was {roll3}')if {die1, die2, die3} & {roll1, roll2, roll3}:    print('You win. Thanks for playing.')else:    print('You lose. Thanks for playing.')这会检查 的集合{die1, die2, die3}和 的集合是否{roll1, roll2, roll3}有任何共同元素。另外,顺便说一句,random.randint(1, 6)*2这并不等于掷两个骰子。它是掷骰子,结果加倍;因此所有奇数都被排除,并且概率被展平。如果你想模拟掷两个骰子,你需要random.randint(1,6) + random.randint(1,6).

一只斗牛犬

添加到 khelwood 的答案中,如果您喜欢这种语法,可以使用此方法从你的代码逻辑来看,当玩家至少做出 1 次正确的猜测时,他们似乎会自动获胜(我不确定这是否是你的意图)。if die1 == roll1 or die2 == roll2 or die3 == roll3:    print(f'Roll # 1 was {roll1}')    print(f'Roll # 2 was {roll2}')    print(f'Roll # 3 was {roll3}')    print(f'You Win! - Thanks for playing!')else:    print(f'Roll # 1 was {roll1}')    print(f'Roll # 2 was {roll2}')    print(f'Roll # 3 was {roll3}')    print(f'You Lose! - Thanks for playing!')Python 评估由关键字分隔的每个条件。非空值将始终返回 True因此,如果您正在执行此方法elif die1 or die2 or die3 != roll1 or roll2 or roll3:die1 die2 roll2 roll3总是返回 True,这就是导致你的程序总是打印“你输了”的原因

明月笑刀无情

#You can do this as well    if die1 == roll1 or die2 == roll2 or die3 == roll3:    print(f'Roll # 1 was {roll1}')    print(f'Roll # 2 was {roll2}')    print(f'Roll # 3 was {roll3}')    print(f'You Win! - Thanks for playing!')  else:    print(f'Roll # 1 was {roll1}')    print(f'Roll # 2 was {roll2}')    print(f'Roll # 3 was {roll3}')    print(f'You Loose! - Thanks for playing!')
随时随地看视频慕课网APP

相关分类

Python
我要回答