A while statement's condition is always true or false, like the if statement. This means Boolean math can be used to control the looping. Since while False: will never execute, what will while True: do? It will infinitely loop. This will be important later; we'll spend more time on it later in the lesson. ,Unlike a lot of other computer languages, Python allows you to use an else statement in conjunction with a while statement. When a while statement finishes its loop naturally, it will then execute the else statement. If the while statement stops prematurely for any reason, it will not execute the else statement. An example is given below. ,There can be times when you want to prematurely end a while statement. The break statement can be used to accomplish this. The break statement can be used to prematurely end the while statement that it's nested in. This means it will end only one while statement, not all of them. An example is given below. , The above example demonstrates that a while loop can be ended, even if it is True. You should also note from the example that the break statement doesn't require a colon (:), which means new indentation isn't needed. Putting a colon at the end of break will cause an error; the omission of the colon isn't optional, it's mandatory.
>>> pop = 0 >>>
while pop != 5:
...pop += 1
...print(pop)
...
1
2
3
4
5
>>>
eggs = [12, 4, 2, 6, 11, 23] >>>
while eggs:
...print(eggs[0])
...del eggs[0]
...
12
4
2
6
11
23
>>>
while False:
...print("This will never print!")
...
>>>
spam = 10 >>>
while spam:
...spam -= 1
...print(spam)
...
9
8
7
6
5
4
3
2
1
0
>>> spam = 0
>>> while spam != 10:
... spam += 1
... print(spam)
... else:
... print("Done printing spam!")
...
1
2
3
4
5
6
7
8
9
10
Done printing spam!
>>> while True:
... pass
... else:
... print("I'll never get seen on the screen!")
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
KeyboardInterrupt
>>> pop = 0 >>>
while True:
...print(pop)
...pop += 1
...
if pop == 10:
...
break
...
0
1
2
3
4
5
6
7
8
9
>>> bacon = 0 >>>
while bacon != 10:
...bacon += 1
...
if bacon < 5:
...
continue
...print(bacon)
...
5
6
7
8
9
10
x = 11;
normalTermination = False
while x:
x -= 1
if x < 5: continue
print(x)
else:
normalTermination = True
if normalTermination:
print('normal termination')
else:
print('abnormal termination')
x = 11;
normalTermination = False
while x:
x -= 1
if x < 5: continue
print(x)
else:
normalTermination = True
if normalTermination:
print('normal termination')
else:
print('abnormal termination')
10
9
8
7
6
5
normal termination
x = 11;
normalTermination = False
while x:
x -= 1
if x < 5: break
print(x)
else:
normalTermination = True
if normalTermination:
print('normal termination')
else:
print('abnormal termination')
for c in [-4, 0, 3, 19]:
print('\ninitial c =', c)
while 5 > c >= 0:
print('c =', c)
c += 1
else:
print('normal termination. c =', c)
initial c = -4 normal termination.c = -4 initial c = 0 c = 0 c = 1 c = 2 c = 3 c = 4 normal termination.c = 5 # This is probably what you wanted. initial c = 3 c = 3 c = 4 normal termination.c = 5 initial c = 19 normal termination.c = 19
Use break
to exit a loop:
while True:
ser = serial.Serial("/dev/ttyUSB0", 4800, timeout = 1)
checking = ser.readline();
if checking.find(",,,,"):
print "not locked yet"
else:
print "locked and loaded"
break
So instead of having this code:
while True:
...
if...: True
else:
False
... try this:
keepGoing = True
while keepGoing:
ser = serial.Serial("/dev/ttyUSB0", 4800, timeout = 1)
checking = ser.readline();
if checking.find(",,,,"):
print "not locked yet"
keepGoing = True
else:
keepGoing = False
print "locked and loaded"
Last Updated : 22 Nov, 2021,GATE CS 2021 Syllabus
Sum of First 10 Numbers is 55
While Operation: Check the boolean test expression, if it is True, run all the "body" lines inside the loop from top to bottom. Then loop back to the top, check the test again, and so on. When the test is False, exit the loop, running continues on the first line after the body lines. ,Just as with the for-loop, a while-loop can iterate zero times. That happens if the boolean test is False the very fist time it is checked, like this: ,The while-loop uses a boolean test expression to control the run of the body lines. The for-loop is great of looping over a collection. The while-loop is more general, providing enough control for any sort of looping, without requiring a collection to loop over. ,The while-loop syntax has 4 parts: while, boolean test expression, colon, indented body lines:
The while-loop syntax has 4 parts: while, boolean test expression, colon, indented body lines:
while test:
indented body lines
Here is a while loop to print the numbers 0, 1, 2, ... 9 (there are easier ways to do this, but here we're just trying to show the parts of the loop).
i = 0
while i < 10:
print(i)
i = i + 1
print('All done')
0
1
2
3
4
5
6
7
8
9
All done
Just as with the for-loop, a while-loop can iterate zero times. That happens if the boolean test is False the very fist time it is checked, like this:
i = 99 while i < 10: print(i) i += 1 print('All done') #(zero iterations - no numbers print at all) All done
Suppose there is some function foo()
and you want a while loop to run so long as it returns True. Do not write this
while foo() == True: # NO not this way ...
It's better style to write it the following way, letting the while itself evaluate the True/False of the test:
while foo(): # YES this way ...
The while statement will repeatedly execute the loop statement or code block while the true/false expression is true. To stop the looping, something needs to happen to change the true/false expression to false.,Follow the while(true/false expression) with a single statement or a block of code. The single statement or code block is repeatedly executed while the condition is true.,In this case, the operand or operands of the while statement’s true/false expression are modified in the while statement’s code block.,There are several ways to change the while true/false expression when the while true/false expression is evaluated. The most common way is to use the increment and decrement operators.
Example
// execute single statement
while (loopCount)
cout << "in while loop " << loopCount-- << endl;
while (loopCount) {
// execute multiple statements
// ...
}
Example 1
while (count > 0) {
// do some work
// ...
// change the value of count
count = count - 1;
}
In this example, the user inputs a new value for testScore
during every loop. The while statement will loop until the user inputs a correct value within 0 and 100.
int testScore;
cout << "Enter test score (0 to 100): ";
cin >> testScore;
while (testScore < 0 || testScore > 100) // testScore is not valid
{
cout << "Invalid test score entered. Re-enter score: ";
// Get a new value for testScore every time the loop executes
cin >> testScore;
}
In simple expression, prefix and postfix modes act the same.
// both are equivalent to x = x + 1;
x++;
++x;
// both are equivalent to x = x - 1;
x--;
--x;
- If you use prefix mode, the variable is incremented or decremented before the expression is evaluated.
- If you use postfix mode, the variable is incremented or decremented after the expression is evaluated.
x = 5;
// postfix, x incremented after addition
y = 10 + x++;
-
At the end of this code, x = ? and y = ?x = 6
y = 15
x = 5;
// prefix, x incremented before addition
y = 10 + ++x;
Here is quick example of an incrementing counter.
int numberOfInputs = 5;
int count = 0;
// use < because count starts at 0
while (count < 5) {
cout << "Current value of count: " << count << endl;
count++;
}