简体   繁体   English

随机将一个数字添加到列表中

[英]randomly adding a number to a list

I am writing a program that rolls a random number.我正在编写一个滚动随机数的程序。 This program also has to roll the die x amount of time i using class Die: Here is the code:该程序还必须使用类 Die 滚动骰子 x 时间:这是代码:

class Die:
    def __init__(self, n):          # Someone commented why am I using self.__n or why when i don't use so is it ok to remove this line from the init function it wasn't working until i put this I believe it is its scope
        self.__n = n

def get_sides(self, n):             #Meant to just return the same number "n" is
    return n

def roll_die(self, n):              # I changed to this to simply return a random int
    return random.randint(1,n)

def roll_multiple(self,n):          # The ideas is to return a list i.e. "[2,4,6,349]"
     for i in range(n):

        return n

#       for i in range(1, n):
#           while i < n:
#              i = random.randint(i, n)
            #lst = [i]
            #lst.append(random.randint(i, n))
            #lst.append(random.randint(i, n))
            #lst.append(random.randint(i, n))



def main():

#n = eval(input("Enter the sides on the dies: "))
n = 43
idie = Die(n)
print(idie.get_sides(n))
print(idie.roll_die(n))
print(idie.roll_multiple(5))

main()

I have to mimic rolling the die "5" times.我必须模仿掷骰子“5”次。 The program has to be called as you can see at the bottom, but I still don't have the hang of iteration or lists it seems because this type of problem has been stumping for a bit now.正如您在底部看到的那样,必须调用该程序,但我仍然没有迭代或列表的窍门,因为这种类型的问题现在已经困扰了一段时间。 Thanks for any help.谢谢你的帮助。

Since you're returning i and n in roll_die and roll_multiple , it will only iterate through the for-loop once which means you will get only one random number when you call roll_die and get 0 when you call roll_multiple .既然你回来时,n roll_dieroll_multiple ,它只会通过迭代for循环一次。这意味着当你打电话,你会得到一个唯一的随机数roll_die并得到0,当你调用roll_multiple Based on the name of the function ( roll_die ), you probably want to just return a random integer without using a for-loop, and call roll_die multiple times using a for-loop.根据函数的名称 ( roll_die ),您可能只想返回一个随机整数而不使用 for 循环,并使用 for 循环多次调用roll_die Based on the code you have, I'm not sure what your objective is (especially the roll_die where you set the minimum to be 0, 1, 2, ...).根据您拥有的代码,我不确定您的目标是什么(尤其是将最小值设置为 0、1、2……的roll_die )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM