Syntax error break outside loop python

Что это значит: в отличие от многих других языков, команда break в Python используется только для выхода из цикла, а не выхода из программы.

Что означает ошибка SyntaxError: 'break' outside loop

Что означает ошибка SyntaxError: ‘break’ outside loop

Это значит, что мы пытаемся выйти из цикла, которого нет

Это значит, что мы пытаемся выйти из цикла, которого нет

Ситуация: мы пишем опросник на Python, и нам важно, чтобы его мог пройти только совершеннолетний. Для этого мы добавляем в код такую логику: 

  1. Спрашиваем про возраст.
  2. Смотрим, он больше 18 или нет.
  3. Если нет — останавливаем программу.
  4. Пишем дальше код, который будет работать, если участнику есть 18 лет и программа не остановилась.

На Python это выглядит так:

# запрашиваем возраст
age_txt = input('Введите свой возраст: ')
# переводим введённое значение в число
age = int(age_txt)
# если меньше 18 лет
if age < 18:
        # выводим сообщение
        print('Вы не можете участвовать в опросе')
        # выходим из программы
        break
    
# спрашиваем имя
name_txt = input('Как вас зовут: ')

Вроде всё логично, но после запуска мы получаем ошибку:

❌ SyntaxError: ‘break’ outside loop

Что это значит: в отличие от многих других языков, команда break в Python используется только для выхода из цикла, а не выхода из программы в целом.

Когда встречается: когда мы хотим выйти из программы в середине её работы, но не знаем как.

Что делать с ошибкой SyntaxError: ‘break’ outside loop

Всё зависит от того, что вы хотите сделать.

Если вы хотите выйти из цикла, то break служит как раз для этого — нужно только убедиться, что всё в порядке с отступами. Например, здесь мы выйдем из цикла, как только переменная станет больше 9:

for i in range(10):
    print(i)
    if i > 8:
break

А если вы хотите закончить работу программы в произвольном месте, то нужно вместо break использовать команду exit(). Она штатно завершит все процессы в коде и остановит программу. Это как раз подойдёт для нашего примера с опросником — теперь программа остановится, если возраст будет меньше 18:

# запрашиваем возраст
age_txt = input('Введите свой возраст: ')
# переводим введённое значение в число
age = int(age_txt)
# если меньше 18 лет
if age < 18:
        # выводим сообщение
        print('Вы не можете участвовать в опросе')
        # выходим из программы
        exit()
    
# спрашиваем имя
name_txt = input('Как вас зовут: ')

Вёрстка:

Кирилл Климентьев

Получите ИТ-профессию

В «Яндекс Практикуме» можно стать разработчиком, тестировщиком, аналитиком и менеджером цифровых продуктов. Первая часть обучения всегда бесплатная, чтобы попробовать и найти то, что вам по душе. Дальше — программы трудоустройства.

Начать карьеру в ИТ

Получите ИТ-профессию
Получите ИТ-профессию
Получите ИТ-профессию
Получите ИТ-профессию

Hello coders!! In this article, we will be learning about the “break outside loop” loop error in Python. We will see its cause with some examples and will ultimately learn how to resolve this error. Let us now understand it in detail.

What does ‘break’ mean in Python?

The ‘break’ statement is used to instruct Python to exit from a loop. It is commonly used to exit a loop abruptly when some external condition is triggered. The break statement can be used in any type of loop – while loop and for loop.

n = 10                 
while n > 0:              
   print ('Value :', n)
   n = n -1
   if n == 5:
      break
print ('Exiting the loop')

output:

What does 'break' mean in Python?

As we can see, when the value of the variable becomes 5, the condition for the break statement triggers and Python exits the loop abruptly.

SyntaxError: break outside loop in Python:

The purpose of a break statement is to terminate a loop abruptly by triggering a condition. So, the break statement can only be used inside a loop. It can also be used inside an if statement, but only if it is inside a loop. If one uses a break statement outside of a loop, then they will get the “SyntaxError: ‘break’ outside loop” error in their code.

n = 10
if n < 15:
	print('The number is less than 15')
else:
	break

output:

break outside loop python output

We can see that the error SyntaxError: break outside loop occurs. This is because we have used the break statement without any parent loop.

Resolution for SyntaxError: break outside loop in Python:

The cause of the above error is that the break statement can’t be used anywhere in a program. It is used only to stop a loop from executing further.

We need to remove the break statements in order to solve the error. An exception can replace it. We use exceptions to stop a program and provide an error message.

n = 20
if n < 15:
	print('The number is less than 15')
else:
	raise Exception("The number is not less than 15")

Output:

Error in break outside loop python

The code now returns an exception based on the given condition. When we use an exception, it stops the program from further execution( if triggered) and displays the error message.

If we want the program to continue further execution, we cam simply use a print statement.

n = 20
if n < 15:
	print('The number is less than 15')
else:
	print("The number is not less than 15")

Output:

Solved Error break outside loop python

Here, due to the use of print statement, the program does not stop from execution.

Difference between break, exit and return:

BREAK EXIT RETURN
Keyword System Call Instruction
exit from a loop exit from a program and return the control back to OS return a value from a function

Conclusion: Break Outside Loop Python

In this article, we discussed in detail the Python “break out of loop error.” We learned about using the break statement and saw the scene in which the said error can occur. So, to avoid it, we must remember to use the break statement within the loop only.

However, if you have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.

Happy Pythoning!

blog banner for post titled: How to Solve Python SyntaxError: ‘break’ outside loop

The break statement terminates the current loop and resumes execution at the next statement. You can only use a break statement inside a loop or an if statement. If you use a break statement outside of a loop, then you will raise the error “SyntaxError: ‘break’ outside loop”.

Table of contents

  • SyntaxError: ‘break’ outside loop
    • What is SyntaxError?
    • What is a Break Statement?
  • Example: If Statement
    • Solution
  • Summary

SyntaxError: ‘break’ outside loop

What is SyntaxError?

Syntax refers to the arrangement of letters and symbols in code. A Syntax error means you have misplaced a symbol or a letter somewhere in the code. Let’s look at an example of a syntax error:

number = 23

print()number
    print()number
           ^
SyntaxError: invalid syntax

The ^ indicates the precise source of the error. In this case, we have put the number variable outside of the parentheses for the print function, and the number needs to be inside the parentheses to print correctly.

print(number)
23

What is a Break Statement?

Loops in Python allow us to repeat blocks of code. In cases, Sometimes conditions arise where you want to exit the loop, skip an iteration, or ignore a condition. We can use loop control statements to change execution from the expected code sequence, and a break statement is a type of loop control statement.

A break statement in Python brings the control outside the loop when an external condition is triggered. We can put an if statement that determines if a character is an ‘s‘ or an ‘i‘. If the character matches either of the conditions the break statement will run. We can use either a for loop or a while loop. Let’s look at an example where we define a string then run a for loop over the string.

string = "the research scientist"

for letter in string:

    print(letter)

    if letter == 's' or letter == 'i':

        break

print("Out of the for loop")
t
h
e
 
r
e
s
Out of the for loop

The for loop runs until the character is an ‘s‘ then the break statement halts the loop. Let’s look at the same string example with a while loop.

i = 0

while True:

    print(string[i])

    if string[i] =='s' or string[i] == 'i':

        break

    i += 1

print(Out of the while loop")
t
h
e
 
r
e
s
Out of the while loop 

We get the same result using the while loop.

Example: If Statement

Let’s look at an example where we write a program that checks if a number is less than thirty. We can use an input() statement to get input from the user.

number = int(input("Enter an appropriate number "))

Next, we can use an if statement to check whether the number is less than thirty.

if number ≺ 30:

    print('The number is less than 30')

else:

    break

Suppose the number is less than thirty, the program prints a message to the console informing us. Otherwise, a program will run a break statement. Let’s run the program and see what happens:


Enter an appropriate number: 50

    break
    ^
SyntaxError: 'break' outside loop

The program returns the SyntaxError: ‘break’ outside loop because the break statement is not for breaking anywhere in a program. You can only use a break statement within a loop.

Solution

To solve this problem, we need to replace the break statement with an exception that stops the program if the number exceeds thirty and provides an exception message. Let’s look at the revised code.

number = int(input("Enter an appropriate"))

if number ≺ 30:

    print('The number is less than 30')

else:

    raise Exception("The number is not less than 30")

We replaced the break statement with a raise Exception.

<meta charset="utf-8">Enter an appropriate number: 50

Exception                                 Traceback (most recent call last)
      2     print('The number is less than 30')
      3 else:
----≻ 4     raise Exception('The number is greater than 30')
      5 

Exception: The number is greater than 30

If the number is greater than thirty the program will raise an exception, which will halt the program.

Summary

Congratulations on reading to the end of this tutorial! The error “SyntaxError: ‘break’ outside loop” occurs when you put a break statement outside of a loop. To solve this error, you can use alternatives to break statements. For example, you can raise an exception when a certain condition is met. You can also use a print() statement if a certain condition is met.

Go to the online courses page on Python to learn more about Python for data science and machine learning.

Have fun and happy researching!

Cover image for How to fix "SyntaxError: ‘break’ outside loop" in Python

Reza Lavarian

Update: This post was originally published on my blog decodingweb.dev, where you can read the latest version for a 💯 user experience. ~reza

Python raises “SyntaxError: ‘break’ outside loop” whenever it encounters a break statement outside a loop. The most common cases are using break within an if block (that’s not part of a loop) or when you accidentally use it instead of return to return from a function.

Here’s what the error looks like:

File /dwd/sandbox/test.py, line 2
  break
  ^^^^^
SyntaxError: 'break' outside loop

Enter fullscreen mode

Exit fullscreen mode

The break statement is a control flow feature used to break out of the innermost loop. For instance, when you reach a specific value. That’s pretty much like the C language.

Based on Python syntax, the break keyword is only valid inside loops — for and while.

Here’s an example:

values = [7, 8, 9.5, 12]

for i in values:
    # Break out of the loop if i > 10
    if (i > 10):
        break
    print(i)

Enter fullscreen mode

Exit fullscreen mode

The above code iterates over a list and prints out the values less than 10. Once it reaches a value greater than 10, it breaks out of the loop.

How to fix SyntaxError: ‘break’ outside loop

The error «SyntaxError: ‘break’ outside loop» occurs under two scenarios:

  1. When using break inside an if block that’s not part of a loop
  2. When using break (instead of return) to return from a function

Let’s see some examples with their solutions.

When using break inside an if block that’s not part of a loop: One of the most common causes of «SyntaxError: ‘break’ outside loop» is using the break keyword in an if block that’s not part of a loop:

if item > 100
  break # 🚫 SyntaxError: 'break' outside loop

# some code here

Enter fullscreen mode

Exit fullscreen mode

There’s no point in breaking out of an if block. If the condition isn’t met, the code isn’t executed anyway. The above code only would make sense if it’s inside a loop:

values = [7, 8, 9.5, 12]

for item in values:
    if (item > 10):
        break
    print(i)

Enter fullscreen mode

Exit fullscreen mode

Otherwise, it’ll be useless while being a SyntaxError too!

However, if you want to keep the if block for syntactical reasons, you can replace the break keyword with the pass keyword.

A pass statement does nothing in Python. However, you can always use it when a statement is required syntactically, but no action is needed.

When using break (instead of return) to return from a function: Another reason behind this error is to accidentally use the break keyword (instead of return) to return from a function:

def checkAge(age):
    if (age < 12):
        break # 🚫 SyntaxError: 'break' outside loop

    # some code here 

Enter fullscreen mode

Exit fullscreen mode

To return from a function, you should always use return (with or without a value):

def checkAge(age):
    if (age <= 12):
        return

    # some code here

Enter fullscreen mode

Exit fullscreen mode

Alright, I think it does it. I hope this quick guide helped you solve your problem.

Thanks for reading.

❤️ You might like:

  • TabError: inconsistent use of tabs and spaces in indentation (Python)
  • How to reverse a range in Python (with examples)
  • Unindent does not match any outer indentation level error in Python (Fixed)

Read next


ant_f_dev profile image

5 Visual Studio Code Extensions to Boost Web Development Productivity

Anthony Fung — Feb 6


srcecde profile image

Send notification based on CloudWatch logs filter patterns

Chirag (Srce Cde) — Jan 27


duxtech profile image

Cap XI: La rentabilidad metodológica, El libro negro del programador. 💻

Cristian Fernando — Jan 22


mariamarsh profile image

10 best GitHub repos for developers ✅

Maria 🍦 Marshmallow — Feb 2

Once unpublished, all posts by lavary will become hidden and only accessible to themselves.

If lavary is not suspended, they can still re-publish their posts from their dashboard.

Note:

Once unpublished, this post will become invisible to the public and only accessible to Reza Lavarian.

They can still re-publish the post if they are not suspended.

Thanks for keeping DEV Community 👩‍💻👨‍💻 safe. Here is what you can do to flag lavary:

Make all posts by lavary less visible

lavary consistently posts content that violates DEV Community 👩‍💻👨‍💻’s
code of conduct because it is harassing, offensive or spammy.

A break statement instructs Python to exit a loop. If you use a break statement outside of a loop, for instance, in an if statement without a parent loop, you’ll encounter the “SyntaxError: ‘break’ outside loop” error in your code.

In this guide, we’re going to discuss what this error means and why you may see it. We’ll explore an example of this error so you can learn how to fix the error.

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest

First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

SyntaxError: ‘break’ outside loop

The Python break statement acts as a “break” in a for loop or a while loop. It stops a loop from executing for any further iterations.

Break statements are usually enclosed within an if statement that exists in a loop. In such a case, a programmer can tell a loop to stop if a particular condition is met.

A break statement can only be used inside a loop. This is because the purpose of a break statement is to stop a loop. You can use a break statement inside an if statement, but only if that if statement is inside a loop.

An Example Scenario

Let’s write a program that validates a username for a game. A username must be under twelve characters long to be valid. A username must not contain any spaces.

To validate our username, we’re going to use two if statements. To start, let’s ask a user to choose a username for our game using an input() statement:

username = input("Enter your new username: ")

Next, let’s use an if statement to check whether our username is less than 12 characters long:

if len(username) < 12:
	print("This username is the right number of characters.")
else:
	break

If the username a user inserts into the program is fewer than 12 characters, our program prints a message to the console informing us that the username is of the correct length. Otherwise, a break statement will run.

Next, let’s validate whether that the username does not contain a space:

if " " not in username:
	print("This username is valid.")
else:
	break

We use an if...in statement to check for a character in the “username” string. We check for a blank space. This blank space is enclosed within the two quotation marks in our if statement.

If a username contains a space, a break statement executes. The break statement is part of the else statement in our code.

Let’s run our code and see what happens:

  File "main.py", line 6
	break
	^
SyntaxError: 'break' outside loop

Our code returns an error.

The Solution

We’ve used a break statement to halt our program if one of our criteria is not met when validating a user’s username.

This causes an error because the break statement is not designed to start a break anywhere in a program. The break statement only stops a loop from executing further.

To fix our code, we need to remove the break statements. We can replace them with an exception that stops our program and provides an error message:

if len(username) < 12:
	print("This username is the right number of characters.")
else:
	raise Exception("Your username must be under twelve characters.")

if " " not in username:
	print("This username is valid.")
else:
	raise Exception("Your username cannot contain space.s")

If the length of a username is equal to or greater than 12, or if a username contains a space, our program will raise an exception. This exception will stop our program from continuing.

Let’s run our code:

Enter your new username: bill3
This username is the right number of characters
This username is valid

Our code runs successfully if our username is valid. Let’s see what happens if we enter an invalid username:

Enter your new username: bill 3
This username is the right number of characters
Traceback (most recent call last):
  File "main.py", line 11, in <module>
	raise Exception("Your username cannot contain spaces")
Exception: Your username cannot contain spaces

Our code returns an exception. Alternatively, we could have used print statements to inform the user that their username was incorrect. This would only be suitable if we wanted our program to continue, or if we had a loop that ran until a username validated successfully.

Conclusion

The “SyntaxError: ‘break’ outside loop” error is raised when you use a break statement outside of a loop.

To solve this error, replace any break statements with a suitable alternative. To present a user with a message, you can use a print() statement. To halt execution of your program when a condition is met, you can raise an exception.

  • The break statement in Python is used to get out of the current loop.
  • We can’t use break statement outside the loop, it will throw an error as “SyntaxError: ‘break’ outside loop“.
  • We can use break statement with for loop and while loops.
  • If the break statement is present in a nested loop, it terminates the inner loop.
  • The “break” is a reserved keyword in Python.

Flow Diagram of break Statement

Break Statement Flow Diagram
Break Statement Flow Diagram

The break statement syntax is:

We can’t use any option, label or condition with the break statement.


Python break Statement Examples

Let’s look at some examples of using break statement in Python.

1. break statement with for loop

Let’s say we have a sequence of integers. We have to process the sequence elements one by one. If we encounter “3” then the processing must stop. We can use for loop for iteration and break statement with if condition to implement this.

t_ints = (1, 2, 3, 4, 5)

for i in t_ints:
    if i == 3:
        break
    print(f'Processing {i}')

print("Done")

Output:

Python Break Statement For Loop
Python break Statement with for Loop

2. break statement with the while loop

count = 10

while count > 0:
    print(count)
    if count == 5:
        break
    count -= 1

Output:

Python Break Statement While Loop
Python break Statement with while Loop

3. break statement with a nested loop

Here is an example of break statement within the nested loop.

list_of_tuples = [(1, 2), (3, 4), (5, 6)]

for t in list_of_tuples:
    for i in t:
        if i == 3:
            break
        print(f'Processing {i}')

Output:

Python Break Statement Nested Loop

Python break Statement Nested Loop

Why Python doesn’t support labeled break statement?

Many popular programming languages support a labelled break statement. It’s mostly used to break out of the outer loop in case of nested loops. However, Python doesn’t support labeled break statement.

PEP 3136 was raised to add label support to break statement. But, it was rejected because it will add unnecessary complexity to the language. There is a better alternative available for this scenario – move the code to a function and add the return statement.

Понравилась статья? Поделить с друзьями:
  • Svn error working copy locked
  • Syntax error at or near select перевод
  • Svn error running context
  • Syntax error at or near returning
  • Svn error 500