On 24/05/2023 12.27, Chris Angelico wrote:
On Wed, 24 May 2023 at 10:12, dn via Python-list <python-list@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.
Yes, an excellent example to show newcomers to make use of 'the
information *provided*' - take a deep breath and read through it all,
picking-out the important information...
However, returning to "condense this into a single line", the
frequently-seen coding is (in my experience, at least):
quantity = float( input( "How many would you like? " ) )
which would not produce the helpful distinction between
line-numbers/function-calls which the above (better-formatted) code does!
Summarising (albeit IMHO):
- if relatively trivial/likely to be well-known: collect the calls into
a chain, eg
user = user.strip().lower()
- otherwise use separate lines in order to benefit from the stack-trace
- (still saying) use separate assignments, rather than chaining more
complex/lesser-known combinations
- ensure that the 'final' identifier is meaningful (and perhaps the
first, and/or even an 'intermediate' if pertinent or kept for re-use later)
- perhaps re-use a single identifier-name as a temp-variable, if can
reasonably 'get away with it'
(and not confuse simple minds, like yours-truly)
--
Regards,
=dn
--
https://mail.python.org/mailman/listinfo/python-list