[Tutor] string integers?

Steven D'Aprano steve at pearwood.info
Mon Feb 13 00:50:03 CET 2012

William Stewart wrote:
> this is the code I have
> str1 = raw_input("Type in a String: ")
> str2 = raw_input("Type in a String: ")
> int1 = raw_input("Type in a integer variable: ")
> int2 = raw_input("Type in a integer variable: ")
> print str1 + str2 + int1 + int2
> import math
> int1 = int(raw_input(""))
> print str1,
> print str2,
> print int1, "*", int2
> print "="
> and it does not give me an error message when I run it, the program runs fine
>  except its did not multiply the 2 integer variables i entered

But you haven't asked it to multiply anything. You asked it to PRINT the two 
variables with an asterisk between them.

And further more, you don't have two integers. You have two strings that 
merely happen to contain digits. Before you can do maths on them, you have to 
tell Python to treat them as integers, not strings. You use the int() function 
(int being short for integer, in case it isn't obvious) for that:

py> x = raw_input("Enter a number: ")
Enter a number: 42
py> type(x)
<type 'str'>
py> x * 10
py> x + 1
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects

Before you can do maths on x, you have to turn it into a number:

py> x = int(x)
py> x * 10
py> x + 1

P.S. Does your computer have a Delete or Backspace key? Please trim your 
replies, there is no need to quote page after page after page of old 
conversation that you don't directly address.


More information about the Tutor mailing list