views:

656

answers:

1

I'm writing a simple program to help generate orders for a game I'm a member of. It falls into the catergory of programmes I don't actually need. But now I've started I want it to work. It all pretty much runs smoothly but I can't figure out how to stop a type-error ocurring about half way through. Here's the code;

status = 1

print "[b][u]magic[/u][/b]"

while status == 1:
    print " "
    print "would you like to:"
    print " "
    print "1) add another spell"
    print "2) end"
    print " "
    choice = input("Choose your option: ")
    print " "
    if choice == 1:
        name = raw_input("What is the spell called?")
        level = raw_input("What level of the spell are you trying to research?")
        print "What tier is the spell: "
        print " "
        print "1) low"
        print "2) mid"
        print "3) high"
        print " "
        tier = input("Choose your option: ")
        if tier == 1:
            materials = 1 + (level * 1)
            rp = 10 + (level * 5)
        elif tier == 2:
            materials = 2 + (level * 1.5)
            rp = 10 + (level * 15)
        elif tier == 3:
            materials = 5 + (level * 2)
            rp = 60 + (level * 40)
        print "research ", name, "to level ", level, "--- material cost = ",
                materials, "and research point cost =", rp
    elif choice == 2:
        status = 0

Can anyone help?

edit

The error I get is;

Traceback (most recent call last):
  File "C:\Users\Mike\Documents\python\magic orders", line 27, in <module>
    materials = 1 + (level * 1)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
+8  A: 

A stacktrace would've helped, but presumably the error is:

materials = 1 + (level * 1)

‘level’ is a string, and you can't do arithmetic on strings. Python is a dynamically-typed language, but not a weakly-typed one.

level= raw_input('blah')
try:
    level= int(level)
except ValueError:
    # user put something non-numeric in, tell them off

In other parts of the program you are using input(), which will evaluate the entered string as Python, so for “1” will give you the number 1.

But! This is super-dangerous — imagine what happens if the user types “os.remove(filename)” instead of a number. Unless the user is only you and you don't care, never use input(). It will be going away in Python 3.0 (raw_input's behaviour will be renamed input).

bobince
thanks for that, works perfectly now
Of course, "level * 1" is valid if s is any sequence like a string.
Ali A