tags:

views:

454

answers:

3

Is there any way to do this in python? I.e. have the variable assignment return the assigned value and compare that to an empty string, directly in the while loop. No biggie if it isn't possible, just to used to doing it in php.

while((name = raw_input("Name: ")) != ''):
    names.append(name)

What I'm trying to do is identical to this in functionality:

names = []
while(True):
    name = raw_input("Name: ")
    if (name == ''):
        break
    names.append(name)
+7  A: 

No, sorry. It's a FAQ though explained here:

http://www.python.org/doc/faq/general/#why-can-t-i-use-an-assignment-in-an-expression

Phil
+9  A: 

No. The python solution is to turn raw_input into a generator (return the data to process with yield instead of return) and then use the for loop:

names = []
for name in raw_input("Name: "):
    names.append(name)

or, even shorter,

names = list(raw_input("Name: "))

Complete code:

def raw_input(x):
    results = ['a1','b2','c3']
    for s in results:
        yield s

names = []
for name in raw_input("Name: "):
    names.append(name)

print names
names = list(raw_input("Name: "))
print names

This prints:

['a1', 'b2', 'c3']
['a1', 'b2', 'c3']

From the comments, I now realize that raw_input() is a method defined by Python, so you need to wrap it:

def wrapper(s):
    while True:
        result = raw_input(s)
        if result = '': break
        yield s

which means we're back to square one but with more complex code. So if you need to wrap an existing method, you need to use nosklo's approach.

Aaron Digulla
+1: Beat me by seconds. Please add the definition of "raw_input as generator" to your answer, though.
S.Lott
Cool thanks! First time using stack overflow btw, never knew it was this awesome, a perfect answer within minutes :)
Andreas
Can you detail how to "turn raw_input into a generator" in a very pythonic way?
vgm64
do you turn it to a generator or use it as a generator? btw nice answer, didn't you know raw_input can be used that way :)
hasen j
This solution will assign a list of characters in the first response to names. It's incorrect.
recursive
recursive is right. Nosklo's answer below is correct: iter() will run until '' is reached, and then list() will converts each iteration to an element.
Richard Levasseur
@recursive: Sorry, didn't realize that raw_input() was an existing method. I assumed that it was something Andreas had written.
Aaron Digulla
+4  A: 
from functools import partial

for name in iter(partial(raw_input, 'Name:'), ''):
    do_something_with(name)

or if you want a list:

>>> names = list(iter(partial(raw_input, 'Name: '), ''))
Name: nosklo
Name: Andreas
Name: Aaron
Name: Phil
Name: 
>>> names
['nosklo', 'Andreas', 'Aaron', 'Phil']
nosklo
+1 for better solution for wrapping an existing method.
Aaron Digulla