Python类型错误问题

2024-06-07 07:17:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一个简单的程序,以帮助生成订单的游戏,我是一个成员。它属于我实际上不需要的程序类别。但现在我已经开始了,我希望它能起作用。这一切运行得很顺利,但我不知道如何阻止一个类型错误出现在大约一半的时间里。这是密码

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'

Tags: theto程序inputstatuslevelwhatrp
1条回答
网友
1楼 · 发布于 2024-06-07 07:17:02

stacktrace可能会有帮助,但估计错误是:

materials = 1 + (level * 1)

“level”是字符串,不能对字符串进行算术运算。Python是一种动态类型语言,但不是弱类型语言。

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

在程序的其他部分中,您正在使用input(),它将以Python的形式计算输入的字符串,因此for“1”将给出数字1。

但是!这是非常危险的 - 想象一下如果用户键入“os.remove(filename)”而不是数字会发生什么。除非用户只是你,你不在乎,否则不要使用input()。它将在Python3.0中消失(raw_input的行为将被重命名为input)。

相关问题 更多 >