Syntax error break outside loop как исправить

Что это значит: в отличие от многих других языков, команда 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!

Содержание

  1. Что означает ошибка SyntaxError: ‘break’ outside loop
  2. Что делать с ошибкой SyntaxError: ‘break’ outside loop
  3. Break Outside Loop Error in Python: Cause and Resolution
  4. What does ‘break’ mean in Python?
  5. output:
  6. SyntaxError: break outside loop in Python:
  7. output:
  8. Resolution for SyntaxError: break outside loop in Python:
  9. Output:
  10. Output:
  11. Difference between break, exit and return:
  12. Conclusion: Break Outside Loop Python
  13. How to Solve Python SyntaxError: ‘break’ outside loop
  14. Table of contents
  15. SyntaxError: ‘break’ outside loop
  16. What is SyntaxError?
  17. What is a Break Statement?
  18. Example: If Statement
  19. Solution
  20. Summary
  21. Ошибка Break Outside Loop в Python: Причина и разрешение
  22. Ошибка Break Outside Loop в Python: Причина и разрешение
  23. Что значит “сломать” в Python?
  24. выход:
  25. Синтаксическая ошибка: разрыв внешнего цикла в Python:
  26. выход:
  27. Разрешение для SyntaxError: break outside loop в Python:
  28. Выход:
  29. Выход:
  30. Разница между break, exit и return:
  31. Вывод: Разорвать Внешний цикл Python
  32. Python SyntaxError: ‘break’ outside loop Solution
  33. Find Your Bootcamp Match
  34. SyntaxError: ‘break’ outside loop
  35. An Example Scenario
  36. The Solution
  37. Conclusion

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

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

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

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

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

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

❌ SyntaxError: ‘break’ outside loop

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

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

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

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

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

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

Источник

Break Outside Loop Error in Python: Cause and Resolution

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.

output:

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.

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.

Output:

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.

Output:

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.

Источник

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?

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:

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.

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.

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.

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.

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

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:

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.

We replaced the break statement with a raise Exception .

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.

Источник

Ошибка Break Outside Loop в Python: Причина и разрешение

Оператор python break используется для резкого выхода из цикла, вызывая условие.”Синтаксическая ошибка: разрыв вне цикла” происходит, если используется

Автор: Team Python Pool
Дата записи

Ошибка Break Outside Loop в Python: Причина и разрешение

Привет, кодеры!! В этой статье мы узнаем об ошибке цикла “break outside loop” в Python. Мы увидим его причину на некоторых примерах и в конечном итоге узнаем, как устранить эту ошибку. Давайте теперь разберемся в этом подробнее.

Что значит “сломать” в Python?

Оператор break используется для указания Python выйти из цикла. Он обычно используется для внезапного выхода из цикла при срабатывании какого-либо внешнего условия. Оператор break может использоваться в любом типе цикла – while loop и for loop.

выход:

Как мы видим, когда значение переменной становится 5, условие для оператора break срабатывает, и Python резко выходит из цикла.

Синтаксическая ошибка: разрыв внешнего цикла в Python:

Цель оператора break состоит в том, чтобы резко завершить цикл, вызвав условие. Таким образом, оператор break может использоваться только внутри цикла. Он также может быть использован внутри оператора if, но только если он находится внутри цикла. Если кто-то использует оператор break вне цикла, то он получит в своем коде ошибку “Синтаксическая ошибка: ‘break’ outside loop”.

выход:

Мы видим, что возникает синтаксическая ошибка Error: break outside loop. Это происходит потому, что мы использовали оператор break без какого-либо родительского цикла.

Разрешение для SyntaxError: break outside loop в Python:

Причина вышеприведенной ошибки заключается в том, что оператор break не может быть использован нигде в программе. Он используется только для того, чтобы остановить дальнейшее выполнение цикла.

Нам нужно удалить операторы break, чтобы устранить ошибку. Исключение может заменить его. Мы используем исключения, чтобы остановить программу и выдать сообщение об ошибке.

Выход:

Теперь код возвращает исключение, основанное на заданном условии. Когда мы используем исключение, оно останавливает дальнейшее выполнение программы( если срабатывает) и выводит сообщение об ошибке.

Если мы хотим, чтобы программа продолжала дальнейшее выполнение, мы можем просто использовать оператор print.

Выход:

Здесь, благодаря использованию оператора print, программа не останавливается от выполнения.

Разница между break, exit и return:

ПЕРЕРЫВ ВЫХОД ВЕРНУТЬ
Ключевое слово Системный вызов Инструкция
выход из петли выйдите из программы и верните управление обратно в ОС возвращает значение из функции

Вывод: Разорвать Внешний цикл Python

В этой статье мы подробно обсудили Python “break out of loop error.” Мы узнали об использовании оператора break и увидели сцену, в которой может произойти упомянутая ошибка. Поэтому, чтобы избежать этого, мы должны помнить, что использовать оператор break только внутри цикла.

Однако, если у вас есть какие-либо сомнения или вопросы, дайте мне знать в разделе комментариев ниже. Я постараюсь помочь вам как можно скорее.

Источник

Python SyntaxError: ‘break’ outside loop Solution

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.

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:

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

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:

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:

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 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:

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

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.

About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.

Источник

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.

Понравилась статья? Поделить с друзьями:
  • Svs ошибка faw
  • Syntax error break outside loop python
  • Svs джили атлас ошибка
  • Syntax error begin expected but identifier a found error
  • Svr4 error 22 invalid argument