Does python's break function apply to all loops, or just the one that contains the function?

Question:

So I want to make a program in python 3. I have a loop, and noticed that I wanted to put a break function break to exit an inner loop. I don’t want to exit the outer loop however, and want to know what it does.
(I’m making hangman, the word guessing game. I also know my code currently sucks.)

while True:
  letter = input("Choose a letter! ").strip().lower()
  for i in myword: #myword is a random word generated earlier.
    if i == "letter":
      message = f"You found the letter {i}"

Can someone help explain what the break will do?
I changed it so that break doesn’t have brackets.

Asked By: Python User

||

Answers:

Only the innermost loop. So if you placed a break within the for loop, such as,

while True:
  letter = input("Choose a letter! ").strip().lower()
  for i in myword: #myword is a random word generated earlier.
    if i == "letter":
      message = f"You found the letter {i}"
      break

your while loop will still iterate.

A small program to demonstrate this could be:

y = 0
while (y < 10):
    for i in range(10):
        print(y)
        y += 1
        if (y > 5):
            break

The program still spits out values 0 through 9 and continues the while loop even though we told it to break at y > 5. It only breaks from the for loop.

Answered By: radhadman

You can use break in Python in all the loops: while, for, and nested. If you are using it in nested loops, it will terminate the innermost loop where you have used it, and the control of the program will flow to the outer loop.

here is a small example

y = 0
while (y < 10):
for n in range(10):
print(y)
y += 1
if (y > 5):
break

Answered By: Nithin Rokkam
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.