Search code examples
pythonpython-3.xdice

How do i get a function to repeat its self without generating an exit code 0?


I made a simple dice roller with a for-in loop that takes 2 pieces of input, the number of dice and the number of sides of the dice. When the roll is made the results are printed to the screen.

After the initial roll is made I'd like to have the code begin again, with new inputs, with out generating an exit code 0.

##Original design obviously does not loop
from random import randint
import time
dice = int(input("\nHow many dice?\n   "))
sides = int(input("How many sides?\n   "))

def roll():
    for quantity in range(dice):
        time.sleep(.5)
        print(randint(1, sides))

roll()

I moved the input variables from a global scope to a local scope so they can be updated with each repetition. When ending the function by calling the function, I achieve some success. I am able to loop the process endlessly without generating an exit code 0 but any number of dice beyond 1 does not seem to register. I can only roll one dice at a time this way.

##Design 2 does not generate any exit codes and continues to loop
##endlessly but will not register more than 1 dice
from random import randint
import time

def roll():
    dice = int(input("\nHow many dice?\n   "))
    sides = int(input("How many sides?\n   "))
    for quantity in range(dice):
        time.sleep(.5)
        print(randint(1, sides))
        roll()

roll()

I've changed the function so that it does not end by calling itself. Instead I created a new function that does nothing but call the first. I've placed the redundant function after the first and have been able to successfully achieve my goal of rolling any number of sided dice as I please... twice. After two iterations/cycles this generates an exit code 0

##Current design will register all input data correctly 
##but only loops 2 times before generating an `exit code 0`
from random import randint
import time

def roll():
    dice = int(input("\nHow many dice?\n   "))
    sides = int(input("How many sides?\n   "))
    for quantity in range(dice):
        time.sleep(.5)
        print(randint(1, sides))

def roll_again():
    roll()

roll()
roll_again()

Anyone know what I'm doing wrong?


Solution

  • You need to place the game logic inside a while loop; enter zero dices to exit when you are done playing.

    from random import randint
    import time
    
    
    def roll():
        for quantity in range(dice):
            time.sleep(.5)
            print(randint(1, sides))
    
    while True:
        dice = int(input("\nHow many dice? (zero to stop)\n   "))
        if dice == 0:
            break
        sides = int(input("How many sides?\n   "))
        roll()