1

Total beginner here,

I'm writing a program that rolls dice for the user, and I want it to be able to change the number of faces of the die per user input. I can't seem to get the variable amount_faces to work as an int for the randint() function, I get a "TypeError: cannot concatenate 'str' and 'int' objetcts" error everytime:

from sys import exit
from random import randint

def start():
    print "Would you like to roll a dice?"
    choice = raw_input(">")
    if "yes" in choice:
        roll()
    elif "no" in choice:
        exit()
    else:
        print "I can't understand that, try again."
        start()

def roll():
    print "How many faces does the die have?"
    amount_faces = raw_input(">")
    if amount_faces is int:
        print "The number of faces has to be an integer, try again."
        roll()
    else:            
        print "Rolling die...."
        int(amount_faces)
        face = randint(1,*amount_faces)
        print "You have rolled %s" % face
        exit()

start()

Any clues?

faeder
  • 13
  • 3

1 Answers1

1

int(amount_faces) does not change amount_faces in-place. You need to assign the integer object the function returns:

amount_faces = int(amount_faces)

amount_faces is not an iterable, so you cannot use the *arg syntax here:

face = randint(1,*amount_faces)

You'll have to remove the *:

face = randint(1, amount_faces)

You are also not testing for integers correctly here:

if amount_faces is int:

int is a type object, amount_faces is just a string. You can catch the ValueError thrown by int() to detect that the input was not convertible, instead:

while True:
    amount_faces = raw_input(">")
    try:
        amount_faces = int(amount_faces)
    except ValueError:
        print "The number of faces has to be an integer, try again."
    else:
        break

print "Rolling die...."
face = randint(1, amount_faces)
print "You have rolled %s" % face

You probably want to check out Asking the user for input until they give a valid response and not use recursion for program control.

Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343