Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #43167 > unrolled thread
| Started by | thomasancilleri@gmail.com |
|---|---|
| First post | 2013-04-09 06:32 -0700 |
| Last post | 2013-04-09 12:19 -0700 |
| Articles | 10 on this page of 30 — 8 participants |
Back to article view | Back to comp.lang.python
While loop help thomasancilleri@gmail.com - 2013-04-09 06:32 -0700
Re: While loop help thomasancilleri@gmail.com - 2013-04-09 06:57 -0700
Re: While loop help Dave Angel <davea@davea.name> - 2013-04-09 13:12 -0400
Re: While loop help thomasancilleri@gmail.com - 2013-04-09 10:18 -0700
Re: While loop help Chris Angelico <rosuav@gmail.com> - 2013-04-10 03:23 +1000
Re: While loop help Dave Angel <davea@davea.name> - 2013-04-09 13:30 -0400
Re: While loop help thomasancilleri@gmail.com - 2013-04-09 06:58 -0700
Re: While loop help Chris Angelico <rosuav@gmail.com> - 2013-04-10 00:05 +1000
Re: While loop help thomasancilleri@gmail.com - 2013-04-09 08:47 -0700
Re: While loop help Joel Goldstick <joel.goldstick@gmail.com> - 2013-04-09 12:02 -0400
Re: While loop help Chris Angelico <rosuav@gmail.com> - 2013-04-10 02:10 +1000
Re: While loop help thomasancilleri@gmail.com - 2013-04-09 09:24 -0700
Re: While loop help Joel Goldstick <joel.goldstick@gmail.com> - 2013-04-09 12:36 -0400
Re: While loop help Chris Angelico <rosuav@gmail.com> - 2013-04-10 02:47 +1000
Re: While loop help thomasancilleri@gmail.com - 2013-04-09 09:57 -0700
Re: While loop help Chris Angelico <rosuav@gmail.com> - 2013-04-10 03:08 +1000
Re: While loop help Dave Angel <davea@davea.name> - 2013-04-09 13:27 -0400
Re: While loop help thomasancilleri@gmail.com - 2013-04-09 09:57 -0700
Re: While loop help thomasancilleri@gmail.com - 2013-04-09 09:24 -0700
Re: While loop help Walter Hurry <walterhurry@lavabit.com> - 2013-04-09 19:35 +0000
Re: While loop help Dave Angel <davea@davea.name> - 2013-04-09 16:12 -0400
Re: While loop help Walter Hurry <walterhurry@lavabit.com> - 2013-04-09 20:59 +0000
Re: While loop help Chris Angelico <rosuav@gmail.com> - 2013-04-10 08:36 +1000
Re: While loop help rusi <rustompmody@gmail.com> - 2013-04-10 08:59 -0700
Re: While loop help thomasancilleri@gmail.com - 2013-04-09 08:47 -0700
Re: While loop help Chris Angelico <rosuav@gmail.com> - 2013-04-10 00:00 +1000
Re: While loop help thomasancilleri@gmail.com - 2013-04-09 09:49 -0700
Re: While loop help Larry Hudson <orgnut@yahoo.com> - 2013-04-09 23:44 -0700
Re: While loop help Larry Hudson <orgnut@yahoo.com> - 2013-04-10 20:00 -0700
Re: While loop help jmfauth <wxjmfauth@gmail.com> - 2013-04-09 12:19 -0700
Page 2 of 2 — ← Prev page 1 [2]
| From | Dave Angel <davea@davea.name> |
|---|---|
| Date | 2013-04-09 16:12 -0400 |
| Message-ID | <mailman.385.1365538374.3114.python-list@python.org> |
| In reply to | #43219 |
On 04/09/2013 03:35 PM, Walter Hurry wrote: > On Wed, 10 Apr 2013 02:10:29 +1000, Chris Angelico wrote: > >> On Wed, Apr 10, 2013 at 1:47 AM, <thomasancilleri@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 works (of course), but in every Python version I've seen, one merely > needs to invoke the python interactive interpreter and the banner is > displayed: > > $ python > Python 2.7.3 (default, Aug 9 2012, 17:23:57) > [GCC 4.7.1 20120720 (Red Hat 4.7.1-5)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> quit() > $ > And if several are installed, that isn't necessarily the one that'll run when one runs a script. Depends on how the script is invoked (and on what OS is running), and on the shebang line, PATH, etc. The real point about those two lines is that they can be added to most scripts. -- DaveA
[toc] | [prev] | [next] | [standalone]
| From | Walter Hurry <walterhurry@lavabit.com> |
|---|---|
| Date | 2013-04-09 20:59 +0000 |
| Message-ID | <kk1vga$a0c$1@news.albasani.net> |
| In reply to | #43225 |
On Tue, 09 Apr 2013 16:12:34 -0400, Dave Angel wrote: > On 04/09/2013 03:35 PM, Walter Hurry wrote: >> On Wed, 10 Apr 2013 02:10:29 +1000, Chris Angelico wrote: >> >>> On Wed, Apr 10, 2013 at 1:47 AM, <thomasancilleri@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 works (of course), but in every Python version I've seen, one >> merely needs to invoke the python interactive interpreter and the >> banner is displayed: >> >> $ python Python 2.7.3 (default, Aug 9 2012, 17:23:57) >> [GCC 4.7.1 20120720 (Red Hat 4.7.1-5)] on linux2 Type "help", >> "copyright", "credits" or "license" for more information. >>>>> quit() >> $ >> >> > And if several are installed, that isn't necessarily the one that'll run > when one runs a script. Depends on how the script is invoked (and on > what OS is running), and on the shebang line, PATH, etc. > > The real point about those two lines is that they can be added to most > scripts. Well yes, but if multiple versions are installed and the script has a shebang, then invoking the same interpreter as the shebang does will produce the same result. But this is dancing on the head of a pin anyway; OP just didn't know what version of Python he was running, so he is extremely unlikely to have more than one version installed, and to be choosing amongst them.
[toc] | [prev] | [next] | [standalone]
| From | Chris Angelico <rosuav@gmail.com> |
|---|---|
| Date | 2013-04-10 08:36 +1000 |
| Message-ID | <mailman.390.1365546964.3114.python-list@python.org> |
| In reply to | #43228 |
On Wed, Apr 10, 2013 at 6:59 AM, Walter Hurry <walterhurry@lavabit.com> wrote: > On Tue, 09 Apr 2013 16:12:34 -0400, Dave Angel wrote: > >> On 04/09/2013 03:35 PM, Walter Hurry wrote: >>> On Wed, 10 Apr 2013 02:10:29 +1000, Chris Angelico wrote: >>> >>>> On Wed, Apr 10, 2013 at 1:47 AM, <thomasancilleri@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 works (of course), but in every Python version I've seen, one >>> merely needs to invoke the python interactive interpreter and the >>> banner is displayed: >>> >>> $ python Python 2.7.3 (default, Aug 9 2012, 17:23:57) >>> [GCC 4.7.1 20120720 (Red Hat 4.7.1-5)] on linux2 Type "help", >>> "copyright", "credits" or "license" for more information. >>>>>> quit() >>> $ >>> >>> >> And if several are installed, that isn't necessarily the one that'll run >> when one runs a script. Depends on how the script is invoked (and on >> what OS is running), and on the shebang line, PATH, etc. >> >> The real point about those two lines is that they can be added to most >> scripts. > > Well yes, but if multiple versions are installed and the script has a > shebang, then invoking the same interpreter as the shebang does will > produce the same result. I still went with a guaranteed-safe option. Adding those two lines to his script is sure to report on the Python being used to run the script, and it's not as if it's a massively-complex incantation :) > But this is dancing on the head of a pin anyway; OP just didn't know what > version of Python he was running, so he is extremely unlikely to have > more than one version installed, and to be choosing amongst them. Dunno about that. It's pretty easy to have two versions of something without understanding why. ChrisA
[toc] | [prev] | [next] | [standalone]
| From | rusi <rustompmody@gmail.com> |
|---|---|
| Date | 2013-04-10 08:59 -0700 |
| Message-ID | <af9b4c1b-09a7-4dc9-8476-c23632904e56@tz3g2000pbb.googlegroups.com> |
| In reply to | #43187 |
On Apr 9, 8:47 pm, thomasancill...@gmail.com wrote: > ... 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! Not perhaps a direct answer... Anyways there is style in which python is best used which people coming from more traditional languages are usually not familiar with: its called 'playing around in the interpreter' Here is a small session based on your code that shows this interaction with the interpreter: --------------------- $ python Python 2.7.3 (default, Jan 2 2013, 16:53:07) [GCC 4.7.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> def inch2meter(i): return round(i*.254,2) ... >>> inch2meter(1) 0.25 >>> def milliliter2pint(m): return round(number * 0.0021134,2) ... >>> milliliter2pint(100) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 1, in milliliter2pint NameError: global name 'number' is not defined >>> def milliliter2pint(m): return round(m * 0.0021134,2) ... >>> milliliter2pint(100) 0.21 >>> --------------------- Notice some things here: 1. I check out the code as soon as its written. So when I cutpasted from your code, without keeping names (m <-> number) consistent, I get an error, correct it and continue 2. There is not a single print statement. Not just the functions have no prints, even the code that calls them has none. Just call get answer. This point needs to be underscored: In C or java you cannot write any useful code without doing IO ie printf/scanf etc. In python you can and you should try to.
[toc] | [prev] | [next] | [standalone]
| From | thomasancilleri@gmail.com |
|---|---|
| Date | 2013-04-09 08:47 -0700 |
| Message-ID | <mailman.364.1365524732.3114.python-list@python.org> |
| In reply to | #43173 |
Sorry I'm just starting to learn python and I'm not sure what version I'm using to be quite honest. I just started typing it up in Komodo edit (Which I'm not personally a fan in particular) I fixed the missing parenthesis which fixed the invalid syntax problem. Also, I apologize for submitting code that did not run. This is the code I have now before I tried looping it again:
#!/usr/bin/env python
#Program starts here
print "To start the Unit Converter please type the number next to the conversion you would like to perform"
choice = raw_input("\n1:Inches to Meter\n2:Millileters to Pint\n3:Acres to Square-Miles\n")
#If user enters 1:Program converts inches to meters
if choice == 1:
#operation = "Inches to Meters"
number = int(raw_input("\n\nType the amount in Inches you would like to convert to Meters.\n"))
calc = round(number * .0254, 2)
print "\n",number,"Inches =",calc,"Meters"
restart = raw_input("If you would like to perform another conversion type: true\n")
#If user enters 2:Program converts millimeters to pints
elif choice == 2:
#operation = "Milliliters to Pints"
number = int(raw_input("\n\nType the amount in Milliliters you would like to convert to Pints.\n"))
calc = round(number * 0.0021134,2)
print "\n",number,"Milliliters =",calc,"Pints"
restart = raw_input("If you would like to perform another conversion type: true\n")
#If user enter 3:Program converts kilometers to miles
elif choice == 3:
#operation = "Kilometers to Miles"
number = int(raw_input("\n\nType the amount in Kilometers you would like to convert to Miles.\n"))
calc = round(number * 0.62137,2)
print "\n",number,"Kilometers =",calc,"Miles"
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"
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!
[toc] | [prev] | [next] | [standalone]
| From | Chris Angelico <rosuav@gmail.com> |
|---|---|
| Date | 2013-04-10 00:00 +1000 |
| Message-ID | <mailman.346.1365516017.3114.python-list@python.org> |
| In reply to | #43167 |
On Tue, Apr 9, 2013 at 11:32 PM, <thomasancilleri@gmail.com> wrote:
> I'm new to learning python and creating a basic program to convert units of measurement which I will eventually expand upon but im trying to figure out how to loop the entire program. When I insert a while loop it only loops the first 2 lines. Can someone provide a detailed beginner friendly explanation. Here is my program.
Hi there!
I'm going to make a few general comments about your code; this won't
necessarily tell you why it's looping the "first two lines" (not sure
quite what you mean there), but may be of use anyway.
Firstly, your code actually doesn't run as-is. It doesn't loop *at
all*. Please paste actual runnable code; it makes our job a lot
easier! You have a copy-paste problem with one of your input lines (a
missing close parenthesis). Once I fixed that, the program appears to
loop quite correctly.
> #!/usr/bin/env python
> restart = "true"
> while restart == "true":
> #Program starts here
Putting your comments flush-left as though they were preprocessor
directives to an old C compiler is unnecessary; indenting them to the
same level as the surrounding code usually makes your code easier to
read.
> print "To start the Unit Converter please type the number next to the conversion you would like to perform"
> choice = input("\n1:Inches to Meter\n2:Millileters to Pint\n3:Acres to Square-Miles\n")
This is BAD. VERY BAD. As evidenced by the print line, you are using
Python 2 (btw, please specify; I tested your code in 2.7, but maybe
your version is a bit different); the input() function in Python 2
will eval whatever the user types in.
> #If user enters 1:Program converts inches to meters
> if choice == 1:
> number = int(raw_input("\n\nType the amount in Inches you would like to convert to Meters.\n"))
This is a MUCH safer way to accept input. Use raw_input() and then
convert it in whatever way is appropriate.
> operation = "Inches to Meters"
> calc = round(number * .0254, 2)
> print "\n",number,"Inches =",calc,"Meters"
> restart = raw_input("If you would like to perform another conversion type: true\n"
>
> #If user enters 2:Program converts millimeters to pints
> elif choice == 2:
> number = int(raw_input("\n\nType the amount in Milliliters you would like to convert to Pints.\n"))
Quite a few of your lines are getting long. That's not a particularly
big problem normally (it's a style issue, not a code correctness one),
but when you're posting in an email, it's usually safer to shorten the
lines to 70-80 characters max; but make sure your code still runs
correctly.
> operation = "Milliliters to Pints"
> calc = round(number * 0.0021134,2)
> print "\n",number,"Milliliters =",calc,"Pints"
> restart = raw_input("If you would like to perform another conversion type: true\n")
>
> #If user enter 3:Program converts kilometers to miles
> elif choice == 3:
> number = int(raw_input("\n\nType the amount in Kilometers you would like to convert to Miles.\n"))
> operation = "Kilometers to Miles"
> calc = round(number * 0.62137,2)
> print "\n",number,"Kilometers =",calc,"Miles"
> restart = raw_input("If you would like to perform another conversion type: true\n")
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.
But, as I said, your code seems to work for me (modulo the missing
parenthesis). Can you give more details about what's not working,
please?
ChrisA
[toc] | [prev] | [next] | [standalone]
| From | thomasancilleri@gmail.com |
|---|---|
| Date | 2013-04-09 09:49 -0700 |
| Message-ID | <05d504a8-ec5b-4cff-b580-213071cf4e28@googlegroups.com> |
| In reply to | #43167 |
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.
[toc] | [prev] | [next] | [standalone]
| From | Larry Hudson <orgnut@yahoo.com> |
|---|---|
| Date | 2013-04-09 23:44 -0700 |
| Message-ID | <G5-dnTPyiu_9l_jMnZ2dnUVZ_qudnZ2d@giganews.com> |
| In reply to | #43200 |
On 04/09/2013 09:49 AM, thomasancilleri@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 -=-
[toc] | [prev] | [next] | [standalone]
| From | Larry Hudson <orgnut@yahoo.com> |
|---|---|
| Date | 2013-04-10 20:00 -0700 |
| Message-ID | <nqOdnTMDMe7QuvvMnZ2dnUVZ_i2dnZ2d@giganews.com> |
| In reply to | #43250 |
On 04/09/2013 11:44 PM, Larry Hudson wrote:
> On 04/09/2013 09:49 AM, thomasancilleri@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 -=-
>
On a little further thought, I realized the "single function" I suggested is even easier than I
originally thought -- even with the results printed in the function. Here's an example:
def convert(frm, to, factor):
# frm and to are strings, factor is a float
print 'Converting {} to {}:'.format(frm, to)
value = float(raw_input('How many {}? '.format(frm)))
print '{:.2f} {} is {:.2f} {}'.format(value, frm, value * factor, to)
You would use it like:
convert('inches', 'meters', 0.0254)
or
convert('meters', 'inches', 39.37)
-=- Larry -=-
[toc] | [prev] | [next] | [standalone]
| From | jmfauth <wxjmfauth@gmail.com> |
|---|---|
| Date | 2013-04-09 12:19 -0700 |
| Message-ID | <808381fc-d0e9-4582-ad9d-ef6c310e6112@c15g2000vbl.googlegroups.com> |
| In reply to | #43167 |
On 9 avr, 15:32, thomasancill...@gmail.com wrote:
> I'm new to learning python and creating a basic program to convert units of measurement which I will eventually expand upon but im trying to figure out how to loop the entire program. When I insert a while loop it only loops the first 2 lines. Can someone provide a detailed beginner friendly explanation. Here is my program.
>
> #!/usr/bin/env python
> restart = "true"
> while restart == "true":
> #Program starts here
> print "To start the Unit Converter please type the number next to the conversion you would like to perform"
> choice = input("\n1:Inches to Meter\n2:Millileters to Pint\n3:Acres to Square-Miles\n")
>
> #If user enters 1:Program converts inches to meters
> if choice == 1:
> number = int(raw_input("\n\nType the amount in Inches you would like to convert to Meters.\n"))
> operation = "Inches to Meters"
> calc = round(number * .0254, 2)
> print "\n",number,"Inches =",calc,"Meters"
> restart = raw_input("If you would like to perform another conversion type: true\n"
>
> #If user enters 2:Program converts millimeters to pints
> elif choice == 2:
> number = int(raw_input("\n\nType the amount in Milliliters you would like to convert to Pints.\n"))
> operation = "Milliliters to Pints"
> calc = round(number * 0.0021134,2)
> print "\n",number,"Milliliters =",calc,"Pints"
> restart = raw_input("If you would like to perform another conversion type: true\n")
>
> #If user enter 3:Program converts kilometers to miles
> elif choice == 3:
> number = int(raw_input("\n\nType the amount in Kilometers you would like to convert to Miles.\n"))
> operation = "Kilometers to Miles"
> calc = round(number * 0.62137,2)
> print "\n",number,"Kilometers =",calc,"Miles"
> restart = raw_input("If you would like to perform another conversion type: true\n")
-----
More (very) important:
meter: lower case "m"
kilometre: lower case "k"
milli: lower case "m"
http://www.bipm.org/en/home/
Less important:
Start with something simple and increase the complexity eg:
>>> # Py 3.2
>>> while True:
... s = input('km: ')
... if s == 'q':
... break
... a = float(s)
... print('{} [kilometre] == {} [metre]'.format(a, a * 1000))
...
km: 1
1.0 [kilometre] == 1000.0 [metre]
km: 1.3456
1.3456 [kilometre] == 1345.6 [metre]
km: q
jmf
[toc] | [prev] | [standalone]
Page 2 of 2 — ← Prev page 1 [2]
Back to top | Article view | comp.lang.python
csiph-web