Search code examples
pythonrandomdicefunction

Python define parameter issues


My program rolls n die depending on input however only ever does on at a time. tried making it go back to d20() with another one in the if but doesn't seem to do anything.

import random

min = 1;
print "1. d20 \n2. d12 \n3. d10 \n4. d8 \n5. d6 \n6. d \n7. d100"
command = raw_input("Function: ")


def d20(n):
    done = 0
    if n>done:
      print random.randint(min, 20)
      done = done + 1
    elif n==done :
     print 'finished'

if command == "d20" or command == "1":
    die = raw_input("How many die? ")
    int(die)
    d20(die)
else:
    print 'else'

Solution

  • It sounds to me like what you're asking is how to re-run d20 n times, where n is the number of dice you chose.

    That is not the job for an if statement, but for a for loop.

    import random
    min_value = 1
    print "1. d20 \n2. d12 \n3. d10 \n4. d8 \n5. d6 \n6. d \n7. d100"
    command = raw_input("Function: ")
    
    def d20(n):
        for i in range(n):
            print random.randint(min_value, 20)
    
    if command == "d20" or command == "1":
        die = raw_input("How many dice? ")
        n = int(die)
        d20(n)
    else:
        print 'else'
    

    Output:

    Function: 1
    How many dice? 3
    5
    17
    13
    

    I have also changed the name from min to min_value because min is a python built-in function that returns a minimum of an iterable and you should not reassign it. Also you don't need ; there.

    Notice also that n = int(die) is NOT a safe command, there's nothing guaranteeing that you'll write an integer there. If you write a string that can't be converted to integer (i.e. "a"), python will raise an exception.

    Happy dnd-ing.