I have a ton of variables that I need to create and reference, for example diceOutCome2, diceOutCome4… diceOutCome12, diceOutComeHornHigh, diceOutComeHornFive, etc and I constanctly need to reference them so I wish to store them as global variables instead of passing them around as parameters.
Most importantly, I am also trying Not to reference them with index numbers but instead with names or property like counter.diceOutCome2… 2 here is not the number 2 outcome but outcome with dice rolled 1 and 1, four would store dice total with 2,2, 1,3 information etc.
What’s the most efficient way and the correct syntax to create them?
def setGlobalVariables():
counter=[]
for i in range (0, 12):
global counter["count_"+i]=0
For properties like “diceOutCome2”, you are actually better off using a list with index numbers, like
counter.diceOutCome[2]. This allows you to easily iterate over all the list of diceOutcomes, or to refer to the outcome before the 5th dice outcome ascounter.diceOutCome[n-1]when n is 5.Horn bets can be computed as methods on an object, either the counter object that you referenced before (
counter.highHorn(5)could evaluate the winning or losing of a high horn bet oncounter.diceOutcome[5]), or on the object used to represent the die roll outcome, a list of which is kept in diceOutCome, as incounter.diceOutcome[5].highHorn(). OrHighHorncould be an subclass ofBet; an instance ofHighHornis constructed using a DiceOutcome, andHighHornwould implement awins()method, defined in abstract onBet, to be implemented in subclasses – evaluating it asHighHorn(counter.diceOutCome[5]).wins(). Since the diceOutcomes are all attached tocounter, then this might be a logical item to pass around to related methods, or a logical item on which to define those methods.In general, if you start thinking about defining variable names with trailing numeric digits, for instance that
something1,something2,something3are going to be of use in your program, you must immediately stop and replace with a list calledsomethings, and access them using list indices likesomethings[2].(Note – For ease of communication, I am using 1-based indexing to correspond to the descriptions – in actuality, indexes to the items in a sequence are 0-based, hence the 5th item would really be referenced as
sequence[4], the item before it issequence[4-1], the 1st item being found atsequence[0]`. The point is, this is the case where indexes make sense, not numeric suffixes on variable names.)