python - Setting a local bool to control flow -


i have issue in python want while loop , ask player input number of dice , number of sides random dice rolls. on second loop , additional loops want ask if continue. if input 'n' or 'no' program exits.

i able logic working global variable , changing variable in function after first time called second time user asked if want continue, understanding using global variables not python-way of doing things. improve this.

the following code works except fact user never prompted exit. know because variable keeps getting set true @ beginning of while loop, don't know how set flag without resorting global variable.

how set true/false variable locally (not-globally) , use control flow in program?

import sys import random  def get_user_input(first_loop):     if not first_loop:         another_time = input("would roll time?")         if another_time.lower() in ['n', 'no']:             sys.exit()     # allows code above output on additional loops.     first_loop = false     return first_loop  while true:     # how not reset true each time program loops?     first_loop = true      get_user_input(first_loop)      number_of_dice = int(input("enter number of dice roll: "))     number_of_sides = int(input("enter number of sides dice: "))      # create dice_total list each time create roll in loop,      # can added list , total calculated     dice_total = []      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 dice rolled is: ", dice_total) 

you're pretty close.

# move outside loop first_loop = true  while true:     if not first_loop:         get_user_input()     first_loop = false 

and no need use first_loop in get_user_input function itself:

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

it better return true/false , act accordingly instead of using sys.exit in function (gives more control):

def get_user_input():     another_time = input("would roll time?")     return not another_time.lower() in ['n', 'no'] 

and can do:

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

Comments

Popular posts from this blog

angular - Is it possible to get native element for formControl? -

unity3d - Rotate an object to face an opposite direction -

javascript - Why jQuery Select box change event is now working? -