While loop help

  • Thread starter thomasancilleri
  • Start date

T

thomasancilleri

I'm new to learning python and creating a basic program to convert units ofmeasurement 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")
 
Ad

Advertisements

T

thomasancilleri

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. Also suddenly I'm getting an invalid syntax error next to my elif statements when I wasn't a minute ago. What is wrong here?



#!/usr/bin/env python

restart = "true"

while restart == "true":

#Program starts here

print "To start the Unit Converter please type the number next to theconversion you would like to perform"

choice = input("\n1:Inches to Meter\n2:Millileters to Pint\n3:Acresto 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 wouldlike 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")
 
T

thomasancilleri

Also I'm getting a invalid syntax next to my elif statements that i wasnt getting before. why is this happening now?
 
C

Chris Angelico

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 theconversion you would like to perform"
choice = input("\n1:Inches to Meter\n2:Millileters to Pint\n3:Acresto 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 wouldlike 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
 
C

Chris Angelico

Also I'm getting a invalid syntax next to my elif statements that i wasnt getting before. why is this happening now?

Ah! That's relating to the close parenthesis problem I mentioned.
That's the exact issue I saw.

When you get told about a problem, sometimes the location pointed out
isn't the actual cause. What you have is a (near) guarantee that the
problem is no later in the file than that point; often it'll be on
that line or the one previous line. In this case, the code is
"raw_input(........ elif", which can't be properly parsed - the open
parenthesis is forcing the code to be interpreted as an expression,
and elif isn't an expression.

If you're stuck figuring out a problem, one neat trick is to delete
the line of code that's blamed for the problem and try again. If the
problem disappears, it was on that line; if the problem moves down to
the next line, it's probably on the preceding line. This trick doesn't
always work, but it can occasionally be quite handy.

ChrisA
 
T

thomasancilleri

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 codingthat will prevent me from learning python in a sloppy way. I'd like to learn it correctly the first time!
 
Ad

Advertisements

T

thomasancilleri

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 codingthat will prevent me from learning python in a sloppy way. I'd like to learn it correctly the first time!
 
J

Joel Goldstick

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 is not converted to an integer. raw_input returns a string.

choice = raw_input("\n1:Inches to Meter\n2:Millileters to Pint\n3:Acres to
Square-Miles\n")

This will convert choice to an int. Actually, it might not if what you
type is not a number. Then it will cause and exception.
But for now, do this:
choice = int(choice)

or leave choices as a string and make your if statements like if choice ==
'1'
 
C

Chris Angelico

... 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("(e-mail address removed)",smart_question())
run_code()

So far, looks like you're following it just fine. :)

ChrisA
 
T

thomasancilleri

For system version I get this:
2.7.2 (default, Oct 11 2012, 20:14:37)
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)]

Also, I understand what your saying about the continuation code. There's noneed for me to include it in each if/else statement, I could just use it at the end of the program outside of the statements and it would run no matter what. But, what I don't understand exactly is the while statement. I've been looking around a lot lately and notice that people say to use for instance:

while restart: or while true: or while restart = true:

What makes a statement true? Is there a way to return a true or false message. My method was to ask the user to type "true" and if that print statement matched restart = "true" then the loop would continue but i imagine there is a better way then matching strings and integers like i have been.

Also what confuses me is that python doesn't use brackets. How do I containall of my if/else statements into one while loop? Do I have to indent eachline of code and extra indentation? I'm used to highschool doing c++ and java when I would just say:

while (x<3)
{
if ()
else ()
}
 
T

thomasancilleri

For system version I get this:
2.7.2 (default, Oct 11 2012, 20:14:37)
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)]

Also, I understand what your saying about the continuation code. There's noneed for me to include it in each if/else statement, I could just use it at the end of the program outside of the statements and it would run no matter what. But, what I don't understand exactly is the while statement. I've been looking around a lot lately and notice that people say to use for instance:

while restart: or while true: or while restart = true:

What makes a statement true? Is there a way to return a true or false message. My method was to ask the user to type "true" and if that print statement matched restart = "true" then the loop would continue but i imagine there is a better way then matching strings and integers like i have been.

Also what confuses me is that python doesn't use brackets. How do I containall of my if/else statements into one while loop? Do I have to indent eachline of code and extra indentation? I'm used to highschool doing c++ and java when I would just say:

while (x<3)
{
if ()
else ()
}
 
Ad

Advertisements

J

Joel Goldstick

For system version I get this:
2.7.2 (default, Oct 11 2012, 20:14:37)
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)]

Also, I understand what your saying about the continuation code. There's
no need for me to include it in each if/else statement, I could just use it
at the end of the program outside of the statements and it would run no
matter what. But, what I don't understand exactly is the while statement.
I've been looking around a lot lately and notice that people say to use for
instance:

while restart: or while true: or while restart = true:

What makes a statement true? Is there a way to return a true or false
message. My method was to ask the user to type "true" and if that print
statement matched restart = "true" then the loop would continue but i
imagine there is a better way then matching strings and integers like i
have been.

Also what confuses me is that python doesn't use brackets. How do I
contain all of my if/else statements into one while loop? Do I have to
indent each line of code and extra indentation? I'm used to highschool
doing c++ and java when I would just say:

Python uses indentation. Most people set their editor to indent 4 spaces
for each level. It seems odd to people coming from braces languages, but
you get used to it, and it makes code very readable.

As to True/False. There is a boolean type and its values are True and
False (note the capital letter). But other values can be considered
True/False. For instance 0 is considered false, and empty string is
considered false. Any other number is considered true as is any string
that isn't empty. Empty sequences are considered false (Tuples, lists)
 
C

Chris Angelico

For system version I get this:
2.7.2 (default, Oct 11 2012, 20:14:37)
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)]

Lovely! Perfect.
But, what I don't understand exactly is the while statement. I've been looking around a lot lately and notice that people say to use for instance:

while restart: or while true: or while restart = true:

while x:
y

will check whether x "feels trueish", and if it does, will execute y,
then go back and check x again. The general principle is that
something is true and nothing is false - for instance, 0 and 0.0 are
false, while 42 and 0.143 are true. Same goes for lists and such; an
empty list is false, a list with something in it is true.

When you make an actual comparison, you'll get back a result that,
normally, will be one of the strict bool objects True and False. For
instance, the expression:

restart == "true"

will be True if restart has the string "true", and False if it has any
other string.
What makes a statement true? Is there a way to return a true or false message. My method was to ask the user to type "true" and if that print statement matched restart = "true" then the loop would continue but i imagine there is a better way then matching strings and integers like i have been.

You can print anything, even the boolean values! :) Try it!

Your method works fine. Since you're getting something with
raw_input(), you're working with strings; whatever the user enters,
that's what you work with. You could make it more friendly by checking
just the first letter and case insensitively, and making it "Continue?
Y/N", but that's optional.
Also what confuses me is that python doesn't use brackets. How do I contain all of my if/else statements into one while loop? Do I have to indent each line of code and extra indentation? I'm used to highschool doing c++ andjava when I would just say:

while (x<3)
{
if ()
else ()
}

It's conventional in C++ to indent every block of code.

int main()
{
//Indent one level
initialize()
while (...)
{
//Indent two levels
do_stuff()
if (...)
{
//Indent three levels
do_more_stuff()
}
do_less_stuff()
}
close_all()
}

Now, just delete all those lines with nothing but braces. You can
still see the program's logical structure:

int main()
//Indent one level
initialize()
while (...)
//Indent two levels
do_stuff()
if (...)
//Indent three levels
do_more_stuff()
do_less_stuff()
close_all()

This is how Python works. (And it's almost legal Python syntax, too.
Add a few colons, fix the comments, pretty much done.) For better or
for worse, Python depends on the indentation; but 99%+ of the time,
you would have that indentation even if it didn't matter. (Personally,
I prefer explicit braces. The duplicated information at times helps
catch bugs, and sometimes I format code according to a logical
structure that doesn't necessarily match its physical structure. It's
a freedom I don't often make use of, but it's one that Python denies
me... as I said, for better or for worse. There are those who argue
that that's a freedom I shouldn't have.)

ChrisA
 
T

thomasancilleri

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.
 
T

thomasancilleri

I responded before I saw this message, this was very helpful so I appreciate your quick and helpful responses. So do you think prompting for a string and then checking if the string is true is a good practice for something like this? When would checking for true/false be necessary?
 
T

thomasancilleri

I responded before I saw this message, this was very helpful so I appreciate your quick and helpful responses. So do you think prompting for a string and then checking if the string is true is a good practice for something like this? When would checking for true/false be necessary?
 
Ad

Advertisements

T

thomasancilleri

sorry i just started using google groups, not really all that sure how to use it properly.
 
C

Chris Angelico

sorry i just started using google groups, not really all that sure how to use it properly.

The best way to use Google Groups is to not use it, frankly. Just
subscribe to the mailing list in gmail; it has its own issues (eg it
encourages top-posting by putting a couple of blank lines at the top
of the quoted text), but they're easier to work around than the GG
problems.

ChrisA
 
Ad

Advertisements

D

Dave Angel

I responded before I saw this message, this was very helpful so I appreciate your quick and helpful responses. So do you think prompting for a string and then checking if the string is true is a good practice for something like this? When would checking for true/false be necessary?

No, DON'T check for the string to be true, check if it matches the
requirements. Word the question for the user's convenience, not the
programming language's. Don't ask for true and false, ask "Continue?"
and accept "Y" or "N". Or ask "Q for quit". Or whatever. Make your
comparison case-insensitive, and permit one-character responses.

continue = "y"
while continue[:1].lower() == "y":
do some work
continue = raw_input("Do you want to continue (y/n)?"
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top