BAKKAB
BAKKAB

Reputation: 61

Why doesn't this simple roll die code 'print' anything?

The text book has this sample code written word for word, but when I press shift + enter, there is no output and I don't know why.

I have tried putting n = 10, both in the paranthesis and again by assigning the value 10 to the variable.

import random

def rollDie():
    return random.choice([1,2,3,4,5,6])

def rollN(n):
    result = ''
    for i in range(n):
         result = result + str(rollDie())
    print(result)

I am not getting any sort of output or error message. It says if I run rollN(10) I should get 10 random integers from 1-6, but I cannot get anything.

Upvotes: 0

Views: 107

Answers (4)

weeb
weeb

Reputation: 51

Try

import random
def rollDie(m):
    return random.choices(range(m))[0]

def rollN(n,m=6):
    print(" ".join(map(str,[rollDie(m) for i in range(n)])))

print(rollN(10))

Upvotes: 0

Chris
Chris

Reputation: 363

The Problem with this code here is that you are defining the functions, but not calling them anywhere. Try this:

import random

def rollDie():
    return random.choice([1,2,3,4,5,6])

def rollN(n):
    result = ''
    for i in range(n):
         result = result + str(rollDie())
    print(result)

rollN(10)

If you wanted to you could shorten the code to:

import random

def rollN(n):
    result = ''
    for i in range(n):
        result = result + str(return random.choice([1,2,3,4,5,6]))
    print(result)

rollN(10)

Upvotes: 0

xiaxio
xiaxio

Reputation: 631

You are not calling the rollN() function. Try this:

import random

def rollDie():
    return random.choice([1,2,3,4,5,6])

def rollN(n):
    result = ''
    for i in range(n):
         result = result + str(rollDie())
    print(result)

def main():
    rollN(10)

if __name__ == "__main__":
    main()

Upvotes: 2

alex067
alex067

Reputation: 3301

"I have tried putting n = 10,"

The problem here is that you have two functions defined but they are never executed. Thus, even by putting n = 10 in the function parameter, the function is still not being actually called upon.

Upvotes: 0

Related Questions