- Forum
- Beginners
- Continue statement not within a loop.
Continue statement not within a loop.
|
|
So the thing is, why am I getting the (Continue statement not within a loop.) error?
and if it is possible, how can i assign the (You have chosen) into a variable? because whenever I type in:
char chosen [25]= You have chosen
it always gets the (You) only..
Because the continue
statement can only be within a loop
Use std::strings instead of char arrays.
continue stops the current iteration of the loop and goes straight to the next iteration, what exactly were you trying to accomplish with your continue statement?
Last edited on
I thought that (switch) was a loop statement.
and thanks for the advice..=)
and isnt the (continue statement) used to «continue» the loop?? or is it something else?
you guys have to go easy on me, am a total noob..yet=P
Like I said, continue quits the current iteration of a loop, so if a continue statement is before the functionality of the loop it won’t do anything for that iteration. See below:
|
|
this will output
make sense?
Topic archived. No new replies allowed.
Actually you can use it in switch inside loops, in this cases break/continue are a useful combo
take a look at this example
var array = [1, 2, "I am a string", function(){}, {}, 1,2,3]
for(let i in array){
switch(typeof array[i]) {
case "number":
array[i] += " I was a number"
break; // break from the switch but go on in the for-loop
// ie. go to *put esclamation mark*
case "function":
array[i] = "function"
// fall through
default:
array[i] = `this is a ${JSON.stringify(array[i])} object`
break; // also here goes to *put esclamation mark*
case "string":
continue; // continue with the next iteration of the loop
// ie. do not put exclamation mark in this case
}
array[i] += "!" // *put esclamation mark*
}
/*
array will become
[ "1 I was a number!", "2 I was a number!", "I am a string", "this is a "function" object!", "this is a {} object!", "1 I was a number!", "2 I was a number!", "3 I was a number!" ]
*/
superprogrammer 0 / 0 / 0 Регистрация: 05.12.2014 Сообщений: 3 |
||||
1 |
||||
Компилятор не видит циклы!05.08.2015, 08:04. Показов 2277. Ответов 7 Метки нет (Все метки)
Конечно, я понимаю что процессор ошибиться не может, и дело только в моем коде, но я считаю что я правильно использую команды break и continue в циклах do while и while, а вот компилятор GNU C++ так не думает…
В 23/29 строке пишет break/continue statement not within a loop (or switch).
__________________
0 |
Programming Эксперт 94731 / 64177 / 26122 Регистрация: 12.04.2006 Сообщений: 116,782 |
05.08.2015, 08:04 |
7 |
Ilot 2001 / 1332 / 379 Регистрация: 16.05.2013 Сообщений: 3,450 Записей в блоге: 6 |
||||
05.08.2015, 08:11 |
2 |
|||
Тест на внимательность?
Проверку ввода пишите самостоятельно.
1 |
zss Модератор 12641 / 10135 / 6102 Регистрация: 18.12.2011 Сообщений: 27,170 |
||||
05.08.2015, 08:12 |
3 |
|||
Поставлю дополнительные скобки для понимания ошибки
1 |
0 / 0 / 0 Регистрация: 05.12.2014 Сообщений: 3 |
|
05.08.2015, 08:23 [ТС] |
4 |
Я так понял что мне цикл do while просто здесь не нужен, так или иначе всем спасибо!
0 |
tnk500 117 / 121 / 42 Регистрация: 25.08.2012 Сообщений: 1,294 |
||||||||
05.08.2015, 08:26 |
5 |
|||||||
superprogrammer, циклы do имеюют проверку условий в конце:
И смысла в двух последних циклах нет — второй может легко стать бесконечным. Хотите сделать то, что хотели сделать — пишите так:
1 |
zss Модератор 12641 / 10135 / 6102 Регистрация: 18.12.2011 Сообщений: 27,170 |
||||
05.08.2015, 08:28 |
6 |
|||
tnk500,
if(sEntPas1 == sRPas1); Это то же самое, что и
0 |
tnk500 |
05.08.2015, 08:32
|
Не по теме: zss, спасибо, не заметил
0 |
zer0mail |
05.08.2015, 20:45
|
Не по теме: Ощущается какое-то противоречие названия темы с ником автора
0 |
- Home
- C Keywords
- continue
The continue statement interrupts the current step of a loop and continues with the next iteration. We do this, for some particular case, when we don’t want to execute the entire body of the loop, but still we want to go through the rest of the iterations.
This is for contrast of the break statement which stops the execution of the loop and transfers the control to the first line after the loop.
Here is a flowchart that demonstrates the behavior of continue:
Usage
continue:
- must be used inside of a loop. Otherwise it makes no sense and the compiler will laugh at you (the error will look like this: «error: continue statement not within a loop«)
- will always be in a conditional statement. Otherwise part of the loop(the «More loop statements» block in the flowchart above) will be «dead code» which will never execute , which also makes no sense (but the compiler will be quiet)
Let’s print all capital letters from A to G, with the exception of E.
char letter; for(letter = 'A'; letter <= 'G'; letter++) { if(letter == 'E') continue; printf("%c", letter); }
Continue statement in nested loops
When we use nested loops we will interrupt only the body of the inner-most loop that surrounds
the statement.
while(...) { //body of the outer loop for(...) { //body of the inner loop if(...) continue; } }
Here we will interrupt only the current
execution of the for loop and transfer control to the next iteration of the for
loop.
In the next example, continue is not part of the inner loop. When the “if” is true, we stop the execution of
the while’s body and skip the entire for loop. The next iteration over the
while will execute normally, including the inner loop.
while(...) { //body of the outer loop if(...) continue; for(...) { //body of the inner loop } }
Summary
In practice the continue statement is rarely used. If you write code regularly,
eventually you will need it at some point, but not as frequently as the break statement.
Related topics:
- for loop
- do..while
- while
- break
- Home
- C Keywords
- continue
While writing code in Python, we need to follow some rules, that define how the code must be written, which is also known as syntax. Every individual statement has its own syntax. And if we do not follow that syntax, Python raises the SyntaxError Exception.
The continue is a Python keyword and a loop control statement. It can only be written inside the loop body, and if we try to use it outside the loop, there Python will raise the
SyntaxError: 'continue' not properly in loop
error.
This Python guide discusses the following error in detail and demonstrates a common example scenario with a solution. By the end of this article, you will have a complete idea of what is
SyntaxError: 'continue' not properly in loop
Error in Python, why it occurs, and how to debug it.
This error raises in a Python program when the
continue
statement is written outside the
for
or
while
loop body.
Example
age = 20
if age>=18:
print("You are eligible to get the vaccine ")
continue
else:
print("You are not Eligible for vaccing")
output
File "main.py", line 4
continue
^
SyntaxError: 'continue' not properly in loop
The error statement has two sub statements separated with a colon
:
.
- SyntaxError
- ‘continue’ not properly in the loop
1. SyntaxError
SyntaxError is one of Python’s standard exceptions. Python parser raises this exception when it finds some statement is not following the defined syntax.
2. ‘continue’ not properly in the loop
This is the error message, telling us that the
continue
keyword is not inside the loop body. We only receive this error message when we use the
continue
keyword outside the loop body. In the above example, we have used the
continue
in the
if..else
body, that’s why Python’s parser raised the error.
Common Example Scenario
continue
can only be used within the
for
or
while
loop body, and it continues to the next iteration of the loop. Inside the loop we can use it anywhere, generally, we put it inside the
if..else
condition so it can only execute for specific conditions not for every iteration.
Example
Let’s create an input validator that asks the user to enter a valid 4 digit passcode between 1000 to 9999. And if the user enters the valid number we will display a message that «the passcode is valid» if not we will display the message that «the passcode is invalid» and ask the user to enter the passcode again.
passcode = int(input("Enter a valid 4 digit passcode (1000 to 9999): "))
#if passcode is not valid
if not (passcode >=1000 and passcode <=9999):
print("Your Passcode is Not valid n Please enter again ")
continue
else:
print("The entered Passcode is valid")
Output
File "main.py", line 6
continue
^
SyntaxError: 'continue' not properly in loop
Break the code
Python is raising the error in the above example because the
continue
statement is not inside any loop statement. The logic we have put in the above example misses the loop statement.
Solution
To solve the above problem we need to put all the code inside the while loop statement with the default condition True, which will make the loop infinite. And the user can only exit that loop when it enters the valid passcode.
while True:
passcode = int(input("Enter a valid 4 digit passcode (1000 to 9999): "))
#if passcode is not valid
if not (passcode >=1000 and passcode <=9999):
print("Your Passcode is Not valid nPlease enter again ")
continue
else:
#if the passcode is valid print the statement and get out of the loop
print("The entered Passcode is valid")
break
Output
Enter a valid 4 digit passcode (1000 to 9999): 99999
Your Passcode is Not valid
Please enter again
Enter a valid 4 digit passcode (1000 to 9999): 9898
The entered Passcode is vaid
Now the Python script runs without any SyntaxError.
Conclusion
While working with the loops we get two-loop control keywords
continue
and
break
. These two keywords are exclusive for loop statements (for and while). And if we use these keywords outside the loop code block we receive the Syntax Error with an error message. For the
continue
outside the loop scope, Python throws the
'continue' not properly in loop
Error and for
break
it throws
'break' outside the loop
error.
This error is very common in Python, and debugging it is also very easy. The only thing you need to keep in mind that, you can not use these two keywords outside the loop scope. If you are still getting this error in your Python program, please share your code in the comment section. We will try to help you in debugging.
People are also reading:
-
Python typeerror: ‘str’ object is not callable Solution
-
How to loop with indexes in Python?
-
Python NameError name is not defined Solution
-
How To Make a Game With Python?
-
Python TypeError: ‘NoneType’ object is not callable Solution
-
Flatten List & List of Lists in Python
-
Python IndexError: tuple index out of range Solution
-
What is Tornado in Python?
-
How to find and remove loops in a Linked List?
-
Python TypeError: ‘>’ not supported between instances of ‘str’ and ‘int’ Solution