【问题标题】:Simple Python - How to change a variable with every repeat of a for loop?简单的 Python - 如何在每次重复 for 循环时更改变量?
【发布时间】:2020-08-11 14:28:57
【问题描述】:

我的代码用于骰子游戏。它有五轮,并在每轮结束时将总数相加。我想找到一种方法,能够在玩家结束时将所有五个回合的总数相加。我在想最简单的方法是在每个循环结束时更改总变量的名称,例如。 roundtotal1、roundtotal2 等。但我不确定,我想看看你的想法。谢谢:)

我的代码:

import random
import time

p1 = ('Bob')
p2 = ('Larry')

#PLAYER 1'S TURN

print('Welcome to Dice Game,',p1)

#Prints round number of 5 rounds
for x in range (1,6):
    round = ('%s' % x)
    print('Round %s' % x)
    time.sleep(0.5)
    print()

#Rolls the first die
    input('Press ENTER to roll your first die...')
    num1 = random.randint(1,6)
    time.sleep(0.5)
    print('...')
    time.sleep(1)
    print('You scored a',num1,'on your first roll!\n')

#Rolls the second die
    time.sleep(2)
    input('Press ENTER to roll your second die...')
    num2 = random.randint(1,6)
    time.sleep(0.5)
    print('...')
    time.sleep(1)
    print('You scored a',num2,'on your second roll!\n')

#If dice rolls 1 and 2 are the same, roll a third die
    time.sleep(1)
    num3 = 0
    if num1 == num2:
        num3 = random.randint(1,6)
        print('As you rolled a double, you get a third die!')
        input('Press enter to roll your third die...')
        time.sleep(0.5)
        print('...')
        time.sleep(1)
        print('You scored a',num3,'on your third roll!\n')
    else:
        pass

#Print the total for the round
    time.sleep(1)
    roundtotal = num1+num2+num3
    print('ROUND TOTAL:',roundtotal)
    print()
    print()

print('GAME TOTAL:',) #Round totals from rounds 1-5 added together
#How do I do this?

【问题讨论】:

  • 收集列表中的所有值?
  • 在主循环之前的代码顶部,创建一个变量grandtotal = 0。作为主循环的最后一步,将roundtotal 添加到grandtotal。

标签: python loops for-loop variables


【解决方案1】:

最简单的方法是设置另一个变量,只添加您滚动的任何内容,因此它将在代码开头附近定义total1 = 0,然后在num1 = random.randint(1,6)行之后添加total1 += num1将让您存储总数用于您在该变量中的滚动,以便您以后可以使用它。

如果您想将玩家拥有的所有掷骰分别存储在一个变量中,那么您可以使用列表的概念

【讨论】:

    猜你喜欢
    • 2021-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-06
    • 2017-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多