0

我是这方面的初学者;我今天刚开始编码,我遇到了这个问题。除了不会加、减、除或其他任何东西之外,代码类型的工作原理:它只是说TypeError: unsupported operand type(s) for -: 'str' and 'str' 或者只是输入数字。有人能帮我吗?以下是代码示例:

a = input("Enter First Name:")
b = input("Enter Last Name:")
c = (" Welcome to the New World Order")
print ("Hey " + a + b+ c)
d = (": ")
num = input("Please enter a number "+a+b+d)
num1 = input("Please enter another number "+a+b+d)
num2 = num+num1
print ('is this your number umm ... ', (num2))
input ("Press<enter>")
4

3 回答 3

2

输入始终是“str”(字符串)类型,您需要将它们转换为 int 或 float 才能对它们进行数学运算。

num = int(input("Please enter a number "+a+b+d))

请注意,如果用户输入了无效数字,整个程序将崩溃,您必须使用try来处理,除了.

于 2013-04-16T08:50:08.460 回答
2
fname = raw_input("Enter First Name:")
lname = raw_input("Enter Last Name:")
c = (" Welcome to the New World Order")
print ("Hey " + fname + " " + lname + c)
d = (": ")

num  = raw_input("Please enter a number "+ fname + " " + lname +" " + d)
num1 = raw_input("Please enter another Number "+ fname + " " + lname +" " + d)

num2 = int(num) +  int(num1)

print '%s %s is these your numbers umm ... '% (num,num1)
print '%d is sum of  your numbers umm ... '% (num2)
raw_input ("Press<enter>")

我认为这就是你想要做的。

如果你是完全的新手,你可能应该先学习 python。

使用这个Learn Python the Hard Way

或了解更多概念阅读 Python 文档

于 2013-04-16T09:04:34.080 回答
1

input()返回字符串,除非您先将它们转换为数字,否则这些字符串将被连接而不是求和(并且TypeError在尝试对它们进行减法、乘法或除法时会抛出 a ):

>>> "1" + "2"
'12'
>>> "1" - "2"
Traceback: <snip>
TypeError: unsupported operand type(s) for -: 'str' and 'str'
>>> "1" * "2"
Traceback: <snip>
TypeError: can't multiply sequence by non-int of type 'str'
>>> "1" * 2  # This is possible (but is still concatenation)!
'11'
>>> "1" / "2"
Traceback: <snip>
TypeError: unsupported operand type(s) for /: 'str' and 'str'

您需要使用以下值从您的值创建整数int()

num2 = int(num) + int(num1)

这将抛出一个ValueErrorifnum或者num1不包含任何可以解释为整数的东西,所以你可能想抓住它:

try:
    num2 = int(num) + int(num1)
    print ('is this your number umm ... ', num2)
except ValueError:
    print('You really should enter numbers!')
于 2013-04-16T08:48:47.513 回答