Nicholas Cannon <nicholascann...@gmail.com> wrote:
> Guys i am only a beginner at python most of the stuff you are saying i
> need to do i dont understand.
Then listen and try to learn :-)
In C it is customary to do all sorts of sanity checks in advance.
Validating user input is an example. We can call this "to ask permission".
This coding style is often neccessary in C, but not recommended in Python.
In Python we just try to do what we want. If it fails, we get an exception,
e.g. a ValueError. Then we do something with this error instead. We can
call this "to ask forgiveness". If you think you need a validator, you are
very likely thinking "unpythonic". Thus, we don't have to check that the
user typed in a float. We just try to construct a float from the input. If
it fails it wasn't convertible to a float. But you don't have to know that
in advance. All the checks you need to do is already in the function
float(). You don't have to repeat them. float() will succeed or raise an
error. Same for conversion to int: If the user input is convertible to int,
the function int() will do that. If it's not convertible, you get an
exception. Just trap the exception and deal with it when it occurs.
But don't use try/except everywhere! Some exceptions might be due to an
error in your own code, i.e. not in the user input. Those errors you should
not silence, but let your program crash and abort. Then you will know there
is an error in your code. That is what an unhandled exception will do, and
in addition it will tell you where the error is and what it is, so just
leave those exceptions unhandled.