While loop help
Larry Hudson
orgnut at yahoo.com
Wed Apr 10 02:44:47 EDT 2013
On 04/09/2013 09:49 AM, thomasancilleri at gmail.com wrote:
> So what would be the proper way to perform a loop of this program. I still can't quite figure out the best way to do it.
>
My suggestion... (pseudocode)
# Print a heading/introduction here
while True:
# Print menu, with an added selection to quit
# Get the user's choice (as an int)
if choice == 1:
# Print prompt for this choice
# Enter the value (as float, not int. Why limit your values to ints anyway?)
# Display the calculated result
elif choice == 2:
# Same procedure as above
elif ... etc
# etc
elif choice == (value for quit):
break # This breaks out of the while loop
else:
# Invalid choice, print error message
# End of loop
Further suggestion:
Since each of the choices use the same basic procedure, it could be written as a separate single
function. It would just need to be passed the appropriate prompt string(s) and conversion
factor. The results display _could_ be in this function also, but that would require passing
even more strings. It would probably be better to simply return the two values (the input value
and the converted value) back to the calling block and print the results there.
Also, don't use the round function here, that does NOT guarantee it will be _printed_ to two
decimal places. Use string formatting in the print statements. For example: (using your
original variable names, and assuming they are now both floats)
old style:
print '%.2f inches = %.2f meters' % (number, calc)
or new style:
print '{:.2f} inches = {:.2f} meters'.format(number, calc)
You also mentioned that you don't like the editor you're using. For a simple substitute you
might try Idle (which normally comes with Python). This gives you the advantage of an
interactive environment as will as an editor. There are many other choices, of course, but as a
newbie you might find this more comfortable than what you're currently using.
I hope this jump-starts your thinking. Keep at it, it's worth the effort.
-=- Larry -=-
More information about the Python-list
mailing list