[Tutor] Suggestions for while loop

Dave Angel davea at ieee.org
Mon May 11 03:13:04 CEST 2009


David <david at abbottdavid.com> wrote:

>
> 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?
>
> 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.
>
> thanks,
> -david
>
>
> #!/usr/bin/python
> import string
>
> names = []
>
> def get_names():
>      wrong_format = 0
>      count = 0
>      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: '))
>
>      while count < total_names:
>          print 'Format: LastName, First Name'
>          answers = raw_input('Enter Name: ')
>          index = answers.find(',')
>          answers = answers.title()
>          index = answers.find(',')
>          if index != -1:
>              names.append(answers)
>              count += 1
>          else:
>              wrong_format += 1
>              print '\nWrong Format!!!'
>              if wrong_format > 1:
>                  print 'That is %i Fixing Format ...' % wrong_format
>              else:
>                  print 'You have done this %i times, Fixing Format ...' 
> % wrong_format
>                  print 'Done, continue:\n'
>                  answers = answers.split()
>                  answers = string.join(answers, ', ')
>                  names.append(answers)
>                  count += 1
>
> def show_names():
>      print 'Your Names Are: \n'
>      for i in sorted(names):
>          print i
>
> def main():
>      get_names()
>      if names:
>          show_names()
>
> if __name__ == "__main__":
>      main()
>
>   
For your second question, there are several things that could be wrong 
with the user's input.  Usually it's easiest to make that a separate 
function to make it readable.  Then the function returns whenever the 
result passes its validation.

def getTotalNumber(prompt):
    while True:
        try:
            numstr = raw_input(prompt)
            n = int(numstr)
            if  0 < n < 50:            #some validation
                 return n
            print "Number is not reasonable, try again"
       except ValueError:
            print "You must enter a number!"

This way there are two forms of validation happening.  If the exception 
fires, the user gets one print statement, and if the validation fails, 
he gets the other.
The purist might complain that the return is in the middle of the 
function, so if you want to fix that, move the return n to the end, and 
change the existing one to a break..

The first question can be solved in a similar way, though the meaning of 
"the error is corrected" is unclear.  You can correct the error by 
asking the user to fix it. Or you could take a wild guess that instead of
      lastname,  firstname
the user has entered
     firstname lastname

But since many names have multiple spaces   (Dr. William Smith,  or   
Henry James, Jr.) or even other punctuation, I'd think the only safe 
thing would be to ask the user separately for the fields you want.  And 
each field may contain spaces or commas, or periods.

Anyway, since it's just an exercise, I'd probably model it the same way 
as the first function, and just ask the user again.  So the function 
would look quite similar, with the one difference that it would return 
an error count as well as the name.  Then the main function would 
accumulate the counts and print the summary at the end.

DaveA


More information about the Tutor mailing list