[Tutor] Beginners question
DL Neil
PyTutor at danceswithmice.info
Tue Mar 31 18:37:10 EDT 2020
With apologies to the OP for 'hi-jacking' the thread, a further
question, if I may:-
On 1/04/20 12:50 AM, Peter Otten wrote:
>>>> while True:
>>>> # get input
>>>> # if input means quit
>>>> break # break out of the loop
>>>> # proceed with whatever you want to do
>>> The above always looks so untidy to my eye. Could we use the 'walrus
>>> operator' instead of while True:?
> While I prefer the old-fashioned way here's how to spell the while loop
> without break:
>>>> while (word:=input("Enter a word: ")) != "quit":
> ... print(f"The word is {word!r}")
> ...
> Enter a word: hello
> The word is 'hello'
> Enter a word: world
> The word is 'world'
> Enter a word: quit
@Peter: why the preference for "the old-fashioned way"?
(perhaps answered below...)
Earlier, I opined that the first code-snippet is "untidy".
Regrettably, so is the second (equally, an opinion), in that it is
starting to look as if we are attempting to do 'too much' in one line of
code. Hey, isn't that the 'virtue' of the walrus operator?
Has such become liable to a similar judgment in deciding whether, for
example; a complex list-comprehension expression should be coded in its
compact form, or broken-out into a more readable for-loop?
(particularly when dealing with lesser-mortals such as I).
What more could we do?
- users may have become habituated to typing "semaphores" such as "quit"
to end input. However, Python allows considerable flexibility over
previous generations of languages. Could we instead invite the user to
hit Enter (with no data)?
- how about Ctrl-Z (which after-all means EoF ("End of File") ) or some
similar Exception-raising practice?
I guess try-ing for Ctrl-Z would necessitate an additional two
blocks/indentation.
Might dispensing with the 'quit rule', allow the following code?
while word:=input("Enter a word: "):
print(f"The word is {word!r}")
Does that satisfy the above (and any other) coding-criteria?
(again: apologies for not having v3.8 to test for myself)
--
Regards =dn
More information about the Tutor
mailing list