Pythonにおける変数は、データを格納するためのメモリ領域です。 変数はプログラム内で値を保持し、その値を後で変更または使用できるようにします。
Pythonの変数名には以下のルールがあります。
Pythonの変数は動的型付け言語であるため、変数の型は実行時に決定されます。 変数には整数、浮動小数点数、文字列、リスト、辞書、オブジェクトなど、 さまざまな型のデータを格納することができます。
# 整数型 (int)
x = 5
y = -10
print(x)
print(y)
# 浮動小数点数型 (decimal)
total = 2000.50
pi = 3.14
print(total)
print(pi)
#文字列型 (str)
name = "Taro" #ダブルクォーテーション
message = 'HelloWorld' #シングルコーテーション
new_line = '''1行目
2行目
3行目''' #トリプルコーテーション※改行を含める場合
print(name)
print(message)
print(new_line)
#ブール型 (bool)
is_true = True
is_false = False
print(is_true)
print(is_false)
#値が存在しない (null)
null_variable = None
print(null_variable)
5
-10
2000.5
3.14
Taro
HelloWorld
1行目
2行目
3行目
True
False
None
型の変換が自動的に行われる場合もあります。例えば、整数型の変数に浮動小数点数を代入すると、自動的に型変換が行われます。
# 整数型の変数に浮動小数点数を代入
integer_variable = 5 # 整数型
print("整数型変数:", integer_variable) # 5
float_variable = 3.14 # 浮動小数点数
integer_variable = float_variable # 自動的に型変換が行われる
print("浮動小数点数:", integer_variable)
整数型変数: 5
浮動小数点数: 3.14
リストは複数の要素をカンマ区切りで[]で囲んで定義します。 各要素の型は任意で定義可能です。
リストの要素へのアクセスは0から開始するインデックス指定と 開始、終了インデックスを指定するスライスとfor文を用いたイテレーションによるアクセスが可能です。
※イテレーション:シーケンス、コレクションの各要素に順番にアクセスするプロセスまたは操作を指します。
リストはミュータブルという要素を変更することが可能なオブジェクトです。
#リスト型 (list)
numbers = [1, 2, 3, 4, 5] #数値のみ
nams = ['Taro', 100, 'Hana'] #数値と文字が混在
print(numbers)
print(nams)
#インデックス
numbers[0] = 6 #変更可能
nams[1] = 'Jiro' #変更可能
print(numbers)
print(nams)
#スライス
print(numbers[0:3]) #先頭から先頭3番目前まで
print(nams[-2:-1]) #末尾2番目~末尾1番目前まで
#イテレーション
for num in numbers:
print(num)
#リスト型 (list)
[1, 2, 3, 4, 5]
['Taro', 100, 'Hana']
#インデックス
[6, 2, 3, 4, 5]
['Taro', 'Jiro', 'Hana']
#スライス
[6, 2, 3]
['Jiro']
#イテレーション
6
2
3
4
5
タプルも複数の要素をカンマ区切りで()で囲んで定義します。 各要素の型は任意で定義可能ですが、イミュータブルという要素を変更するできないオブジェクトです
以下はタプル内の要素を変更しようとしているため、TypeErrorが発生します
#タプル型 (tuple)
position = (3, 5)
print(position)
#インデックス
position[0] = 6 #変更不可 例外エラーが発生します
(3, 5)
Traceback (most recent call last):
File "/home/XX/python_project/sample.py", line 8, in <module>
position[0] = 6 #変更不能
~~~~~~~~^^^
TypeError: 'tuple' object does not support item assignment
タプル内の各要素の変更はできませんが、タプル変数への代入は可能です。
#タプル型 (tuple)
position = (3, 5)
print(position)
position = ('red', 'green', 'blue')
print(position)
(3, 5)
('red', 'green', 'blue')
タプルもリストのように参照は可能です
#インデックス
colors = ('red', 'green', 'blue')
print(colors[0])
#スライス
print(colors[0:2]) #先頭から先頭3番目前まで
print(colors[-2:-1]) #末尾2番目~末尾1番目前まで
#イテレーション
for color in colors:
print(color)
red
('red', 'green')
('green',)
red
green
blue
辞書型は一意のキー(Key)と値(Value)のペアを複数持つことができるオブジェクトで キーと値を「:」でつなげて「{}」で囲み定義します。
キーと値を複数定義する場合は各要素をカンマで区切ります。
#辞書型 (dict)
person = {'name': 'Taro', 'age': 20, 'city': 'Tokyo'}
print(person)
{'name': 'Taro', 'age': 20, 'city': 'Tokyo'}
キーの重複があっても最後の値がキーに関連付けられます。
duplicate_dict = {'key1': 1, 'key2': 2, 'key1': 3}
print(duplicate_dict)
{'key1': 3, 'key2': 2}
辞書型の要素へのアクセスをする方法について
color_dict = {'red': 5, 'green': 3, 'orange': 8}
# 'green'というキーに関連する値を取得する
green_num = color_dict['green']
print(green_num)
3
color_dict = {'red': 5, 'green': 3, 'orange': 8}
# 'green'というキーに関連する値を取得する
green_num = color_dict.get('green')
print(green_num)
# 存在しないキーの場合、デフォルト値「0」を指定できる
green_num = color_dict.get('black', 0)
print(green_num)
3
0
color_dict = {'red': 5, 'green': 3, 'orange': 8}
# 'green'というキーに関連する値を取得する
green_num = color_dict.get('green')
print(green_num)
# 存在しないキーの場合、デフォルト値「0」を指定できる
green_num = color_dict.get('black', 0)
print(green_num)
3
0
color_dict = {'red': 5, 'green': 3, 'orange': 8}
# すべてのキーを取得する
keys = color_dict.keys()
print(keys)
dict_keys(['red', 'green', 'orange'])
color_dict = {'red': 5, 'green': 3, 'orange': 8}
# すべての値を取得する
values = color_dict.values()
print(values)
dict_values([5, 3, 8])
color_dict = {'red': 5, 'green': 3, 'orange': 8}
# すべてのキーと値のペアを取得する
values = color_dict.items()
print(values)
dict_items([('red', 5), ('green', 3), ('orange', 8)])
要素取得時に値が無い場合に辞書に新しいキーとデフォルトの値を追加することができる setdefaultメソッドが利用可能です。
color_dict = {'red': 5, 'green': 3, 'orange': 8}
# 存在する場合
values = color_dict.setdefault('green',3)
print(values)
# 存在しない場合
values = color_dict.setdefault('black',11)
print(values)
print(color_dict)
3
11
{'red': 5, 'green': 3, 'orange': 8, 'black': 11}
辞書型の要素を追加、変更、削除する方法について
# 存在しない値を指定すると新たにキーと値のペアが追加される
color_dict = {'red': 5, 'green': 3, 'orange': 8}
color_dict['black'] = 11
print(color_dict)
{'red': 5, 'green': 3, 'orange': 8, 'black': 11}
color_dict = {'red': 5, 'green': 3, 'orange': 8}
print(color_dict)
# 別の辞書を使用して更新
color_dict.update({'black': 11, 'white': 12})
print(color_dict)
# 既存の辞書を使用して更新
color_dict.update({'red': 13})
print(color_dict)
{'red': 5, 'green': 3, 'orange': 8}
{'red': 5, 'green': 3, 'orange': 8, 'black': 11, 'white': 12}
{'red': 13, 'green': 3, 'orange': 8, 'black': 11, 'white': 12}
color_dict = {'red': 5, 'green': 3, 'orange': 8}
print(color_dict)
# キーワード指定
color_dict.update(black=11, white=12)
print(color_dict)
{'red': 5, 'green': 3, 'orange': 8}
{'red': 5, 'green': 3, 'orange': 8, 'black': 11, 'white': 12}
color_dict = {'red': 5, 'green': 3, 'orange': 8}
print(color_dict)
# コンストラクタを利用して更新
color_dict = dict(color_dict, black=11, white=12)
print(color_dict)
{'red': 5, 'green': 3, 'orange': 8}
{'red': 5, 'green': 3, 'orange': 8, 'black': 11, 'white': 12}
集合型 (セット)は、重複する要素を持たない順序がないコレクションです。
セットは中括弧 {} で定義して各要素はカンマで区切ります。
colors = {'red', 'green', 'orange'}
print(colors)
{'red', 'orange', 'green'}
colors = {'red', 'green', 'orange', 'green', 'green', 'black'}
print(colors)
{'red', 'orange', 'black', 'green'}
集合型(セット)はミュータブルなデータ型です。
要素を追加、削除、更新することができます。
colors = {'red', 'green', 'orange'}
print(colors)
#addメソッドで要素の追加
colors.add('yellow')
print(colors)
{'orange', 'red', 'green'}
{'orange', 'yellow', 'red', 'green'}
colors = {'red', 'green', 'orange'}
print(colors)
#update メソッドでセットに他のリストなどから要素を追加
colors.update(['yellow','white','black'])
print(colors)
{'orange', 'red', 'green'}
{'black', 'yellow', 'red', 'green', 'white', 'orange'}
#remove メソッドでセット要素を削除
colors = {'red', 'green', 'orange'}
print(colors)
colors.remove('orange')
print(colors)
{'green', 'red', 'orange'}
{'green', 'red'}
Pythonの関数は「def」をキーワードに使用して定義します。
Pythonの関数名には以下のルールがあります。
関数は0個以上の引数を受け取ることができ括弧内に指定して関数内で利用します
def 関数名(引数1, 引数2, ...):
# 関数の本体
処理
return 戻り値
def multiply(a, b):
"""二つの数を掛け合わせる関数"""
result = a * b
return result
# 関数を使って掛け算を行う例
num1 = 6
num2 = 8
result = multiply(num1, num2)
print(f"{num1} × {num2} = {result}")
6 × 8 = 48
デフォルト値を持つ引数を指定する方法があります。 デフォルト引数はデフォルト値がある引数の後に定義します。
def multiply(a, b=10):
"""二つの数を掛け合わせる関数"""
result = a * b
return result
# 関数を使って掛け算を行う例
num1 = 6
result = multiply(num1)
print(f"{num1} × 10(デフォルト値) = {result}")
6 × 10(デフォルト値) = 60
可変長の引数を渡す方法があります。 引数名の前に「*」を付けます。※引数名はargsでなくても可
可変長の引数は通常の引数の後に定義します。
def multiply(*args):
"""複数の数を掛け合わせる関数"""
result = 1 # 掛算初期値を1に設定
for num in args:
result *= num # 各引数を順番に掛けていく
return result
# 関数を使って掛け算を行う例
result1 = multiply(1, 2, 3)
result2 = multiply(2, 4, 8, 16)
print(f"result1: {result1}")
print(f"result2: {result2}")
result1: 6
result2: 1024
可変長の辞書型の引数を渡す方法があります。 引数名の前に「**」を付けます。
def dic_info(**kwargs):
"""キーワード引数を表示する関数"""
for key, value in kwargs.items():
print(f"{key}: {value}")
# 関数を呼び出して引数を表示
dic_info(name="Taro", age=20, city="tokyo")
name: Taro
age: 20
city: tokyo
ラムダ関数(lambda function)は、Pythonにおいて匿名で関数を定義するための手法です。
ラムダ関数は通常1行の式で定義され「lambda」キーワードで定義されます。
lambda 引数1, 引数2, ...: 式
multiply = lambda a, b: a * b
result = multiply(3, 4)
print(result)
12
高階関数とは関数を引数として取得したり戻り値で返します
# 引数となる関数
def multiply_two(a, b):
return a * b
def multiply_three(a, b,c):
return a * b * c
# 引数を受け取る関数
def execute_function(func, *args):
print(func(*args))
execute_function(multiply_two, 3, 4)
execute_function(multiply_three, 3, 4, 5)
12
60
関数内に関数を定義(※関数内関数)して戻り値で返す例
# 関数の処理結果を戻り値として返す関数
def outer_multiplier(a,b):
def inner_multiplier(x,y): #関数内関数の引数x,y
return x * y
return inner_multiplier(a,b) #関数内関数の処理結果を返す
# 使用例
print(outer_multiplier(3,4)) # 3 * 4 = 12
print(outer_multiplier(4,5)) # 4 * 5 = 20
12
20
関数内関数とは異なるクロージャーについて
クロージャーは、他の関数の中に定義され、かつ外部の関数から変数を参照する関数です。
関数内関数と異なり引数を受け取り、関数内関数の処理結果を返します。
クロージャーは外部の関数の引数を直接利用して、関数オブジェクトを返します。
# 関数を戻り値として返す関数
def outer_multiplier(a,b):
def inner_multiplier(): #直接外部関数の引数を利用
return a * b
return inner_multiplier #関数オブジェクトを返す
# 使用例
method_obj1 = outer_multiplier(3,4)
method_obj2 = outer_multiplier(4,5)
print(method_obj1) # 関数オブジェクト <function outer_multiplier.<locals>.inner_multiplier at 0x...>
print(method_obj2) # 関数オブジェクト <function outer_multiplier.<locals>.inner_multiplier at 0x...>
print(method_obj1()) # 関数処理結果 12
print(method_obj2()) # 関数処理結果 20
<function outer_multiplier.<locals>.inner_multiplier at 0x...>
<function outer_multiplier.<locals>.inner_multiplier at 0x...>
12
20
Pythonの制御構文には条件分岐やループなどいくつかの構文があります。
条件分岐
if 条件:
# 条件がTrueの場合に実行されるコード
elif 別の条件:
# 別の条件がTrueの場合に実行されるコード
else:
# どの条件も満たされない場合に実行されるコード
x = None
if x:
print('真')
elif x == False:
print('偽')
else:
print('無')
無
ループ(繰り返し)
for文はイテラブル(リスト、タプル、文字列など)の各要素に反復処理を行います。
※イテラブルは各要素に順番にアクセスすることができるデータ構造を表します。
for 要素 in イテラブル:
# イテラブルの各要素に対して繰り返し実行されるコード
colors = ['red', 'green', 'blue']
for color in colors:
print(color)
red
green
blue
while文
while文は指定した条件が真の間反復処理を行います。
while 条件:
# 条件がTrueの間、繰り返し実行されるコード
count = 0
while count < 3:
print(count)
count += 1
0
1
2
例外処理
try-except文は例外が発生する可能性のあるコードを囲み、 except節で例外のハンドリングを行います。
try:
# 例外が発生する可能性のあるコード
except 例外の種類 as 変数:
# 例外が発生した場合に実行されるコード
else:
# 例外が発生しなかった場合に実行されるコード
finally:
# 最後に必ずに実行されるコード
try:
result = 1 / 0 #ゼロ除算
except ZeroDivisionError as e:
print(f"エラー内容: {e}")
else:
print(f"正常結果: {result}")
finally:
print("最終処理1")
try:
result = 1 / 10 #除算
except ZeroDivisionError as e:
print(f"エラー内容: {e}")
else:
print(f"正常結果: {result}")
finally:
print("最終処理2")
エラー内容: division by zero
最終処理1
正常結果: 0.1
最終処理2
内包表記
内包表記はシーケンス(リスト、セット、辞書など)を作成するための簡潔な構文です
リスト内包表記 [式 for 要素 in イテラブル]という形式
multiply = []
# 通常のリスト処理
for x in range(5):
multiply.append(x*x)
print(multiply)
# リスト内包表記
multiply = [x*x for x in range(5)]
print(multiply)
[0, 1, 4, 9, 16]
[0, 1, 4, 9, 16]
辞書内包表記 {key: value for 要素 in イテラブル}という形式
multiply_dic = {}
# 通常の辞書処理
for x in range(5):
multiply_dic[x] = x * x
print(multiply_dic)
# 辞書内包表記
multiply_dic = {x: x * x for x in range(5)}
print(multiply_dic)
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
セット内包表記 {式 for 要素 in イテラブル}という形式
unique_multiply = set()
# 通常の方法
for x in range(5):
unique_multiply.add(x*x)
print(unique_multiply)
# セット内包表記
unique_multiply = {x*x for x in range(5)}
print(unique_multiply)
{0, 1, 4, 9, 16}
{0, 1, 4, 9, 16}
breakとcontinue文
break文はループを途中で終了させます。
for i in range(10):
if i == 5:
break
print(i)
0
1
2
3
4
continue文はループの途中で処理をスキップしてイテレーションを次に進めます。
for i in range(10):
if i == 5:
contine
print(i)
0
1
2
3
4
6
7
8
9
pass文は何もしないステートメントです。 未実装などで何もする必要がない場合などに構文要件を満たすために存在します。
def todo_function():
pass
ジェネレータ(Generators)は、イテレータを作成するための特殊な関数です。
※イテレータはイテレーションを実現するオブジェクトです。
通常の関数は一度にすべての結果を生成しますが、ジェネレータは必要な時点で一度に一つずつ結果を生成します。
ジェネレータはyieldキーワードを使用して値を生成します。
# 色を返すジェネレータ関数
def color_generator():
yield 'black'
yield 'red'
yield 'yellow'
#ジェネレータオブジェクトを生成
gen = color_generator()
# ジェネレータを使用したイテレーション
for value in gen:
print(value)
black
red
yellow
Pythonのデコレータは関数やクラスに対して機能を追加したり修飾したりするための機能です。
既存の関数やクラスを変更することでコードの再利用やメンテナンス性の向上などを目的にします。
デコレータは@デコレータ名のように関数やクラスの上に定義を行います。
#クロージャー関数を定義する
def sample_decorator(func):
def wrapper():
print("start wrapper!!")
func()
print("end wrapper!!")
return wrapper
@sample_decorator #デコレータしたい関数の直前に@関数名を入れる
def sample_func():
print("sample!!")
#デコレータが適用されたsample_funcを呼出すとデコレータ内のwrapper関数が呼び出される
sample_func()
start wrapper!!
sample!!
end wrapper!!
デコレータを使用しない場合は以下の様に呼出しを行う必要があります。
#クロージャー関数を定義する
def sample_decorator(func):
def wrapper():
print("start wrapper!!")
func()
print("end wrapper!!")
return wrapper
def sample_func():
print("sample!!")
sample = sample_decorator(sample_func)
sample()
start wrapper!!
sample!!
end wrapper!!
今回は、Pythonの文法などの基礎について記載しました。
引き続きPythonの基礎以外に実際の利用が想定される内容などについて追記していきます。
本コンテンツはプロモーションが含まれます。