Python 代入式

PythonPythonBeginner
今すぐ練習

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

はじめに

この実験では、「ウオルサス演算子」(:=) としても知られる Python の代入式について学びます。この演算子は Python 3.8 で導入され、式の一部として変数に値を代入することができます。コードの最適化、冗長な計算の回避、複雑な式の単純化に特に役立ちます。

この実験が終わるとき、あなたは Python プログラムで代入式を理解して適用できるようになるはずです。簡単な例から始めて、徐々により複雑な例に進みます。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/ControlFlowGroup(["Control Flow"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/PythonStandardLibraryGroup(["Python Standard Library"]) python/BasicConceptsGroup -.-> python/variables_data_types("Variables and Data Types") python/BasicConceptsGroup -.-> python/numeric_types("Numeric Types") python/ControlFlowGroup -.-> python/conditional_statements("Conditional Statements") python/ControlFlowGroup -.-> python/while_loops("While Loops") python/ControlFlowGroup -.-> python/list_comprehensions("List Comprehensions") python/FunctionsGroup -.-> python/function_definition("Function Definition") python/FunctionsGroup -.-> python/scope("Scope") python/PythonStandardLibraryGroup -.-> python/math_random("Math and Random") subgraph Lab Skills python/variables_data_types -.-> lab-5002{{"Python 代入式"}} python/numeric_types -.-> lab-5002{{"Python 代入式"}} python/conditional_statements -.-> lab-5002{{"Python 代入式"}} python/while_loops -.-> lab-5002{{"Python 代入式"}} python/list_comprehensions -.-> lab-5002{{"Python 代入式"}} python/function_definition -.-> lab-5002{{"Python 代入式"}} python/scope -.-> lab-5002{{"Python 代入式"}} python/math_random -.-> lab-5002{{"Python 代入式"}} end

単純な代入式

このステップでは、代入式の基本構文を理解するために簡単な例から始めます。

Python シェルを開く

ターミナルに次のコマンドを入力して Python シェルを開きます。

python3

単純なテスト

簡単な例から始めましょう。

## 代入式の基本例
n = 5
result = (squared := n * n)
print(squared, result)

出力:

25 25

ここでは、丸括弧内のウオルサス演算子 := を使って n * n の結果を変数 squared に代入します。次に、squared の値を変数 result に代入します。最後に、squaredresult の値を表示します。

条件文における代入式の使用

このステップでは、条件文内での代入式の使い方を調べます。

## 条件文における代入式の使用
input_str = "Hello, world!"
if (length := len(input_str)) > 10:
    print(f"The string has {length} characters, which is more than 10.")
else:
    print(f"The string has {length} characters, which is less than or equal to 10.")

出力:

The string has 13 characters, which is more than 10.

ここでは、input_str の長さを計算し、if 文の条件内でウオルサス演算子を使って変数 length に代入しています。これにより、条件分岐の両方のブランチで length の値を使用できるようになります。

ループにおける代入式の使用

次に、ループで代入式をどのように使うか見てみましょう。

## ループにおける代入式の使用
numbers = [1, 2, 3, 4, 5]
while (n := numbers.pop()) > 2:
    print(f"Popped {n}, which is greater than 2.")
print(f"Popped {n}, which is less than or equal to 2.")

出力:

Popped 5, which is greater than 2.
Popped 4, which is greater than 2.
Popped 3, which is greater than 2.
Popped 2, which is less than or equal to 2

この例では、while ループの条件内でウオルサス演算子を使って、numbers リストから要素を取り出して変数 n に代入しています。2 以下の要素が取り出されるまでループが続きます。

リスト内包表記における代入式の使用

最後に、リスト内包表記で代入式を使う方法を調べましょう。

## リスト内包表記における代入式の使用
from math import sqrt

numbers = [1, 4, 9, 16, 25]
roots = [int(root) for n in numbers if (root := sqrt(n)) == int(root)]
print(roots)

出力:

[1, 2, 3, 4, 5]

この例では、リスト内包表記の中でウオルサス演算子を使って、numbers の各数値の平方根を計算し、それが整数であるかどうかを確認します。もし整数であれば、整数の平方根を roots リストに追加します。

まとめ

この実験では、Python の代入式(ウオルサス演算子)を段階的な一連の例を通じて調べました。条件文、ループ、およびリスト内包表記における基本構文と使い方について説明しました。これまでに、Python コードで代入式をどのように使って複雑な式を最適化し、単純化するかを十分に理解しているはずです。

代入式を賢く使ってコードをより読みやすく効率的にするようにしてください。どんなプログラミング機能も、過度に使うと保守性の低いコードにつながる可能性があるので、過度にまたは不適切に使わないようにすることが重要です。

さまざまなシナリオでウオルサス演算子を練習し、実験して Python のプログラミングスキルを向上させましょう。ご成功をお祈りします。楽しいコーディングをお過ごしください!