[Tutor] While Loop?

Alan Gauld alan.gauld at btinternet.com
Mon May 19 09:39:40 CEST 2014


On 18/05/14 23:44, Sam Ball wrote:

>> I however would like to add in another line that tells the user their account is invalid
>> before looping around and asking them to re enter their account.

OK, Time to introdusce another Pyhon idioM, the break clause.

while True:   # loop forever
     get input from user
     check/convert input
     if no errors:
        break   # exits the loop
     print error message here

"Please Input Your Account Number:")
>>     userAccountNumber = int(userAccount)
>
>> As for users typing in a name like "Charlie" or a float I would like that to spit out
>> an error also, but I haven't learned how to accomplish that yet.

The code you have will detect the error and throw an exception.
To stay in the loop you need to catch those exceptions in a try/except 
clause.

while True:
    try:
       get input
       check/convert input
       break
    except error1, error2,....:
       print error messages here

If you haven't covered try/except yet then you should read up on it
as it has several variations and subtleties.

HTH

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list