[Tutor] Output never stops

bob gailer bgailer at gmail.com
Mon Aug 4 19:34:14 CEST 2008


David wrote:

[snip]
> #!/usr/bin/python
>
> person = {'Lary':43,'Joan':24}
>
> choice = 0
> while choice != '-1':
>    if choice == '':
>        print "You must enter Lary or Joan to continue! (-1 to quit): "
>    choice = raw_input(
>            "Who's age do want to know, Lary or Joan? (-1 to quit): ")
>    if choice == 'Lary':
>        print "Lary's age is:", person.get('Lary')
>
>    elif choice == 'Joan':
>        print "Joan's age is:", person.get('Joan')
>
>    else:
>        print "Goodbye!"
>
>
Consider leveraging the dictionary (and some other"Pythonic" 
refinements). Separate the logic from the data. Now you can add more 
names and ages without changing the logic.

#!/usr/bin/python

person = {'Lary':43, 'Joan':24, 'Bob':68}
keys = person.keys()
names = ', '.join(keys[:-1]) + ' or ' + keys[-1]
while True:
   choice = raw_input("Who's age do want to know, %s? (-1 to quit): " % 
names)
   age = person.get(choice, None)
   if age is not None:
      print choice + "'s age is:", age
   elif choice == "-1":
      print "Goodbye!"
      break
   else:
      print "Invalid choice "  + choice
 
          


-- 
Bob Gailer
919-636-4239 Chapel Hill, NC



More information about the Tutor mailing list