我在写一个简单的程序,以帮助产生一个游戏,我的一个成员的订单。它属于我实际上并不需要的程序的CATERGORY。但现在我已经开始想它的工作。这一切都非常顺利运行,但我无法弄清楚如何停止类型错误ocurring大约完成了一半。下面的代码;

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

谁能帮助?

修改

我得到的错误是;

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'
有帮助吗?

解决方案

一个异常堆栈将已经帮助,但据推测的错误是:

materials = 1 + (level * 1)

“等级”是一个字符串,你不能对字符串做算术题。 Python是一种动态型语言,但不是一个弱类型之一。

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

在使用的是输入()的程序,这将评价输入字符串作为Python的,因此对于“1”给你的数目1的其它部分。

但是!这是超级危险的 - 想象会发生什么的号码,如果用户键入“os.remove(文件名)”代替。除非用户是只有你和你不关心,从来没有使用输入()。这将在Python 3.0(的raw_input的行为将被重命名输入)被停用。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top