niomsilicon.blogg.se

Examples of programs written in python
Examples of programs written in python













examples of programs written in python

Similarly, when something unexpected happens, e.g., a temporary file you created disappeared at the midway point, raise a RuntimeError. When you never expect the input to be negative, raise a ValueError with an appropriate message.

examples of programs written in python

In fact, the exception handling system in Python is mature, and we should use it. It is also a good practice to make our code harder to be misused, i.e., not to let variables go out of our intended range without notice. Having these guard rails in place will guarantee our half-baked code is never used in the way it is not supposed to. This is useful when we gradually develop our program, which we implement one case at a time and address some corner cases later.

examples of programs written in python

NotImplementedError: Function tanh is not implementedĪs you can imagine, we can raise NotImplementedError in places where the condition is not entirely invalid, but it’s just that we are not ready to handle those cases yet. However, we want to point out that the following is a wrong but common way to do sanitation: We do this only where it can go wrong, namely, on the interface functions that we expose as API for other users or on the main function where we take the input from a user’s command line. Usually, we do not do this on every function to save our effort as well as not to compromise the computation efficiency. Certainly, that is a balance you need to decide on. You may wonder if it is necessary to make our code lengthier by adding these sanitations. Canonicalized input is easier to check for conformation (e.g., we know /etc/passwd contains sensitive system data, but we’re not so sure about /tmp/./etc/././passwd). For example, a URL should start with “ and a file path should always be a full absolute path like /etc/passwd instead of something like /tmp/./etc/././passwd. This means we should make the input in a standardized format. Otherwise, we have to consider three different cases that we call range(), namely, range(10), range(2,10), and range(2,10,3), which will make our while loop more complicated and error-prone.Īnother reason to sanitize the input is for canonicalization. Then, the while loop can be written as such. But with the two if statements at the beginning of the function, we know there are always values for variables a, b, and c. This is a simplified version of range() that we can get from Python’s built-in library.















Examples of programs written in python