5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[python]の:=について(セイウチ演算子)

Posted at

はじめに

pythonのコードで:=という見慣れない演算子を見かけたので、端的に備忘録として残します。

:=の正体

これはセイウチ演算子と呼ばれていて、左辺に右辺の値を割り当てるという意味を持つ数学の記号のようです。

pythonではどのように使うのかというと、主に、条件式で代入処理を行うことができます。
例を示します。

n に値を代入して、それを比較したいと思います。

# これはsyntaxエラーを出します
if n = int(input()) > 3:
    print(f'{n} > 3')
else:
    print(f'{n} <= 3')

pythonでは条件式内で通常の代入はできないようです。
そこで:=を利用することで、これを実現します。

if (n := int(input())) > 3:
    print(f'{n} > 3')
else:
    print(f'{n} <= 3')

こうすると、nに入力を受け取り、それが3より大きいかを比較することができます。

おまけ

C言語でいうとこんな感じのイメージになります。
これは条件式中でpに対する代入が行われ、値が評価されますね。

#include <stdio.h>
int main()
{
    char str[128];
    char *p;
    while ((p = fgets(str, 128, stdin)) != NULL)
        puts(p);
    return 0;
}
5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?