I'll start off by saying that not only am I new to Python but programming in general. But the problem is that whenever I have the user put in a number, then have the user put in another number, I can't get the two x,y variables to add up. the closest I've gotten was have x=2, y=3 and have it show up 23, NOT 5.

Code:
x = raw_input ("Give me the first number to add ")
print ("ok, ") + x
print ("got it!")


y = raw_input ("Now give me the second number to add! ")
print ("alright ") + y


print ("The answer to your problem is ") + (x+y)


raw_input ("press <Enter>")

Recommended Answers

All 2 Replies

The problem is that raw_input returns a string and not an integer. You must convert it to integer with the int function. See this example

>>> x = raw_input("enter a number: ")
enter a number: 2
>>> print x, repr(x), type(x)
2 '2' <type 'str'>
>>> x = int(x)
>>> print x, repr(x), type(x)
2 2 <type 'int'>

The result of raw_input is a string, not an integer, so the + operator on the two strings (+ is concatenate for strings) correctly gives you "23" from "2" + "3"

If you want an integer, you can cast it: x = int(raw_input("Give me the first number: ") and so forth. Of course if the user enters "I quit" or some such thing, the cast will raise an exception. To avoid that, you put the whole thing inside a try: block. But if the user enters a floating point number (1.3 or 1.0101e-12 or ...) that should probably work too, and your int cast will do the wrong thing. This whole "programming" thing is full of such gotchas.

You could probably profit from a visit here: http://docs.python.org/tutorial/index.html (and by poking around in http://docs.python.org in general)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.