+ 2
what is the difference between "while" and "while True " in Python?
4 Respuestas
+ 6
'while' is a keyword
'while True' is a complete while statement with a boolean value.
The 'while' keyword needs to be followed by a condition that will return a boolean value.
Syntax:
🔸 while condition:
code
In your question, True is already a boolean value so the code inside the while block will execute infinitely unless a break keyword is executed.
EDIT: (for recent examples you've posted)
From your first example:
🔹 while True means that it will print i and add 1 to it infinitely...
🔹 however, there is a condition if i >= 5 where if it becomes True, the break will execute then the while loop will stop.
Second example:
🔹 Same output with the first one but different approach
🔹 In this case, the condition is in the while statement, and once i becomes greater or equal to 4, the while loop will stop.
For better understanding, I adjusted the value of i so it will be the same for both examples.
https://code.sololearn.com/cVp44Cs9v0OQ/?ref=app
+ 3
while : syntax error
while true : start of loop with true condition runs until innerly break
Can you show your code snippets about what is your question actually about???
+ 3
while True : #condition is always True, loop runs until breaked explicitly
while i<=4 : # loop runs until i<=4 becomes false.
+ 1
i = 0
while True:
print(i)
i = i + 1
if i >= 5:
break
i = 1
while i <=4:
print(i)
i = i + 1