gpt4 book ai didi

python - Python While 循环中的赋值条件

转载 作者:IT老高 更新时间:2023-10-28 22:21:22 30 4
gpt4 key购买 nike

在 C 中,可以做到

while( (i=a) != b ) { }

但在 Python 中,似乎不能。

while (i = sys.stdin.read(1)) != "\n":

生成

    while (i = sys.stdin.read(1)) != "\n":
^
SyntaxError: invalid syntax

(^ 应该在 = 上)

有解决办法吗?

最佳答案

启动Python 3.8,并引入assignment expressions (PEP 572) (:= 运算符),现在可以将表达式值(此处为 sys.stdin.read(1))捕获为变量,以便在正文中使用它while:

while (i := sys.stdin.read(1)) != '\n':
do_smthg(i)

这个:

  • sys.stdin.read(1) 分配给变量 i
  • 比较 i\n
  • 如果条件成立,进入while正文,其中i可以使用

关于python - Python While 循环中的赋值条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7780998/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com