[Tutor] Re: Suggestions for cleaner code

Matt Richardson marichar@csusb.edu
Tue Jul 8 20:31:03 2003


I'll get there one of these days....
Can I ask why 'input' is frowned upon?  I noticed that in 'Core Python
Programming' the method is as below, namely "int(raw_input())", but in
the 'Non-programmer's' tutorial, 'input()' is used.  Just curious.

Thanks,
Matt


On Tue, 2003-07-08 at 17:19, Lee Harr wrote:
> # list of tuples (description, message)
> # make sure your "exit" choice is last in the list
> messages = [('Greeting', 'Hello.'),
>                 ('Discussion', 'I should have paid more attention in math 
> classes.'),
>                 ('Question', 'Why did I sleep through class?'),
>                 ('Extend', 'Now with simpler extensibility!'),
>                 ('Farewell', 'Farewell'),
>             ]
> 
> 
> def show_choices():
>     print 'Choose one of the following: '
> 
>     # starting with python2.3, use enumerate
>     n = 1
>     for description, message in messages:
>         print '%2s %s' % (n, description)
>         n += 1
> 
> 
> def show_message(option):
>     description, message = messages[option-1]
>     print
>     print message
>     print
> 
> 
> def get_input():
>     # raw_input is recommended over input
>     # in fact, don't use input at all
>     while 1:
>         try:
>             option = int(raw_input('Enter %s - %s : ' % (1, len(messages))))
>             if not (1 <= option <= len(messages)):
>                 continue
>             if option == len(messages):
>                 option = 0
>             return option
>         except ValueError:
>             pass
> 
> 
> def main():
>     while 1:
>         show_choices()
>         option = get_input()
>         if option:
>             show_message(option)
>         else:
>             show_message(len(messages))
>             break
> 
> 
> 
> if __name__ == '__main__':
>     main()
> 
> _________________________________________________________________
> The new MSN 8: smart spam protection and 2 months FREE*  
> http://join.msn.com/?page=features/junkmail
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
-- 
Matt Richardson
Instructional Support Technician
Department of Art
CSU San Bernardino
marichar@csusb.edu