简体   繁体   中英

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:

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. 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 . 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. 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, ...).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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