If the while loop body consists of one statement, write this statement into the same line: while True: print(‘Hello’). Even you can write a single line while loop which has multiple iterations in Python.
a = 5
while a > 0: a = a - 1; print(a)
The upper code will print 4 to 0 numbers. But It also covers the limitations of this approach.
Python One Line While Loop Example
Simple examples code.
Single-Statement While Loop One-Liner
This code will run infinite iteration so do use exit before running it.
while True: print('Hello') #;exit();
Output:
Multi-Statement While Loop One line
It is not as readable, and it doesn’t conform to PEP 8, but it is doable.
a = 5
while a > 0: a = a - 1; print(a)
Output:
4
3
2
1
0
Nested Compound Statements While Loop Single line
When using a compound statement in python (statements that need a suite, an indented block), and that block contains only simple statements, you can remove the newline, and separate the simple statements with semicolons.
However, that does not support compound statements.
So:
if expression: print "something"
works, but
while expression: if expression: print "something"
does not because both the while
and if
statements are compound.
Source: stackoverflow.com
Do comment if you have any doubts and suggestions on this Python while loop topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.