Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
628 views
in Technique[技术] by (71.8m points)

syntax - How to do variable assignment inside a while(expression) loop in Python?

I have the variable assignment in order to return the assigned value and compare that to an empty string, directly in the while loop.

Here is how I'm 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)

Is there any way to do this in Python?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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']

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...