[Tutor] Calculator functions part II

Christopher Smith csmith@blakeschool.org
Thu, 21 Jun 2001 11:11:54 -0500


Brendhan Horne is wondering why the following produces a run-time error:

ans = a * b
a = raw_input ("First Number:")
b = raw_input ("Second Number:")
ans = a*b

As someone pointed out, you have input two strings and string 
multiplication is undefined.  So you can either convert your strings to 
numbers with int() or float() *or* you can replace raw_input() with 
input().  
-----
Whereas raw_input records everything you type as a string, 
input() will allow you to enter any type of value.
-----
Example:

a=input("a:")
b=input("b:")
print a*b

If you enter 3.5 and then 2 you will see 7.0 printed.  If you enter "3" 
and 2 you will see 33 (because "3"*2 means to repeat the "3" two times) 
but if you enter "3" and "2" you will generate an error because "3"*"2" 
is not defined.  Here is the output of running the above code 3 times:

a:3.5
b:2
7.0
a:"3"
b:2
33
a:"3"
b:"2"
Traceback (most recent call last):
  File "<stdin>", line 2, in ?
  File "<stdin>", line 4, in go
TypeError: unsupported operand type(s) for *

Python is very different than something like BASIC where you can only use 
input to input a number.  As the above little program shows, you can 
enter any valid value for a and b and then if the multiplication operator 
is defined for the two things you enter then the correct result will be 
printed.

Hope this helps.

/c