[Tutor] Numbers appearing as strings in program
Mon, 14 Aug 2000 14:30:08 -0700 (PDT)
> I've written this simple calculator program but I've got a problem
> with it: The NUMBERS are "turning" to STRINGS!! I'm not sure what is
> wrong cuz I'm new to Python. Does the built in statement 'raw_input'
> only support strings???If so, how can I get numbers as input from the
> user? Here is the script calculator.py:
You got it --- raw_input() will always return a string back to you.
Don't worry; there are a few ways to get the numbers back.
For example, you can use the int() or float() functions on those strings,
which will return the numerical values of those strings.
On an unrelated topic, since you're always reading in 'x' and 'y' for the
operations, you can optimize slightly by making a small input function of
your own. Here's one that can take care of the number conversions for
you, so you don't have to worry about it:
x = raw_input("Enter a value for X:")
y = raw_input("Enter a value for Y:")
return (float(x), float(y))
After you make a function like readNumbers(), you can use it like this in
if (choice == 'A'):
x, y = readNumbers()
and it should make things easier for you. If you find yourself repeating
the same code, it's usually a prime target for making a convenient
> Another thing, the Addition function works but instead of adding the
> numbers like (1 + 1 = 2) it concatenates it like (1 + 1 = 11). The
> rest of the functions don't work at all. Any help would be deeply
The reason that's happening is because of the string stuff --- addition
for strings is defined to be string contatenation. And since raw_input
was giving you back strings. It's a different bug, but from the same
String addition is really useful if you want to put two strings together:
>>> "Hello" + " world!"
But you have to be careful not to expect number addition when you have
>>> "1" + "1"
And trying to mix the two just doesn't work:
>>> 1 + "1"
Traceback (innermost last):
File "<stdin>", line 1, in ?
TypeError: number coercion failed
If you have any questions on this, email us back. Good luck to you!