[Tutor] Suggestions for while loop
David
david at abbottdavid.com
Mon May 11 01:08:17 CEST 2009
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()
--
Powered by Gentoo GNU/Linux
http://linuxcrazy.com
More information about the Tutor
mailing list