Python学習チャンネル by PyQ

Pythonのオンライン学習プラットフォームPyQのオフィシャルブログです

【Pythonお悩み解決】SyntaxError: cannot assign to expression here. Maybe you meant '==' instead of '='?とは何ですか?

こんにちは、PyQサポートです。

今回は SyntaxError: cannot assign to expression here. Maybe you meant '==' instead of '='? というエラーの意味と、その解消方法を解説します。

質問:SyntaxError: cannot assign to expression here. Maybe you meant '==' instead of '='? というエラーはどういうものですか?

SyntaxError: cannot assign to expression here. Maybe you meant '==' instead of '='? というエラーが出ました。どのように修正したらよいでしょうか?

入力した内容(コード)

def get_price():
    book-price = 1000
    return book-price


price = get_price()
print(price) 

出たエラー(実行結果)

Python 3.10 で実行した結果

  File "/Users/pyq/scripts/assign.py", line 2
    book-price = 1000
    ^^^^^^^^^^
SyntaxError: cannot assign to expression here. Maybe you meant '==' instead of '='? 

回答 変数名に-が使われているためです

まずはエラーメッセージを確認してみましょう。

SyntaxError: cannot assign to expression here. Maybe you meant '==' instead of '='?

SyntaxErrorとあるので、文法的に間違いがあるということです。

次に内容を確認すると、cannot assign to expression here.とあり、これは「ここで式(expression)に代入(assign)できない」という意味です。

さらにMaybe you meant '==' instead of '='?とあり、「=でなく==では?」と提案してくれています。

なぜこのようなエラーになったのか解説します。

-は演算子として解釈される

このプログラムでは変数名にbook-priceを使っています。

しかし、Pythonでは-を変数名や関数名の一部として使用することはできません。
-を使うと引き算の演算子として扱われるためです。

そのため、book-price = 1000は以下のように解釈されてしまいます。

book - price = 1000

book - priceは引き算の式(expression)です。そのため、代入(assign)はできません。

「代入」ではなく以下のような「比較」であれば可能なので、エラーメッセージにて「=でなく==では?」と提案されたのです。

# 比較は可能
book - price == 1000

単語の区切りには_を使う

今回のように複数の単語を組み合わせた変数名を使いたい場合、各単語の区切りには_を使いましょう

今回であれば、以下のようにbook-priceではなくbook_priceとすれば、エラーは解消します。

def get_price():
    book_price = 1000
    return book_price


price = get_price()
print(price) 

なお、Pythonのコーディング規約であるPEP8にも「変数名は小文字のみで、単語の区切りは_を使う」とあります。

また、Pythonの変数名に使える文字については、こちらをご参照ください。

Python 3.9以前のエラーメッセージ

余談ですが、Python 3.9以前では以下のようなエラーメッセージです。

  File "/Users/pyq/scripts/assign.py", line 2
    book-price = 1000
    ^
SyntaxError: cannot assign to operator

Python 3.9以前はMaybe you meant '==' instead of '='?がありません。
Python 3.10でエラーメッセージが改善され、より親切な内容になったことがわかります。

まとめ

今回のポイントは以下のとおりです

  • -は演算子として解釈されるので、変数名には使えない
  • 複数の単語を組み合わせた変数名を使用するときは、単語の区切りに_を使う
Copyright ©2017- BeProud Inc. All rights reserved.