1

Possible Duplicate:
Is there any way to do variable assignments directly inside a while(<here>) loop in Python?

Sorry about such a basic question. I'm trying to learn Python, but really haven't found an answer to this.

In Python, can I assign a value to a variable in a while or if statement? If so, how?

For example. I had to do this:

line_list = []
while True:
    line = raw_input(">>> ")
    if not line: break
    line_list.append(line)
print line_list

But I'd like to do this:

line_list = []
while line = raw_input(">>> "):
    line_list.append(line)
print line_list

The tutorials I'm looking at don't mention this one way or another, but this is a common construct in most other languages.

Community
  • 1
  • 1
David W.
  • 105,218
  • 39
  • 216
  • 337
  • 4
    This cannot be done. And if you search, you'll see that you're not the first person to ask. "a common construct in most other languages" is false, also. It's common in C, C++ and languages the specifically strive for C-like features. That's not *most*. – S.Lott Feb 01 '12 at 20:11

3 Answers3

7

That's not possible. Assignments in Python are statements, not expressions.

They do not evaluate to the assigned value, nor return a reference to the object being assigned to, as is customary in other languages.

Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
6

As Frédéric's answer indicates, it is impossible to assign to a variable an a while or if, however you can accomplish basically the same thing using iter() with the function/sentinel call format:

for line in iter(lambda: raw_input(">>>"), ""):
    line_list.append(line)
Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
0

You don't want to use a while loop here! That infinitely appends to the list, once some input is entered and "enter" is hit.

This should work:

while 1:
    line = raw_input(">>> ")
    if line:
        line_list.append(line)

Of course, this isn't the same thing, but it works for what you want, as far as I can tell.

uncleshelby
  • 543
  • 1
  • 8
  • 19