gpt4 book ai didi

Python 类型错误问题

转载 作者:太空宇宙 更新时间:2023-11-03 12:26:02 26 4
gpt4 key购买 nike

我正在编写一个简单的程序来帮助为我参与的游戏生成订单。它属于我实际上不需要的程序类别。但现在我已经开始了,我希望它能发挥作用。一切都运行得很顺利,但我不知道如何阻止大约一半的类型错误发生。这是代码;

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)

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

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

在程序的其他部分,您正在使用 input(),它将输入的字符串作为 Python 进行评估,因此“1”将为您提供数字 1。

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

关于Python 类型错误问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/320827/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com