uTypeError:“str”和“str”的操作数类型不受支持

2024-10-01 07:32:09 发布

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

我得到这个错误:

uTypeError: unsupported operand type(s) for -: 'str' and 'str'

根据此代码:

print "what is your name?"  
x=raw_input()
print "Are you woman or man?"
y=raw_input()
print "how old are you?"
z=raw_input()
print "at what age did you or will you first travel in an plane?"
f=raw_input()

print "This is a story about a ",y," named ",x
print z-f ,"years ago",x, " first took an airplane."
print " the end"

为什么?在


Tags: oryouaninputrawistype错误
2条回答

^{}返回一个字符串,因此基本上可以得到以下结果:

print '20'-'11'

由于不能从一个字符串中减去另一个字符串,因此需要先将它们转换为数字。在

试试这个:

^{pr2}$

其次,使用描述性变量名,而不是x、y、z和f,因此如下所示:

age = float(raw_input())
...
firstPlaneTravelAge = float(raw_input())

print age-firstPlaneTravelAge, ...

另外请注意,此代码没有验证,如果用户输入的内容不是数字,它将崩溃。在

变量z和{}是字符串。Python不支持从一个字符串中减去另一个字符串。在

如果要显示数字,则必须将其转换为浮点或整数:

print int(z) - int(f),"years ago",x, " first took an airplane."

这些字符串首先是因为raw_inputalways returns a string。在

相关问题 更多 >