我正在尝试基于python中的用户输入在字符串中生成随机数列表

时间:2018-10-05 02:39:57

标签: python list

我正在尝试为DnD创建一个简单的骰子掷骰程序,并且正在尝试制作一个骰子掷骰程序,以便您可以掷出任意数量的骰子,并向您显示掷骰的列表。我对python还是有些生疏,并且遇到了困难。这就是我所拥有的(注意:这是一个4面骰子):

List = []

def Dice():
     List = List + [random.randint(1, 4)]
     return List

while multiplier > 0:
     Dice()
     multiplier = multiplier - 1   #multiplier is how many times you rolled the dice
print(Dice())

无论何时运行,我都会收到以下错误消息:

Traceback (most recent call last):
   File "C:/Users/Un-Local User/Desktop/Python/Dice Sim.py", line 68, in <module>
      Dice()
   File "C:/Users/Un-Local User/Desktop/Python/Dice Sim.py", line 5, in Dice
      List = List + [random.randint(1, 4)]
UnboundLocalError: local variable 'List' referenced before assignment

2 个答案:

答案 0 :(得分:0)

使用append阅读here

对于未绑定错误,这里有一个不错的explanation

from random import randint

List = []
def Dice():
     List.append(randint(1, 4))
     return List

multiplier = 4
while multiplier > 0:
     Dice()
     multiplier = multiplier - 1   #multiplier is how many times you rolled the dice

print(Dice())

答案 1 :(得分:0)

您必须将变量List设置为全局变量,才能在函数中使用或修改它们:

import random
global List
List = []

def Dice():
    global List
    List = List + [random.randint(1, 4)]
    return List

while multiplier > 0:
    Dice()
    multiplier = multiplier - 1   #multiplier is how many times you rolled the dice
print(Dice())