Phorden Phorden - 2 months ago 17
Python Question

Setting a local bool to control flow

I have an issue in Python where I want to do a while loop and ask the player to input number of dice and the number of sides to do random dice rolls. On the second loop and any additional loops I want to ask if they would like to continue. If they input 'n' or 'no' then the program exits.

I was able to get this logic working with a global variable and changing that variable in my function after the first time it is called so the second time the user would be asked if they want to continue, however from my understanding using global variables like this is not a very Python-way of doing things. I would like to improve this.

The following code works except for the fact that the user will never be prompted to exit. I know this is because they variable keeps getting set back to True at the beginning of the while loop, but I don't know how to set a flag without resorting to a global variable.

How do I set a True/False variable locally (not-globally) and use it to control flow in the program?

import sys
import random

def get_user_input(first_loop):
if not first_loop:
another_time = input("Would you like to roll another time?")
if another_time.lower() in ['n', 'no']:
sys.exit()
# This allows the code above to output on additional loops.
first_loop = False
return first_loop

while True:
# How do I not reset this back to True each time the program loops?
first_loop = True

get_user_input(first_loop)

number_of_dice = int(input("Enter the number of dice you would like to roll: "))
number_of_sides = int(input("Enter the number of sides for the dice: "))

# create the dice_total list so each time we create a roll in the loop,
# it can be added to a list and the total calculated
dice_total = []

for die in range(number_of_dice):
random_roll = random.randrange(1, number_of_sides)
print("You rolled: ", random_roll)
dice_total.append(random_roll)

dice_total = sum(dice_total)
print("The total of the dice rolled is: ", dice_total)

Answer

You're pretty close.

# move this outside the loop
first_loop = True

while True:
    if not first_loop:
        get_user_input()
    first_loop = False

And no need to use first_loop in the get_user_input function itself:

def get_user_input():
    another_time = input("Would you like to roll another time?")
    if another_time.lower() in ['n', 'no']:
        sys.exit()

It would be better to return True/False and act accordingly instead of using sys.exit in a function (gives you more control):

def get_user_input():
    another_time = input("Would you like to roll another time?")
    return not another_time.lower() in ['n', 'no']

And then you can do:

while True:
    if not first_loop:
        if not get_user_input():
            # break out of the loop
            break