Pythonの基本
この記事ではPythonの基本について説明します。
YouTube Video
"Hello World!"の実行
1print("Hello World!")
Pythonにおける変数
Pythonにおける変数は、データや情報をプログラム内で保管し利用するための名前付きの記憶領域です。変数にはさまざまなデータ型を代入することができ、必要に応じて変更することもできます。以下に、Pythonの変数の基本的な使い方を示すサンプルコードをいくつか紹介します。
1# 1. Assigning values to variables
2# Integer type variable
3age = 25
4print("Age:", age) # Output: Age: 25
5
6# Floating-point type variable
7height = 175.5
8print("Height:", height, "cm") # Output: Height: 175.5 cm
9
10# String type variable
11name = "John"
12print("Name:", name) # Output: Name: John
13
14# Boolean type variable
15is_student = True
16print("Are you a student?", is_student) # Output: Are you a student? True
17
18# 2. Assigning values to multiple variables simultaneously
19# You can assign multiple variables at once
20x, y, z = 5, 10, 15
21print("x =", x, ", y =", y, ", z =", z) # Output: x = 5 , y = 10 , z = 15
22
23# 3. Updating the value of a variable
24# The value of a variable can be updated by reassignment
25age = 26
26print("Updated age:", age) # Output: Updated age: 26
27
28# 4. Updating multiple variables at once
29# Example of swapping values between variables
30a, b = 1, 2
31a, b = b, a
32print("a =", a, ", b =", b) # Output: a = 2 , b = 1
33
34# 5. Type conversion
35# Type conversion allows operations between different types
36count = "5" # String "5"
37count = int(count) # Convert to integer type
38print("Handling count as an integer:", count * 2) # Output: Handling count as an integer: 10
39
40# Conversion to floating-point number
41pi_approx = "3.14"
42pi_approx = float(pi_approx)
43print("Approximation of pi:", pi_approx) # Output: Approximation of pi: 3.14
このように、Pythonでは変数を柔軟に扱うことができます。変数は型を指定せずに使用でき、必要に応じて再代入で変更することも可能です。また、型変換によって異なる型を互いに変えることも容易です。
Pythonにおけるデータ型
Pythonにはいくつかの基本的なデータ型があります。以下にそれぞれの説明とサンプルコードを含めて紹介します。
整数型 (Integer)
整数型は、小数点を持たない整数の数値を扱うためのデータ型です。
1# Example of integer type
2x = 10
3print(x) # Output: 10
4print(type(x)) # Output: <class 'int'>
浮動小数点数型 (Float)
浮動小数点数型は、小数点を含む数値を扱うデータ型です。
1# Floating Point Number Example
2y = 3.14
3print(y) # Output: 3.14
4print(type(y)) # Output: float
文字列型 (String)
文字列型は、文字の列を表すデータ型です。文字列はシングルクォート '
またはダブルクォート "
で囲むことができます。
1# Example of String
2s = "Hello, World!"
3print(s) # Output: Hello, World!
4print(type(s)) # Output: <class 'str'>
真偽値型 (Boolean)
真偽値型は、真 (True
) または偽 (False
) の2つの値を取ります。
1# Example of Boolean
2b = True
3print(b) # Output: True
4print(type(b)) # Output: <class 'bool'>
リスト型 (List)
リスト型は、複数の要素を格納できる可変長のシーケンスで、リスト内の要素のデータ型は異なっていても構いません。
1# Example of List
2lst = [1, 2, 3, "four", 5.0]
3print(lst) # Output: [1, 2, 3, 'four', 5.0]
4print(type(lst)) # Output: <class 'list'>
タプル型 (Tuple)
タプル型は、複数の要素を格納できるシーケンスで、一度作成するとその内容を変更できません。
1# Example of Tuple
2tup = (1, "two", 3.0)
3print(tup) # Output: (1, 'two', 3.0)
4print(type(tup)) # Output: <class 'tuple'>
辞書型 (Dictionary)
辞書型は、キーと値のペアを保持するコレクションです。キーはユニークでなければなりません。
1# Example of Dictionary
2dct = {"one": 1, "two": 2, "three": 3}
3print(dct) # Output: {'one': 1, 'two': 2, 'three': 3}
4print(type(dct)) # Output: <class 'dict'>
セット型 (Set)
セット型は、ユニークな要素を保持するためのコレクションです。同じ値を複数含むことはできません。
1# Example of Set
2st = {1, 2, 2, 3}
3print(st) # Output: {1, 2, 3}
4print(type(st)) # Output: <class 'set'>
これらのデータ型はPythonでデータを扱う際によく使用される基本的な型です。必要に応じて使い分けることで、プログラムの様々な要件を満たすことができます。
Python概要
Pythonは、1991年にグイド・ヴァンロッサムによって開発された高水準のプログラミング言語です。その設計哲学は、「シンプル」「明快」「読みやすさ」に重点を置いており、その結果としてコードが直感的で、書きやすく読みやすいという特長があります。以下にPythonの主要な特徴を概要として説明します。
-
読みやすく、シンプル:
- コードの構造が明確で、自然言語に近い表現が使われるため、初心者にとっても学びやすい言語です。
- インデントによってブロックを定義するため、コードが自動的に整形され、可読性が高まります。
-
豊富なライブラリとフレームワーク:
- 標準ライブラリが豊富で、多くのタスクを簡単に実行することができます。
- 数値計算(NumPy)、データ解析(Pandas)、機械学習(scikit-learn, TensorFlow)、Web開発(Django, Flask)など、さまざまな分野に特化したライブラリやフレームワークが充実しています。
-
多用途性:
- Pythonはスクリプト言語としても、フル機能のアプリケーション開発にも適しており、Webアプリケーション、デスクトップアプリケーション、科学計算、機械学習、データ分析、IoTなど、さまざまな用途に使用されています。
-
クロスプラットフォーム:
- プラットフォームに依存しないので、Windows、macOS、Linuxをはじめとする多くのオペレーティングシステムで実行可能です。
-
オープンソースとコミュニティ:
- Pythonはオープンソースプロジェクトであり、活発なコミュニティに支えられています。これにより、頻繁な更新やライブラリの開発、サポートが行われています。
-
動的型付けと自動メモリ管理:
- 動的型付けにより、変数の型宣言が不要で、開発が迅速に進められます。
- ガベージコレクションによる自動メモリ管理を行っており、メモリ管理が簡単です。
Pythonはこれらの特徴によって、教育、産業、学術領域を含む広範な分野で利用されています。
Pythonにおけるエスケープ文字
Pythonでは、エスケープ文字を使用して文字列内に特定の制御文字や特殊な意味を持つ文字を含めることができます。エスケープ文字は、通常の文字列に特定の意味を付加するための特殊な記号です。Pythonにおけるエスケープ文字について詳しく見ていきましょう。
エスケープ文字の基本
Pythonでは、バックスラッシュ (\
) を使用してエスケープ文字を定義します。エスケープ文字は、通常の文字列内で特定の動作を示します。たとえば、\n
は改行、\t
はタブスペースを意味します。
次のようにエスケープ文字を含む文字列を定義できます。
1# Example of escape characters
2print("Hello\nWorld") # A newline is inserted after "Hello"
3
4# Output:
5# Hello
6# World
主なエスケープ文字の一覧
Pythonで使用される主要なエスケープ文字は次の通りです。
\\
: バックスラッシュそのものを表します\'
: シングルクォートを文字列に含めます\"
: ダブルクォートを文字列に含めます\n
: 改行\t
: タブ\r
: キャリッジリターン\b
: バックスペース\f
: 改ページ\a
: 警告音(ベル)\v
: 垂直タブ\N{name}
: Unicodeデータベースの名前による文字\uXXXX
: 16ビットのUnicode文字(4桁の16進数で指定)\UXXXXXXXX
: 32ビットのUnicode文字(8桁の16進数で指定)\xXX
: 16進数で指定された文字
よく使われるエスケープ文字の例
エスケープ文字を使用する具体例をいくつか紹介します。
ダブルクォートとシングルクォート
文字列内にダブルクォートやシングルクォートを含めるには、エスケープ文字を使用します。
1# String containing double quotes
2quote = "He said, \"Python is amazing!\""
3print(quote)
4
5# String containing single quotes
6single_quote = 'It\'s a beautiful day!'
7print(single_quote)
8
9# Output:
10# He said, "Python is amazing!"
11# It's a beautiful day!
改行とタブ
改行やタブは、テキストを整形する際によく使われます。
1# Example using newline
2multiline_text = "First line\nSecond line"
3print(multiline_text)
4
5# Example using tab
6tabbed_text = "Column1\tColumn2\tColumn3"
7print(tabbed_text)
8
9# Output:
10# First line
11# Second line
12# Column1 Column2 Column3
Unicodeエスケープ文字
Pythonでは、Unicode文字を表すために \u
または \U
を使用します。特に非英語の文字を扱う際に便利です。
1# Example of Unicode escape
2japanese_text = "\u3053\u3093\u306B\u3061\u306F" # Hello in Japanese
3print(japanese_text)
4# Output:
5# こんにちは(Hello in Japanese)
特殊なエスケープ文字の注意点
エスケープ文字を使う際には、いくつかの注意点があります。
- そのままの文字列: バックスラッシュを含む文字列をそのまま表示したい場合は、文字列の前に
r
を付けます。
1raw_string = r"C:\Users\name\Documents"
2print(raw_string)
3# Output:
4# C:\Users\name\Documents
ここでは、バックスラッシュがエスケープ文字として解釈されず、そのまま出力されます。
- Unicodeの使用: Unicodeエスケープ文字を使用する際は、指定する16進数が正確であることを確認してください。誤った指定をすると、文字が正しく表示されません。
バックスラッシュのエスケープ
バックスラッシュ自体を文字列内に含めたい場合は、二重のバックスラッシュを使用します。
1# Example containing backslash
2path = "C:\\Program Files\\Python"
3print(path)
4# Output:
5# C:\Program Files\Python
応用例: 複雑な文字列のフォーマット
エスケープ文字を組み合わせて、複雑な文字列をフォーマットすることも可能です。
1# Example of formatting a message
2message = "Dear User,\n\n\tThank you for your inquiry.\n\tWe will get back to you shortly.\n\nBest Regards,\nCustomer Support"
3print(message)
4# Output:
5# Dear User,
6#
7# Thank you for your inquiry.
8# We will get back to you shortly.
9#
10# Best Regards,
11# Customer Support
まとめ
Pythonのエスケープ文字は、文字列内に特定の制御文字や特殊文字を含めるための強力なツールです。使い方を理解し、必要に応じて適切に活用することで、より柔軟な文字列処理が可能になります。
Pythonのバージョン
Pythonのバージョンについて、主要なリリースとその特徴を簡潔にみてみましょう。
- Python 1.0(1994年)
1# Sample code that works in Python 1.0
2def greet(name):
3 print "Hello, " + name # print was a statement
4
5greet("World")
最初の正式リリース。Pythonの基本構文と標準ライブラリが確立されました。
- Python 2.0(2000年)
1# Sample code that works in Python 2.0
2
3# List comprehension
4squares = [x * x for x in range(5)]
5print squares
6
7# Unicode string (u"...")
8greet = u"Hello"
9print greet
リスト内包表記、完全なガベージコレクションの導入、Unicodeサポートの開始など、重要な機能が追加されました。Python 2は長期間使われましたが、2020年にサポートが終了しました。
- Python 3.0(2008年)
1# Sample code that works in Python 3.0
2
3# print is now a function
4print("Hello, world!")
5
6# Unicode text is handled natively
7message = "Hello"
8print(message)
後方互換性がない大規模な改善版。print
が関数化され、Unicode
が標準の文字列型になり、整数型の統一など、Pythonの一貫性と使いやすさを大幅に向上させました。Python 3は現在の主流バージョンです。
- Python 3.5(2015年)
1# Sample code that works in Python 3.5
2import asyncio
3
4async def say_hello():
5 await asyncio.sleep(1)
6 print("Hello, async world!")
7
8asyncio.run(say_hello())
async
/await
構文が導入され、非同期プログラミングがよりシンプルに記述できるようになりました。
- Python 3.6(2016年)
1# Sample code that works in Python 3.6
2
3name = "Alice"
4age = 30
5print(f"{name} is {age} years old.") # f-string makes formatting simple
**Formatted String Literals(f-strings)**が追加され、文字列フォーマットが簡便になりました。また、型ヒントも拡張されました。
- Python 3.7(2018年)
1# Sample code that works in Python 3.7
2
3from dataclasses import dataclass
4
5@dataclass
6class Person:
7 name: str
8 age: int
9
10p = Person("Bob", 25)
11print(p)
**データクラス(dataclasses)**が導入され、構造体のようなクラスの定義が容易になりました。また、async
/await
のサポートが強化されました。
- Python 3.8(2019年)
1# Sample code that works in Python 3.8
2
3# Assignment inside an expression
4if (n := len("hello")) > 3:
5 print(f"Length is {n}")
**Walrus演算子(:=)**が追加され、代入式が使えるようになりました。positional-only parameters
も導入され、関数の引数に関する柔軟性が向上しました。
- Python 3.9(2020年)
1# Sample code that works in Python 3.9
2
3a = {"x": 1}
4b = {"y": 2}
5c = a | b # merge two dicts
6print(c) # {'x': 1, 'y': 2}
型ヒントの改善や、リストと辞書の結合用の演算子(|
)が追加されました。また、標準ライブラリが整理されました。
- Python 3.10(2021年)
1# Sample code that works in Python 3.10
2
3def handle(value):
4 match value:
5 case 1:
6 return "One"
7 case 2:
8 return "Two"
9 case _:
10 return "Other"
11
12print(handle(2))
パターンマッチングが追加され、条件分岐をより強力に記述できるようになりました。エラーメッセージの改善や、型システムのさらなる強化も行われました。
- Python 3.11(2022年)
1# Sample code that works in Python 3.11
2
3# Improved performance (up to 25% faster in general)
4# More informative error messages
5try:
6 eval("1/0")
7except ZeroDivisionError as e:
8 print(f"Caught an error: {e}")
**パフォーマンスの大幅な改善**があり、以前のバージョンに比べて速度が向上しました。また、例外処理や型チェックに関する改良が行われました。
- Python 3.12(2023年)
1# Sample code that works in Python 3.12
2
3# Automatically shows exception chains with detailed traceback
4def f():
5 raise ValueError("Something went wrong")
6
7def g():
8 try:
9 f()
10 except Exception:
11 raise RuntimeError("Higher level error") # Automatically chained
12
13try:
14 g()
15except Exception as e:
16 import traceback
17 traceback.print_exception(type(e), e, e.__traceback__)
エラーメッセージのさらなる改善や、パフォーマンスの向上が行われています。また、例外のチェーンが自動的に表示されるようになり、より詳細なデバッグが可能になりました。新しい構文機能や標準ライブラリの強化も加わり、開発者の生産性が向上しています。
- Python 3.13(2024年)
1# Sample code that works in Python 3.13
2
3# Using the new 'except*' syntax for handling multiple exceptions in parallel
4import asyncio
5
6async def raise_errors():
7 raise ExceptionGroup("Multiple errors", [
8 ValueError("Invalid value"),
9 TypeError("Wrong type"),
10 ])
11
12async def main():
13 try:
14 await raise_errors()
15 except* ValueError as e:
16 print("Caught ValueError(s):", e.exceptions)
17 except* TypeError as e:
18 print("Caught TypeError(s):", e.exceptions)
19
20asyncio.run(main())
Python 3.13では、ExceptionGroup
とexcept*
構文がさらに洗練され、非同期処理における複数の例外を並列的にキャッチできるようになりました。これにより、並列処理やasyncio
を活用するアプリケーションのデバッグやエラーハンドリングがより直感的かつ強力になっています。その他にも、型ヒントの改善や標準ライブラリの更新により、保守性と記述性が向上しています。
Python バージョン3は継続的に進化しており、最新のバージョンではパフォーマンス、型システムの改善、新機能の追加が行われています。
YouTubeチャンネルでは、Visual Studio Codeを用いて上記の記事を見ながら確認できます。 ぜひYouTubeチャンネルもご覧ください。