Alright, making a dice roller...because I need a dice roller. Anywho, in the process of testing it came across an exception that I can't figure out how to remedy. The exception gets thrown at line 33 below:

Source code:

import random

#PUT FAILSAFES IN THIS FUNCTION.
#gets dice information
def getDiceInfo():
  print("Input number of dice (max 20):")
  diceNum = int(input())
  print("Input size of dice (ex. a 6 sided dice(standard die) would have a size of 6):")
  diceSize = int(input())
  print("Input modifier (input 0 if there is no modifier): ")
  mod = int(input())
  return [diceNum, diceSize, mod]

#returns a list of the dice "rolls"
def getDiceRolls(Num, Size):
  listNum = []
  counter = 0
  
  while counter < Num:
    listNum.append(random.randint(1,Size))
    counter += 1
  
  return listNum
  
#prints formatted sting...kinda...
def formatAndPrint(listDice, diceNum, diceSize, mod):
    tempStr = "[" + str(diceNum) + "d" + str(diceSize) + "("
    
    #problem is in this loop:
    for i in listDice:
        #exception gets thrown here
        tempStr += str(listDice[i]) + ", "
    tempStr += str(mod) +"): "
    
    listDice.append(mod)
    tempInt = 0
    for i in listDice:
        tempInt += listDice[i]
    tempStr += str(tempInt)
    
    print(tempStr)
        
  
diceNum, diceSize, mod = getDiceInfo()

listDice = getDiceRolls(diceNum, diceSize)

formatAndPrint(listDice, diceNum, diceSize, mod)


# Desired output format: [2d6](5,6): 11

The exception is out of list index range, can't add numbers to a string either, so getting rid of the int won't help...kinda at a loss here.

Recommended Answers

All 2 Replies

When you use

for i in listDice:

, "i" is already an element in listDice, not an index.
So, str(listDice) should just be str(i).

Edit...ah...I get it...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.