Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assignment Condition in Python While Loop

In C, one can do

while( (i=a) != b ) { } 

but in Python, it appears, one cannot.

while (i = sys.stdin.read(1)) != "\n": 

generates

    while (i = sys.stdin.read(1)) != "\n":          ^ SyntaxError: invalid syntax 

(the ^ should be on the =)

Is there a workaround?

like image 986
tekknolagi Avatar asked Oct 15 '11 22:10

tekknolagi


People also ask

How do you put a condition in a while loop in Python?

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.

Can we assign value in while loop?

You can pretty well use it anywhere a normal expression can be used (that comma inside your function calls is not a comma operator, for example) and it's very useful in writing compact source code, if that's what you like. In that way, it's part of the family that allows things like: while ((c= getchar()) !=

What is the condition in a while loop?

The while loop is used when we don't know the number of times it will repeat. If that number is infinite, or the Boolean condition of the loop never gets set to False, then it will run forever.

Can we use assignment operator in if condition in Python?

No. Assignment in Python is a statement, not an expression.


2 Answers

Starting Python 3.8, and the introduction of assignment expressions (PEP 572) (:= operator), it's now possible to capture an expression value (here sys.stdin.read(1)) as a variable in order to use it within the body of while:

while (i := sys.stdin.read(1)) != '\n':   do_smthg(i) 

This:

  • Assigns sys.stdin.read(1) to a variable i
  • Compares i to \n
  • If the condition is validated, enters the while body in which i can be used
like image 167
Xavier Guihot Avatar answered Sep 23 '22 13:09

Xavier Guihot


Use break:

while True:     i = sys.stdin.read(1)     if i == "\n":        break     # etc... 
like image 20
Mark Byers Avatar answered Sep 23 '22 13:09

Mark Byers