我是一个完全的初学者;我刚刚开始编码,我遇到了这个问题。
代码类型的工作除了它不会添加,减去,除法或其他任何东西:它只是说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>")
答案 0 :(得分:2)
输入始终是“str”(字符串)类型,您需要将它们转换为int或float以对它们进行数学运算。
num = int(input("Please enter a number "+a+b+d))
请注意,如果用户输入的内容不是有效数字,整个程序将崩溃,以处理您必须使用尝试,除。
答案 1 :(得分: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。
答案 2 :(得分:1)
input()
返回字符串,除非您先将它们转换为数字,否则会将它们连接起来而不是求和(并且在尝试减去,乘以或除以时会抛出TypeError
它们):
>>> "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)
如果ValueError
或num
不包含任何可以解释为整数的内容,则会抛出num1
,因此您可能想要抓住它:
try:
num2 = int(num) + int(num1)
print ('is this your number umm ... ', num2)
except ValueError:
print('You really should enter numbers!')