While loop help
Chris Angelico
rosuav at gmail.com
Tue Apr 9 12:10:29 EDT 2013
On Wed, Apr 10, 2013 at 1:47 AM, <thomasancilleri at gmail.com> wrote:
> ... I'm not sure what version I'm using ...
Try putting these lines into a Python script:
import sys
print(sys.version)
That, on any version of Python (back a fairly long way, Steven
D'Aprano can probably say how far), will give you a line or so of
output that summarizes your version. For instance, I can get the
following:
3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 10:55:48) [MSC v.1600 32 bit (Intel)]
2.7.4 (default, Apr 6 2013, 19:54:46) [MSC v.1500 32 bit (Intel)]
3.1.1+ (r311:74480, Nov 2 2009, 14:49:22)
[GCC 4.4.1]
3.4.0a0 (default:5dcd7ee0716a, Mar 30 2013, 08:17:06)
[GCC 4.7.2]
It's a handy system summary.
> choice = raw_input("\n1:Inches to Meter\n2:Millileters to Pint\n3:Acres to Square-Miles\n")
> if choice == 1:
You probably want to use int(raw_input(...)) here; currently, you're
going to get back a string eg "1", which is not equal to the integer
1. But at least now you don't have the automatic evaluation happening
:)
> restart = raw_input("If you would like to perform another conversion type: true\n")
>
> Not sure what you meant to exactly by this:
> "There's a lot of duplicated code here, most notably your continuation
> condition. You can simply back-tab after the elif block and have some
> code that reunites all the branches; this would also make things
> clearer"
Notice how you have the "restart = " line (which I quote above)
duplicated into each of your code branches? That's what I'm talking
about. Here's a pseudocode version of the looping you have:
while restart:
choice = get_choice()
if choice == 1:
do_choice_1()
restart = get_restart()
elif choice == 2:
do_choice_2()
restart = get_restart()
elif choice == 3:
do_choice_3()
restart = get_restart()
Here's how you could deduplicate that:
while restart:
choice = get_choice()
if choice == 1:
do_choice_1()
elif choice == 2:
do_choice_2()
elif choice == 3:
do_choice_3()
restart = get_restart()
The restart line is unindented one level, which brings it out of the
if/elif block, and then it'll get executed regardless of 'choice'. (To
strictly match your original code, you'd need to finish the elif block
with "else: continue", but the code makes at least as good sense
without it, so I'd consider that optional.)
> Thanks for your reply and if you have any ideas for me to improve my coding that will prevent me from learning python in a sloppy way. I'd like to learn it correctly the first time!
You're doing fine. The general pattern of programming is:
while True:
write_code()
try:
figure_out_what_is_wrong_with_code()
except LackOfSkillException:
mail("python-list at python.org",smart_question())
run_code()
So far, looks like you're following it just fine. :)
ChrisA
More information about the Python-list
mailing list