Reputation: 1
I'm a complete beginner at this; I just started coding today and I'm having this problem.
The code kind of works except it won't add, subtract, divide, or anything else: it just says TypeError: unsupported operand type(s) for -: 'str' and 'str'
or it just puts the number. Can someone help me? Here is a example of the code:
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>")
Upvotes: 0
Views: 136
Reputation: 1121256
input()
returns strings and those would be concatenated instead of summed unless you convert them to numbers first (and would throw a TypeError
when trying to substract, multiply or divide them):
>>> "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'
You need to create integers from your values using int()
:
num2 = int(num) + int(num1)
This will throw a ValueError
if either num
or num1
does not contain anything that can be interpreted as an integer, so you may want to catch that:
try:
num2 = int(num) + int(num1)
print ('is this your number umm ... ', num2)
except ValueError:
print('You really should enter numbers!')
Upvotes: 1
Reputation: 533
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>")
I think this is what you want to do.
If you are complete newbie you should probably learn python first.
Use this one Learn Python the Hard Way
or For more concepts Read Python Documentation
Upvotes: 2
Reputation: 7600
The input is always a "str" (string) type, you need to convert those to int or float to do math operations on them.
num = int(input("Please enter a number "+a+b+d))
Note that if the user enters something that is not a valid number, the entire program will crash, to handle that you must use try, except.
Upvotes: 2