在括号中循环使用子赋值

时间:2014-07-22 16:24:11

标签: python loops inline variable-assignment

有没有办法在Python中执行此操作? (我知道你可以做Java。)

#PSEUDO CODE!!
while (inp = input()) != 'quit'
    print(inp)

E.g。在java中,上面的伪代码转换为:

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try {
    String inp;
    while (!(inp = reader.readLine()).equals("quit")) {
        System.out.println(inp);
    }
} catch (IOException io) {
    System.out.println(io.toString());
}

编辑:

......回答......但这是唯一的方法吗?

while True:
    inp = input()
    if inp == 'quit':
        break
    print(inp)
print('eof')

2 个答案:

答案 0 :(得分:5)

修改

在这种特殊情况下,您可以使用for循环和iter

for inp in iter(input, 'quit'):
    print(inp)
只要此值不等于iter(input, 'quit')

input将继续调用inp函数并将其返回值分配给'quit'


不,您无法在Python中执行内联分配。 grammar根本不允许它(请记住,赋值是Python中的语句)。

你可以这样做:

while True:            # Loop continuously
    inp = input()      # Get the input
    if inp == 'quit':  # If it equals 'quit'...
        break          # ...then break the loop
    print(inp)         # Otherwise, continue with the loop

它大致相当于你想要做的事情。

答案 1 :(得分:1)

您可以在循环之前定义inp并在while内重新分配:

inp = None
while inp  != 'quit':
    print(inp)
    inp = input()

如果您想在最初进入while循环设置inp = input()之前退出。

inp = input()
while inp  != 'quit':
    print(inp)
    inp = input()