The input function (was Re: total and utter newbie)

Paul Boddie paul at boddie.net
Wed Nov 13 13:47:41 EST 2002


"rockbox" <rockboxb at webmail.co.za> wrote in message news:<pan.2002.11.12.23.36.32.644986 at webmail.co.za>...
> 
> value = input('Enter Value : ')
> rate = input('Enter VAT Rate : ')
> vat=(rate/100)*value
> total=value+vat

I suppose this is another reason for warning people off the 'input'
function, with the primary reason (stated in the Python tutorial) for
not using that function in many applications being the possible
subversion of the program through malicious user inputs.

Anyway, since the 'input' function can potentially return a result of
any type, yet Python's division will only work as expected (in this
case) either with future division enabled or with values of specific
types, it must be good practice to obtain and check the user-supplied
values using 'raw_input' and then a conversion to 'float' (or an
even-more-suitable numeric type).

For example:

  value_string = raw_input("Enter Value : ")
  rate_string = raw_input("Enter VAT Rate : ")
  try:
    value = float(value_string)
    rate = float(rate_string)
    vat = (rate / 100) * value
    total = value + vat
  except ValueError:
    print "Please use numbers!"

Or something like the above.

Paul



More information about the Python-list mailing list