今回の記事は備忘録としてあとで参照する目的で、Pythonの基礎事項をリストアップしておきます。
出力の操作:hello, world!
print関数
print('hello, world')
変数
text = 'hello, world' print(text)
文字の置換
text = 'hello, world' text = text.replace('l', 'L') print(text)
変数の型と演算
変数の型を確認する
a = '1' type(a)
b = 1 type(b)
c = 1. type(c)
変数の型を変える
a = '1' str_a = str(a) type(str_a)
b = 1 int_b = int(b) type(int_b)
b = 1 float_b = float(b) type(float_b)
変数の型を変える・その2
b = 1 print('bの値は{}です'.format(b))
文字を結合する
text1 = 'py' text2 = 'thon' text1 + text2
数値演算を施す
a = 3 b = 2 [a+b, a-b, a*b, a/b] #加減乗除
a**b #累乗
基本的な構文
if
a = 3 b = 2 if a >= b: print(a - b)
この場合、条件が不成立だった場合には何の処理もされません。
if a <= b: print(b - a)
これに対して、不成立の場合の処理を与えられるのが、次のif-else文です。
if-else
a = 3 b = 1 if a <= b: print(b - a) else: print(a - b)
if-elif-else
a = 3 b = 3 if a < b: print(b - a) elif a > b: print(a - b) else: print('identical')
for
for n in range(3): print('Hi!')
while
n = 1 while( n <= 5 ): print('Hi!') n = n + 1
リスト型
リストを作成する、要素を参照する
fruits = ['apple', 'orange', 'banana'] fruits[0] # 0番目(Pythonのカウントはゼロから始まることに注意)のリストの要素を取得する
fruits[1:] # 1番目以降(1番目を含む)の要素を取得する
fruits[:2] # 2番目より前(2番目を含まない)の要素を取得する
リストに要素を追加する
fruits.append('melon') print(fruits)
リストから要素を削除する
fruits.remove('apple') print(fruits)
リストの末尾の要素を削除する
fruits.pop()
print(fruits)
for文と組み合わせてリストの要素ごとに処理を繰り返す
fruits = ['apple', 'orange', 'banana'] for hoge in fruits: print(hoge+' juice')
for文・if文と組み合わせる
integers = [1,2,3,4,5,6,7,8] even = [] odd = [] for n in integers: if n % 2 == 0: even.append(n) else: odd.append(n) print(even) print(odd)
条件付きのリスト作成
even2 = [n for n in range(1,10) if n % 2 == 0] print(even2)
辞書型
辞書を作成する、キーを使って要素を個別的に参照する
score = {'国語': 82, '数学': 93, '英語': 88} score['英語']
辞書に要素を追加する
score['理科'] = 81 score
for文と組み合わせて要素を網羅的に参照する
total = 0 for value in score.values(): total = total + value print(total)
あるいはitemsを使って以下のようにも書くことができます。
total = 0 for item in score.items(): total = total + item[1] print(total)
itemsを使うとkeyの方も参照できます。
for item in score.items(): print(item[0])
あるいはkeysを使っても同様のことができます。
for key in score.keys(): print(key)
関数
関数を定義する
def greeting(name): hello = 'Hello, Mr.{}'.format(name) return print(hello) greeting('Sato')
for文と組み合わせる
name_list = ['Sato', 'Tanaka', 'Suzuki', 'Honda'] for name in name_list: greeting(name)