標準入力
input関数
- 入力内容が戻り値
- 戻り値は文字列
- 改行は自動的には入らない
入力データの処理
整数入力
ans = int(input("入力してください。"))
>>> 123
空白区切りの文字列を整数に変換して入力する
a, b = map(int, input().split(" "))
>>> 12 23
空白区切りの文字列を、配列として、整数に変換して入力する
# 入力を受ける → 空白で分ける → 整数としてmapにする → リストに変換する
pattern_A = list(map(int, input().split(" ")))
# 入力を受ける → 空白で分ける → 各要素をリスト内包表記で一つずつintに変換
pattern_B = [int(x) for x in input().split(" ")]
一つずつ、4回入力を受け取る
a,b,c.d = map(int, [input() for _ in range(4)])
プログラムを終了する
Lecture 31 1行が長い場合
\ バックスラッシュでつなぐ
それか、()で囲っておく
Lecture 32 if分
if x < 0:
print('negative')
elif x == 0:
print('zero')
else:
print('positive')
Lecture 34 論理演算子
==
!=
<
<=
=
and
or
Lecture 35 in と not の使い所
if x in y:
if x not in y:
Lecture 36 値が入っていないことを確認するテクニック
0 は false
文字列が入っていると True
配列が空なら False
False 0, 0.0, [], ()
Lecture 37 None を判定する場合
None
if is_empty is not None
print(1 == True)
print(1 is True)
Lecture while, continue, break
while count < 5:
print(count)
count += 1
while True:
if count >= 5:
break
breakはループから抜ける
continueはループ先頭に戻る
Lecture 39 while else
while:
else: breakで抜けなければ実行される
Lecture 41 for, break, continue
list = [4,3,2,1]
for i in list:
print(i) # 4,3,2,1 の順に表示
for else
while ... else ... と同じく、break で抜けなかった場合に実行される。
for ...:
....
if ...:
print("fuga")
break
else:
print("hoge")
Lecture 43 range関数
for i in range(10):
for i in range(2,10,3): 2から10を超えるまで、3おきに
イテレータからの受け取り方
List
Tuple の List
まとめて受けられる
C = [(1,2), (3,5), (8,13), ...]
for a, b in C:
print(a, b) # 1 2 / 3 5 / ... が表示される
Dict
何もしないと、key が出てくる
d = {"a":"apple", "b":"banana", "c":"citron", ... # atwiki の仕様上、大かっこで閉じれない。。。
for k in d:
print(k) # a / b / c
value 側がほしいなら d.values() にする。
key と value がセットで欲しいなら d.items() にする。
enumerate関数
List と一緒にいくつ目か、の情報も欲しい場合に、enumerate が便利
for i, fruit in enumerate([a,b,c]):
print(i, fruit) # 0 a / 1 b / ... と表示される
zip関数
複数の iterable要素 をまとめる。複数のリストを同時に回したいときに便利。
for day,fruit,drint in zip(days, fruits, drinks):
days, fruits, drinks の長さが違う場合、どうなる? -> 短いものに合わせられる。
では、長いものに合わせたいときは?(何かで埋めて)
itertools.zip_longest()
Lecture 46 辞書
Lecture 47 関数定義 def
def say_something():
関数の代入もできる
return s
def what_is_this(color): 引数パターン
Lecture 48 関数の引数
def add_num(a:int, b:int) -> int:
明示はできるが、間違った入力でも動作してしまう。
Lecture 49 位置引数、キーワード引数、
def menu(entree, drink, dessert):
menu(entree='beef', drink='ice', dessert='ice')
menu('beef', drink='ice', dessert='ice')
menu(drink='ice', 'beef', dessert='ice') これはダメ
def menu(entree='beef', drink='ice', dessert='ice'): デフォルト値
Lecture 50 デフォルト引数で気をつけること
参照引数(たとえばリスト)をデフォルトに入れるのは、間違いのもと
Lecture 51 位置引数のタプル化
def say_something(*args) *アスタリスク
for arg in args:
def say_something(word, *args):
say_something('Hi', 'Mike', 'Nancy') 最初のHiがword、後ろが引数
Lecture 52 キーワード引数の辞書化
def menu(**kwargs): **ダブルアスタリスク
for k,v in kwargs.items():
Lecture 53 Docstringとは
関数の説明書き、Pythonなりのルールがある。ルールに沿うとヘルプでの表示に使える。
Lecture 54 関数内関数
関数内だけで使う関数は、ローカルに定義できる
def outer(a,b):
def plus(c,d):
return c + d
Lecture 55 クロージャ
高度なPython技術なので「そんなものがある」程度
関数の使い分けができる
def outer(a,b):
def inner():
return a + b:
return inner ここではまだ実行されない
Lecture 56 デコレーター
@print_info の@
同じ関数をちょっと変えて使い回す場合など
Lecture 57 ラムダ(lambda)
Lecture 58 ジェネレータ
yield ある状態を保持する(ループを途中で止める)
Lecture 59 リスト内包処理
r = [i for i in t]
r = [i for i in t if i % 2 == 0]
Lecture 60 辞書包括表記
d = {x:y for x,y in zip(w,f)}
Lecture 61 集合内包表記
s = {i for i in range(10) if i % 2 == 0}
Lecture 62 ジェネレータ内包表記
def g():
g = (i for i in range(10)) タプルではなくジェネレータになる。
タプルにする場合には taple(...) とタプルの宣言をする
Lecture 63 名前空間とスコープ
グローバルとローカル変数がぶつかる場合、global
global
例えば、関数内で global で変数を宣言すると、よそで宣言された同じ名前の変数を使える(つまりグローバルに使える)
a = 1
def testfunc():
global a
print(f"{a} in testfunc) # エラーにならず、1が表示される
で、上手に消化できない挙動
def testfunc1():
global a # 関数の中で突然、「俺はグローバルだぜ」と宣言する。まだ外では a が存在していない。
a = 1
print("%d in testfunc1", a)
def testfunc2():
global a
print("%d in testfunc2", a)
if __name__ == "__main__":
testfunc1() # 1 in testfunc1
testfunc2() # 1 in testfunc2 <- testfunc1 で宣言した a もglobal で使えた
Lecture 66 コマンドライン引数
import sys
print(sys.argv)
最終更新:2020年06月14日 12:11