[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Lies in education [was Re: The "loop and a half"]

On 11/10/2017 21:52, breamoreboy at gmail.com wrote:

 >> More importantly is the fact that due to your magnificent 
performance recently you have
> been promoted to be the General Manager of my Dream Team.

Thanks, I guess.

> You can of course cement your  place when you explain how, in your language, converting an invalid 
piece of user input, which should be an integer, is always converted to 
zero, and how you handle the inevitable divide by zero errors that will 
always, eventually, occur.

You mean it shouldn't do what happens here (Py3):

  a = input("? ").split()
  x = int(a[0])
  y = int(a[1])

  print (x,y)
  print (x/y)

and somebody enters '10 0' ? I don't think you can do much about that. 
However since that thread I've tweaked the way I do this, so that here 
[non-Python code]:

  print "? "
  readln a, b    # read each as int, float or string
  println a/b    # floating point divide

this produces these a/b results for various inputs:

  10 20          # 0.500000
  10,20          # 0.500000
  10skjhf 20     # error, divide string by int
  17.9 2         # 8.950000
  10             # error, divide int by string ("")
                 # (blank) error, divide string by string
  .1e10 1e5      # 10000.000000
  ten twenty     # error, divide string by string

For throwaway programs, or for testing, or for trusted input, this is 
perfectly reasonable. For perfect error checking, you need to do a bit 
more work on either verifying input, or using more sophisticated parsing.