OT: Addition of a .= operator

Chris Angelico rosuav at gmail.com
Tue May 23 20:27:52 EDT 2023


On Wed, 24 May 2023 at 10:12, dn via Python-list <python-list at python.org> wrote:
> However, (continuing @Peter's theme) such confuses things when something
> goes wrong - was the error in the input() or in the float()?
> - particularly for 'beginners'
> - and yes, we can expand the above discussion to talk about
> error-handling, and repetition until satisfactory data is input by the
> user or (?frustration leads to) EOD...

A fair consideration! Fortunately, Python has you covered.

$ cat asin.py
import math

print(
    math.asin(
        float(
            input("Enter a small number: ")
        )
    )
)
$ python3 asin.py
Enter a small number: 1
1.5707963267948966
$ python3 asin.py
Enter a small number: 4
Traceback (most recent call last):
  File "/home/rosuav/tmp/asin.py", line 4, in <module>
    math.asin(
ValueError: math domain error
$ python3 asin.py
Enter a small number: spam
Traceback (most recent call last):
  File "/home/rosuav/tmp/asin.py", line 5, in <module>
    float(
ValueError: could not convert string to float: 'spam'

Note that the line numbers correctly show the true cause of the
problem, despite both of them being ValueErrors. So if you have to
debug this sort of thing, make sure the key parts are on separate
lines (even if they're all one expression, as in this example), and
then the tracebacks should tell you what you need to know.

ChrisA


More information about the Python-list mailing list