I just came across this piece of code
while 1: line = data.readline() if not line: break #...
and thought, there must be a better way to do this, than using an infinite loop with break
.
So I tried:
while line = data.readline(): #...
and, obviously, got an error.
Is there any way to avoid using a break
in that situation?
Ideally, you'd want to avoid saying readline
twice... IMHO, repeating is even worse than just a break
, especially if the statement is complex.
Yes. you can declare a variable inside any loop(includes do while loop.
You initiate the loop with the while keyword, then set the condition to be any conditional expression. A conditional expression is a statement that evaluates to True or False . As long as the condition is true, the loop body (the indented block that follows) will execute any statements it contains.
Yes, the comma operator has the lowest precedence of all.
You need to initialize previous guess before while loop Otherwise it will be initialized again and again. You have to set the value of previous guess to x the computer generator and when you move on after loop you have to update the previous guess to next simply like this: Add before while { previous_guess = x }
Starting Python 3.8
, and the introduction of assignment expressions (PEP 572) (:=
operator), it's now possible to capture the condition value (data.readline()
) of the while loop as a variable (line
) in order to re-use it within the body of the loop:
while line := data.readline(): do_smthg(line)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With