【Python3.6】Pythonにはインクリメント・デクリメント演算子がない

公開日時:2018年03月21日 / 最終更新日時:2019年02月11日

Python にはインクリメント・デクリメント演算子がありません。

(i++ とか i-- とか ++i とか --i とか)

そのため「num = num + 1」「num += 1」と記述します。

 

 

Pythonでのインクリメントの書き方

Pythonでは以下のように記述します。

 

■プログラム例

[test@SAKURA_VPS test]$ cat test.py 
#coding:utf-8 
 
num = 0 
 
while num < 10: 
    print('num : ', num) 
    # 後でインクリメントする 
    num += 1 
 
[test@SAKURA_VPS test]$

 

 

■プログラム実行結果

[test@SAKURA_VPS test]$ python3.6 test.py 
num :  0 
num :  1 
num :  2 
num :  3 
num :  4 
num :  5 
num :  6 
num :  7 
num :  8 
num :  9 
[test@SAKURA_VPS test]$

 

 

個人的には

が同じ処理なので初見分かりづらいです。

num =+1 の方が分かりやすそうですが、却って混乱するのかもしれません。

 

なぜPythonにはインクリメント演算子がないのか?

以下の Python に関する質問に答えが書いてありました。

※2006年1月と10年以上前の質問と回答です。

 

Why is there no post-pre increment operator in python

https://mail.python.org/pipermail/python-list/2006-January/374573.html

 

riteshtijoriwala at gmail.com wrote:
> Anyone has any idea on why is there no post/pre increment operators in python ?

Short answer: Because Guido didn't like them.

Longer answer: Because they encourage people to write cryptic one-liners.

There really isn't anything you can't write with them that you couldn't write just as well without them.

It just takes another line or two of code.

The end result may be a little longer, but it's almost always easier to understand.

> Although the statement:
> ++j
> works but does nothing

Well, it works in the sense that it's not a syntax error, but it doesn't quite do nothing.

It applies the unary + operator to the value of j, then does it again, then throws away the result.

Granted, that's probably not what you expected, and probably not very useful, but it's not quite "nothing".

 

gmail.com の riteshtijoriwala が書いた:

>Python にポスト/プリインクリメント演算子がないのはどういった考えでしょうか?

短い答え:

Guidoは好きではなかったので。

※Guido は、Googleで開発を担当した Python の作者である Guido van Rossum 氏のことです。

 

長い答え:

ポスト/プリ インクリメント演算子があると、みんなが難解なワンライナーのプログラムを書かせることになるからです。

Python ではポスト/プリ インクリメント演算子は書くことができなくて、そもそもありません。

だからそれによりもう1行か2行のコードを書くことになります。

その結果、最終的にはコードが少し長くなるかもしれませんが、ほとんどの場合、コードは理解しやすくなります。

 

>声明:
> ++ j
>は動作しますが何もしません

 

++j は、構文エラーではありませんが、何もしません。

単項+演算子をjの値に適用してから、再度実行して結果を破棄します。

確かに、それはおそらく期待したものではなく、あまり有用ではないかもしれませんが、それはまったく「何もしない」訳ではありません。

 

 

 

Posted by 100%レンタルサーバーを使いこなすサイト管理人

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

AlphaOmega Captcha Medica  –  What Do You See?
     
 

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください

Secured By miniOrange