Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Would it be bad practice if I used a break in my while loop for this particular problem?

Treehouse's Code :

name = input("What's your name? ")

question = input("{}, do you understand Python while loops?\n Enter yes/no: ".format(name))

while question.lower() != "yes":

    print("Ok", name, ", while loops in Python repeat as long as a certain Boolean condition is met.")

    question = input("{}, now do you understand Python while loops? Enter yes/no: ".format(name))

print("Great {}! I'm so happy you understand Python while loops.".format(name))

My version :

name = input("What's your name? ")

question = input("{}, do you understand Python while loops?\n Enter yes/no: ".format(name))

while question.lower() != "yes":

    print("Ok", name, ", while loops in Python repeat as long as a certain Boolean condition is met.")

    ask_again = input("{}, now do you understand Python while loops? Enter yes/no: ".format(name))

    break

print("Great {}! I'm so happy you understand Python while loops.".format(name))

Mod Edit: Fixed code formatting, see comment below for how to post fancy code!

When posting code, there is some markdown you can use to make it more readable. If you wrap your code in three back-ticks you'll get special formatting, and you can optionally add the language for fancy syntax highlighting.

```language

Your code here!

```

// Your code here!

If someone below has fully addressed your question, I would also encourage you to vote and mark as best answer. Happy coding!

1 Answer

Steven Parker
Steven Parker
243,095 Points

If a loop has only one exit condition, using the expression in the "while" itself to control the loop will usually make the code more compact and easy to read.

"Break" is handy when you need to respond to an alternate exit condition.

But without any conditions, the "break" in the code above would always terminate the loop, effectively counteracting the "while". So you could get the same operation by leaving off both the "while" line and the "break" entirely.

Also notice that in the original code, the "question" variable is re-used for the answer, so the loop can test it. Even without the "break", loading the input into a different variable wouldn't be very useful.

And when posting code in the forum, use Markdown formatting to preserve the code appearance (including indenting).