[Tutor] Suggestions for cleaner code
Jeff Shannon
jeff@ccvcorp.com
Tue Jul 8 20:53:02 2003
Kalle Svensson has given some good suggestions, and if you follow his
dictionary hints then this bit of code becomes redundant, but I figured
I'd point this out anyhow...
> if (1 <= option <= 3):
> if option == 1:
> print 'Hello'
> elif option == 2:
> print 'I should have paid more attention in math classes.'
> elif option == 3:
> print 'Why did I sleep through class?'
> else:
> print 'Farewell'
> loop = 1
>
Here you are checking to see if option is between 1 and 3, and then
checking which number it is. You could do this just as well with a
single level of if/elif, instead of two levels:
if option == 1: [...]
elif option == 2: [...]
elif option == 3: [...]
else: [...]
Also, as a minor point, one could argue that you're not being completely
truthful to your users -- you claim that 4 will quit, but really
*anything* except 1, 2, or 3 will quit. Someone who accidentally hits a
key other than 1-4 might be unhappy that the program exited rather than
giving them another chance... This can be solved by either limiting the
quit to 4 and having any other input cause a new cycle through the loop
(just change that last else into an elif), or by changing your message
to inform users (instead of '4 Farewell', say something like 'Any other
key: Farewell').
Jeff Shannon
Technician/Programmer
Credit International