如何对输出值进行额外的功能?

时间:2019-08-07 17:45:48

标签: python-3.x

我需要访问“ Attacker”和“ Defender”骰子的结果并进行比较。不知道该怎么做。我已经尝试过IF循环(if a > b, print "lala"),但是它不起作用。

import random
counter = 0
while counter < 1:
    a = random.randrange(1,6)
    b = random.randrange(1,6)
    c = random.randrange(1,6)
    print("Attacker:")
    print(a,"-", b,"-", c)
    counter += 1
counter = 0
while counter < 1:
    d = random.randrange(1,6)
    e = random.randrange(1,6)
    g = random.randrange(1,6)
    print("Defender:")
    print(d,"-", e,"-", g)
    counter += 1

预期程序正在为每个玩家打印范围(0-6)中的3个随机数,然后比较以“ Player1(或P2)获胜”为结果的结果

2 个答案:

答案 0 :(得分:0)

a循环之外声明g-while变量。变量的范围决定了可以在哪里使用它们。您已经在while循环中声明了这些变量,因此只能在它们的while循环中使用它们。

a = None  # or whatever default value
b = None
...
g = None

counter = 0
while counter < 1:
    a = random.randrange(1, 6)
    ...

counter = 0
while counter < 1:
    d = random.randrange(1, 6)
    ...

if a > b:
    ...

答案 1 :(得分:0)

import random
counter = 0
number_of_dice=3
playerA = [0]*number_of_dice
playerB = [0]*number_of_dice

#let's fill those arrays
for i in range(number_of_dice):
    playerA[i] = random.randrange(1,6)
    playerB[i] = random.randrange(1,6)

print("Player A threw ",playerA)
print("Player B threw ",playerB)

#now evaluate the scores
wins_for_A = 0
wins_for_B = 0
for i in range(number_of_dice):
    if playerA[i]>playerB[i]:
        wins_for_A+=1
    elif playerA[i]<playerB[i]:
        wins_for_B+=1
    #no else... that means a draw

if wins_for_A>wins_for_B:
    print("player A wins")
elif wins_for_A<wins_for_B:
    print("player B wins")
else:
    print("draw")

它输出类似

Player A threw  [5, 3, 3]
Player B threw  [3, 2, 3]
player A wins

Process finished with exit code 0