[Tutor] Suggestions for while loop
Richard Lovely
roadierich at googlemail.com
Mon May 11 05:33:17 CEST 2009
2009/5/11 David <david at abbottdavid.com>:
> Hi, I am going through Wesley Chun's book and this is Exercise 8-11;
> Write a program to ask the user to input a list of names, format "Last Name"
> "comma" "First Name". Write a function that manages the input so that
> when/if the user types in the names in the wrong format the error is
> corrected, and keep track of the number of errors. When done sort the list.
>
> Questions;
>
> This;
> answers = raw_input('Enter Name: ')
> index = answers.find(',')
>
> Does not seem to be a very good to me, how could I check for a comma between
> two words?
Look up string.split(), see what happens if the comma isn't in the
string you try to split. You could also try the "in" operator.
>
> And This;
> try:
> total_names = int(raw_input('Enter Total Number of Names: '))
> except ValueError:
> print 'You must enter a number!'
> total_names = int(raw_input('Enter Total Number of Names: '))
>
> Does not handle the second input for exceptions.
while True: # loop forever
try:
total_names = int(raw_input('Enter Total Number of Names: '))
except ValueError:
print 'You must enter a number!'
else:
# execution only gets to here if no exception occurred
break # exit the loop
You could do the same using a continue statement in the except:
clause, and break outside the entire structure.
total_names = -1 # set an invalid initial value
while not 0 < total_names < 50: # loop while total_names has an invalid value
try:
# If this excepts, total_names is not changed.
total_names = int(raw_input('Enter Total Number of Names: '))
# if total_names now has a valid value, the loop exits.
except ValueError:
print 'You must enter a number!' # loop continues.
--
Richard "Roadie Rich" Lovely, part of the JNP|UK Famile
www.theJNP.com
More information about the Tutor
mailing list