This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Suggestion for a new loop type
Type: enhancement Stage: resolved
Components: Versions: Python 3.8
process
Status: closed Resolution: rejected
Dependencies: Superseder:
Assigned To: Nosy List: Happy Fakeboulder, matrixise, zach.ware
Priority: normal Keywords:

Created on 2018-08-03 19:28 by Happy Fakeboulder, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (3)
msg323065 - (view) Author: Happy Fakeboulder (Happy Fakeboulder) Date: 2018-08-03 19:28
A "while-except" loop, in which it acts like a do-while loop from other languages, except the condition is "did an exception occur during the execution of the iteration". One could specify a type of exception at the top, similar to an except block header. (sorry, I'm an idiot)
Example (the keyword might be different):

# asks for a number until the user gives one properly, then
# calculates the square of it.
whexc ValueError:
    num = int(input("Enter a number: "))
print("The square of your number is " + str(num * num)) # assuming whexc works, this will not cause an error
msg323067 - (view) Author: Zachary Ware (zach.ware) * (Python committer) Date: 2018-08-03 19:52
Ideas like this are better sent to the python-ideas@python.org mailing list for discussion rather than immediately opening an issue.  Note though that I think this has a low chance of acceptance; there's a very high bar to clear to add syntax, even higher for new keywords, and this doesn't seem to buy much over:

   while True:
       try:
           num = int(input("Enter a number: "))
       except ValueError:
           print("I said a *number*")
       else:
           break
   print("The square of your number is", num**2)

Especially considering that this version allows you to handle the error however you want, and handle different errors differently, rather than just silently restarting the loop no matter the error.

Also, this will be valid in 3.8 and achieve exactly what you're asking for:

   while not (ans := input("Enter a number: ")).isnumeric():
       pass
   print("The square of your number is", int(ans) ** 2)


Do feel free to send your idea to python-ideas anyway, I'm just one opinion :)
msg323099 - (view) Author: Stéphane Wirtel (matrixise) * (Python committer) Date: 2018-08-04 07:53
You can also use a context manager and the `with` statement.
History
Date User Action Args
2022-04-11 14:59:04adminsetgithub: 78513
2018-08-04 07:53:14matrixisesetnosy: + matrixise
messages: + msg323099
2018-08-03 19:52:12zach.waresetstatus: open -> closed

versions: - Python 3.4, Python 3.5, Python 3.6, Python 3.7
nosy: + zach.ware

messages: + msg323067
resolution: rejected
stage: resolved
2018-08-03 19:28:12Happy Fakebouldercreate