在括号中循环使用子赋值

dyl*_*nmc 0 python loops inline variable-assignment

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

#PSEUDO CODE!!
while (inp = input()) != 'quit'
    print(inp)
Run Code Online (Sandbox Code Playgroud)

例如,在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());
}
Run Code Online (Sandbox Code Playgroud)

编辑:

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

while True:
    inp = input()
    if inp == 'quit':
        break
    print(inp)
print('eof')
Run Code Online (Sandbox Code Playgroud)

iCo*_*dez 5

编辑:

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

for inp in iter(input, 'quit'):
    print(inp)
Run Code Online (Sandbox Code Playgroud)

iter(input, 'quit')只要此值不相等,它将继续调用input函数并将其返回值赋值.inp'quit'


不,您无法在Python中执行内联分配.该语法根本不允许这样做(请记住,分配是语句在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
Run Code Online (Sandbox Code Playgroud)

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