【问题标题】:Random numbers are the same after every loop每次循环后随机数都相同
【发布时间】:2018-09-08 22:59:36
【问题描述】:

我的程序应该为每个掷骰显示一对骰子,这按计划工作。我希望它重复多次,但每次重复它不再是随机的,只是重复从第 2 行和第 3 行分配的数字。如果我滚动 2 和 3,它每次都重复 2 和 3。 我怎样才能让它在每次循环时分配一个新的随机数?

import random
dice1 = random.randrange(1,6)
dice2 = random.randrange(1,6)

... [编辑:]

visualdice_1 =( """
            +-------+
            |       |
            |   *   |
            |       |
            +-------+""")

visualdice_2 =( """
            +-------+
            | *     |
            |       |
            |     * |
            +-------+""")

然后与

关联
def showdice():
#Dice1 Visual Execution
    if dice1 == 1:
        print(visualdice_1)
    if dice1 == 2:
        print(visualdice_2)

def start():
    confirmation = input("Would you like to roll the dice? (Y/N): ")
    if confirmation == "Y" or confirmation == "y":
        print ("You've rolled:",dice1,"and", dice2), showdice()
        return start()
    else:
        print("Goodbye")
start()

【问题讨论】:

  • 不要使用递归来实现简单的循环。你只是在浪费堆栈空间。
  • 另外,print(…), showdice(…) 充其量只是误导性代码。如果您的意思是两个单独的语句,请将它们放在单独的行中(或者,如果必须,使用分号)。您在这里所做的是以非常复杂的方式创建两个 None 值的元组,然后忽略该元组。

标签: python python-3.x loops random


【解决方案1】:

您在描述中发现了自己的问题:“第 2 行和第 3 行分配的编号”。您在循环上方分配数字。

相反,将随机数生成器放在循环中,并编辑您的 showdice() 函数以将您的骰子值作为参数:

def showdice(dice):
#Dice1 Visual Execution
    if dice == 1:
        print(visualdice_1)
    if dice == 2:
        print(visualdice_2)
    # I suppose this continues until "if dice == 6"...
    ...

def start():
    dice1 = random.randrange(1,6)
    dice2 = random.randrange(1,6)
    confirmation = input("Would you like to roll the dice? (Y/N): ")
    if confirmation == "Y" or confirmation == "y":
        print ("You've rolled:",dice1,"and", dice2)
        showdice(dice1)
        showdice(dice2)
        return start()
    else:
        print("Goodbye")
start()

否则,它将始终使用您在脚本顶部实例化的相同随机掷骰子。

【讨论】:

  • 我试过这个,但切出的 showdice() 函数不再起作用,因为它不再识别 dice1 和 dice2 变量。我可以以某种方式合并这两个函数吗?
  • if dice1 == 1: print(visualdice_1) if dice1 == 2: print(visualdice_2) etc... visualdice_1 是一个骰子的图形 visualdice_1 =( """ +---- ---+ | | | * | | | +-------+""") 像这样
  • @jeaneroo 你可能想做的就是把骰子传给 showdice,比如showdice(dice1, dice2)。当然,您还必须更改为 def showdice 行以获取这些参数,并且可能更改正文以使用这些参数而不是全局参数。
  • 您能否发布您对showdice() 的完整定义作为对您问题的修改?
  • 我编辑了我的帖子@sacul,showdice 应该将结果的“图像”(例如 1)与第一个骰子的 visualdice1 相关联
【解决方案2】:

只需重新运行:

dice1 = random.randrange(1,6)
dice2 = random.randrange(1,6) 

打印功能之前。

【讨论】:

    猜你喜欢
    • 2013-05-14
    • 2012-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多