[Tutor] Breaking out of loop...
beachkid at insightbb.com
Fri Nov 20 18:53:05 CET 2009
Alan Gauld wrote:
> "Ken G." <beachkid at insightbb.com> wrote
>> I am trying to break out of a loop posted below. When asked for
>> monthdate, it should break out if I entered the number zero and it
>> does not. GRRR. Been working on this for almost an hour.
>> monthdate = 999
>> while monthdate <> 0:
> You are comparing monthdate with a number but raw_input returns a string.
> Also <> is deprecated, change it to !=
> while monthdate != "0":
> and it should work.
>> monthdate = raw_input('Enter the month and date in two digit
>> format each: ') month = monthdate[0:2]
>> date = monthdate[2:4]
>> year = ('2009')
>> print month, date, year
> With this code you always process monthdate so if the user
> types zero it will fail.
> The idiomatic Python way to do this is:
> while True: # loop "forever"
> monthdate = raw_input('Enter the month and date in two digit
> format each: ')
> if monthdate == "0":
> break # exit the loop
> month = monthdate[0:2]
> date = monthdate[2:4]
> year = ('2009')
> print month, date, year
> That change means you can get rid of the initial assignment to 999 too.
Truly amazing! Thanks.
More information about the Tutor