2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

python 動作確認メモ【備忘録】

Last updated at Posted at 2019-08-31

python 動作確認メモ
 
以下、挙動は正しいことを確認して記載している。個人的なメモである。

※個人的な学習を含めた動作確認のまとめである。
(だいたい毎週土曜に随時更新を行う。)
※.format()と.time()は出力を見やすくするために事前に学習していた。
※エラーの対応については最低限しか行っていない(実際最低限も行っていない・・)。
※だた、動作の確認ができればよい。そんなメモである・・。

pythonについて

  • 高級言語である(人間にとって理解しやすく近い思考のもの)

特徴

  • ライブラリが多く存在しており、今も増加している。
  • 計算・機械学習との親和性が高い。

エディタ

  • pycharmを使用

  こちらからインストールを行う(windows版)

  • VSCodeを使用

  こちらからインストールを行う

pythonのインストール

  • Python3を使用

  こちらからインストールを行う

使用するコマンド

【 Linuxコマンド 】

  • ls・・現在のディレクトリにあるファイルを表示する
  • cd ・・ディレクトリ間を移動する
  • cat ・・ファイルの中身を表示する
  • ↑(キーボード)・・過去のコマンドをさかのぼる

Linuxコマンド:Windowsコマンド対応表

環境構築

  • anaconda3のインストール

  こちらからインストールを行う

  • 仮想環境の作成

    $ conda create --name py_study python=3.7.3
    
  • 仮想環境の実行

$ conda activate py_study


- 仮想環境の終了

```bash
$ conda deactivate 

初学編

変数とは

  • 値に名前を付ける仕組みである

型について

  • int型
     数値(整数)。小数点を含まない。

  • float型
     数値(浮動小数点)。少数点を含む。

  • str型
     文字列。''(シングルクォート)もしくは""(ダブルクォート)で囲んで表現。

  • bool型
     真偽値を表す。TrueもしくはFalseを定義する。

※プログラム中に TypeErorr が発生する場合は、キャスト(明示的型変換)を行う

標準入力

standard_input.pyを作成


import time

first = input("\n\n以下で3回数値を入力してください。\n\n数値を入力してください:")
print("\n{}が入力されました".format(first))
second = input("\n\n数値を入力してください:")
print("\n{}が入力されました".format(second))
third = input("\n\n数値を入力してください:")
print("\n{}が入力されました\n\n".format(third))
fst_sum = int(first) + int(second) + int(third)

time.sleep(2)
print(first, "", second, "", third, "の合計を計算中・・\n" )
time.sleep(2.5)
print("\n\n入力値の合計は{}です。\n\n".format(fst_sum))

② ファイルの実行


$ python standard_input.py

③実行結果

以下で3回数値を入力してください。

数値を入力してください:342

342が入力されました


数値を入力してください:423

423が入力されました


数値を入力してください:2352

2352が入力されました


342 と 423 と 2352 の合計を計算中・・



入力値の合計は3117です。

条件分岐

・if文を使用する

if_sample.py


import time

# 入力値を整数で代入する
first = int(input("\n\n以下で3回数値を入力してください。\n\n数値を入力してください:"))
print("\n{}が入力されました".format(first))
second = int(input("\n\n数値を入力してください:"))
print("\n{}が入力されました".format(second))
third = int(input("\n\n数値を入力してください:"))
print("\n{}が入力されました\n\n".format(third))
fst_sum = first + second + third

answer = input("では、合計値を暗算してみましょう。\n\n{}+{}+{}=".format(first,second,third))

# 処理を2秒間停止させる
time.sleep(2)

star = "*"*20
# 答え合わせ
if fst_sum == answer:
    print("****正解です****")
else:
    print("\n\n*****不正解です*****\n\n入力値の合計は{}です。\n\n{}\n\n".format(fst_sum, star))

実行結果

以下で3回数値を入力してください。

数値を入力してください:1

1が入力されました


数値を入力してください:1

1が入力されました


数値を入力してください:1

1が入力されました


では、合計値を暗算してみましょう。

1+1+1=1


*****不正解です*****

入力値の合計は3です。

********************

 
・簡易計算プログラムの作成


import time

"""
※現状、①と③で文字列を入力すると実行時にエラーとなる。
"""

# 入力値を代入する
print("\n\n①整数②演算子③整数を入力してください。")
print("\n\n※①と③で文字列を入力すると実行時にエラーとなります。")
first = input("\n\n\n①整数を入力してください:")
print("\n{}が入力されました".format(first))
second = input("\n\n演算子を入力してください:")
print("\n{}が入力されました".format(second))
third = input("\n\n整数を入力してください:")
print("\n{}が入力されました\n\n".format(third))


# 処理を2秒間停止させる
time.sleep(2)

# 入力値の判定
if int(first) and int(third):

    #入力演算子の判定

    #足し算
    if second == "+":
        answer = int(first) + int(third)
        print("{} + {} の計算結果は”{}”です。".format(first, third, answer))

    #引き算
    elif second == "-":
        answer = int(first) + int(third)
        print("{} + {} の計算結果は”{}”です。".format(first, third, answer))
    
    #掛け算
    elif second == "*":
        answer = int(first) + int(third)
        print("{} + {} の計算結果は”{}”です。".format(first, third, answer))

    #割り算
    elif second == "/":
        answer = int(first) + int(third)
        print("{} + {} の計算結果は {} です。".format(first, third, answer))
    
    #剰余
    elif second == "//":
        answer = int(first) + int(third)
        print("{} + {} の計算結果は {} です。".format(first, third, answer))

    #べき乗
    elif second == "**":
        answer = int(first) + int(third)
        print("{} + {} の計算結果は {} です。".format(first, third, answer))

    else:
        print("入力した演算子は無効です。")

else:
    print("数値は整数で入力してください。")

実行結果


①整数②演算子③整数を入力してください。


※①と③で文字列を入力すると実行時にエラーとなります。



①整数を入力してください:2

2が入力されました


演算子を入力してください:+

+が入力されました


整数を入力してください:2

2が入力されました


2 + 2 の計算結果は”4”です。

リスト

  • 三回値を入力して、それをリストに格納し、合計する。

import time

print("\n空のリストを定義します")

time.sleep(1.5)
# 空のリストを作成
num_list = []

print("\n\nnum_list = {}".format(num_list))


first = input("\n\n以下で3回数値を入力してください。\n\n数値を入力してください:")
print("\n{}が入力されました".format(first))
second = input("\n\n数値を入力してください:")
print("\n{}が入力されました".format(second))
third = input("\n\n数値を入力してください:")
print("\n{}が入力されました\n\n".format(third))

# リストに値を格納する
num_list = [int(first), int(second), int(third)]
# num_list.append(int(first))でも追加できる。

# for文で値を取り出す
time.sleep(1.5)

result = 0
for i in num_list:
    result += i 

print(result)

# Pythonの組み込み関数 sum() を使う
time.sleep(1.5)

print("\n\n{}".format(sum(num_list)))

実行結果

空のリストを定義します


num_list = []


以下で3回数値を入力してください。

数値を入力してください:2

2が入力されました


数値を入力してください:3

3が入力されました


数値を入力してください:2

2が入力されました


7


7

 

・リストに整数と演算子が5つ混合に入力される場合の
リストの要素の順番を変更しなくても計算ができる場合の結果を出力するプログラム

# if文だけでは分岐に時間がかかるのでロジックのみ

・演算子がはじめと終わりに入っていたらNG
・すべて数字であればNG
・リストの中に演算子が入っていなければNG

...etc

タプル

 一度宣言した後に変更することができない「変数」・「配列」である。
例えば、季節や都道府県などの値の変更が必要ないものを格納する際に使用する。


season = ("", "", "", "")

for文(反復)

 for文を使うとデータの集合(listオブジェクト等)から、"データを一つずつ取り出す"ことができる。

for_sample.py


num_list = [1, 2, 3, 4, 5]
for data in num_list:
    print("繰り返して", data, "を取得")

※インデントは処理のブロックを表す。

実行結果

繰り返して 1 を取得
繰り返して 2 を取得
繰り返して 3 を取得
繰り返して 4 を取得
繰り返して 5 を取得

 

  • range関数を使用したfor文 

  容易に回数を指定して繰り返し処理を行うことができる。

for data in range(5):
    print("繰り返して", data, "を取得")

実行結果

繰り返して 0 を取得
繰り返して 1 を取得
繰り返して 2 を取得
繰り返して 3 を取得
繰り返して 4 を取得

※この時"0"から始まることに注意

 

  • enumerate()を使用したfor文 

  繰り返し処理の繰り返し番号が集合の要素と同時に取得できる。

season = ("", "", "", "")
for idx, data in enumerate(season):
    print("{}回目に{}を取得".format(idx + 1, data))

実行結果

1回目に春を取得
2回目に夏を取得
3回目に秋を取得
4回目に冬を取得

 

While文(ループ文)

 指定した条件を満たすまでループ処理を行うことができる。

while_sample.py

count = 1
print("\n5回まで入力できます。")

# 5回入力するまで行い、"exit"が入力されたら中断する
while count <5:
    data = input("\n\n好きな値を入力してください:")
    print("\n{}回目の入力:{}".format(count, data))
    if data == "exit":
        print("\n\n\"{}\"が入力されたため終了します".format(data))
        break
    count += 1

# 入力回数条件を満たしているかの判定
if count <5:
    print("\n\n5回の入力の途中でやめました")
else:
    print("\n\n5回入力できました")

実行結果

5回まで入力できます。


好きな値を入力してください:s

1回目の入力:s


好きな値を入力してください:exit

2回目の入力:exit


"exit"が入力されたため終了します


5回の入力の途中でやめました

 

  • 無限ループの中で一定の条件下でbreakする条件を用意した場合

count = 0

while True:
    print(count)
    count += 1
    if count == 10:
        break

実行結果

0
1
2
3
4
5
6
7
8
9

 

  • 入力された数値を足し続け、"exit"が入力されると終了するプログラム
count = 1
data = 0

while True:
    count += 1
    input_num = input("\n数値を入力してください : ")
    if input_num == "exit":
        print("\n\n処理を終了します・・\n\n\"END\"")
        break
    else:
        data += int(input_num)
        print("\n{}回目の入力合計 : {}".format(count, data))

実行結果


数値を入力してください : 2

2回目の入力合計 : 2

数値を入力してください : 2

3回目の入力合計 : 4

数値を入力してください : 2

4回目の入力合計 : 6

数値を入力してください : 3

5回目の入力合計 : 9

数値を入力してください : 645

6回目の入力合計 : 654

数値を入力してください : 234

7回目の入力合計 : 888

数値を入力してください : exit


処理を終了します・・

"END"

※今回もエラーは考えないものとする。
 

辞書

 辞書型(dictオブジェクト)について

season = {
    "":"spring",
    "":"summer",
    "":"autumn",
    "":"winter",}

print(season[""])

※基本的に辞書は","で終わらせる。(処理速度がわずかに変わる為)

実行結果

summer

 

  • 辞書型の値には別の辞書を格納できる
result = {
    "田中":{"国語":80, "算数":90,},
    "鈴木":{"国語":90, "算数":100,},
    "中村":{"国語":100, "算数":80,},}

print(result["鈴木"])
print(result["鈴木"]["国語"])

 

  • 辞書のキーにタプルを指定できる(listは指定できない※エラーとなる。)。
data = {("A", "B", "C"):"エービーシー"}

print(data[("A", "B", "C")])

実行結果

エービーシー

GPSの緯度、経度をキーにして場所を値に指定する場合などに使える。

 

  • dictの分岐応用

 if文を用いることで辞書の中身への存在の確認ができる。

hitorigoto = "今日はいい天気だなあ"
if "天気" in hitorigoto:
    print("含まれます")

実行結果

含まれます

ここまでのまとめのプログラム【1】

  1. "キーを入力してください:"と表示させてキーを入力してもらう
  2. "値を入力してください:"と表示させて値を入力してもらう
  3. 入力結果を辞書に記録する
  4. 辞書を表示する
  5. "1."に戻る
  6. "exit"と入力されたら終了する

matome_1.py

print("\n辞書の作成を行います。")

user_dict = {}
while True:

    key = input("\n\nキーを入力してください : ")
    value = input("\n値を入力してください : ")

    if key == "exit" or value == "exit":
        print("\n\n辞書の作成を終了します\n現在の辞書の中身は\n\n{}\n\nです。".format(user_dict))
        break
    else:
        user_dict[key] = value
        print("\n\n追加された項目は\"{} : {}\"です\n".format(key, value))

実行結果

辞書の作成を行います。


キーを入力してください : りんご

値を入力してください : apple


追加された項目は"りんご : apple"です



キーを入力してください : さくらんぼ

値を入力してください : cherry


追加された項目は"さくらんぼ : cherry"です



キーを入力してください : exit

値を入力してください : a


辞書の作成を終了します
現在の辞書の中身は

{'りんご': 'apple', 'さくらんぼ': 'cherry'}

です。

 

ファイルに保存する

 open()を使用する。

  • 新規作成 ・・ファイルを作成して保存
  • 追記   ・・既存のファイルに追記
  • 上書き  ・・既存のファイルを上書き

がある。

【書き込み】

writefile.py


file1 = open("file1.txt", mode='w')
file1.write("こんにちは")
file1.close()

実行後、コマンドプロンプトへ移動して下記を実行

作業中ディレクトリ>dir

2019/09/07  15:28    <DIR>          .
2019/09/07  15:28    <DIR>          ..
2019/08/31  17:08             5,686 20190831_1.py
2019/09/07  15:28             2,471 20190907_1.py
2019/09/07  15:28                10 file1.txt
               3 個のファイル               8,167 バイト
               2 個のディレクトリ  196,984,541,184 バイトの空き領域

作業中ディレクトリ>type file1.txt
こんにちは

【読み込み】

writefile.py


file1 = open("file1.txt", mode='r')
data = file1.read()
file1.close()
print(data)

実行結果

こんにちは

 

with構文

 open()を使用した際にclose()は必要だが、長いプログラムを書く際にうっかりclose()を失念する場合がある。そのような事態を防ぐためにwith構文を使用する。

with.py

with open("file1.txt", mode='r') as fr:
    data = fr.read()
print(data)

実行結果

こんにちは

 

文字列分割

 文字列を特定の区切り位置で分割し、リストとして格納する方法

abc_str = "a,b,c"
arg = abc_str.split(',')
print(arg)

実行結果

['a', 'b', 'c']

 

  • 改行コードが含まれている場合の処理
abc_str = "a\nb\nc"
arg = abc_str.split('\n')
print("\n.split() : {}".format(arg))

abc_str = "a\nb\nc"
arg = abc_str.splitlines()
print("\n.splitlines() : {}".format(arg))

実行結果

.split() : ['a', 'b', 'c']

.splitlines() : ['a', 'b', 'c']

ここまでのまとめプログラム【2】

 json.load() / json.dump() (いつか使う日が来る。)を使わずに、辞書のファイルに対しての読み込みと書き込みを行ってみる。

matome_2.py

print("\n辞書の登録を行います。\n登録が終了した場合は\"exit\"を入力してください。")

# "exit"を入力するまで登録を続ける
while True:
    key = input("\n\nキーを入力してください : ")
    value = input("\n値を入力してください : ")

    #登録を続けるかどうかの判定
    if key == "exit" or value == "exit":
        print("\n\n登録終了\n\n---END---")
        break
    else:
        data = key + "," + value + ","
        with open("file2.txt", mode='a') as fw:
            fw.write(data)

# 辞書として読み込みを行う。
print("\n\nファイルを辞書として読み込み")
with open("file2.txt", mode='r') as fr:
    line = fr.read()
    line_list = line.split(',')
    data_dict = {}
    input_list = []
    for idx, i in enumerate(line_list[:-1]):
        if (idx + 1) % 2 == 0:
            input_list += [i]
            key, value = input_list[0], input_list[1]
            data_dict[key] = value
            input_list = []
        else:
            input_list += [i]

print("\n\n{}\n\n以上".format(data_dict))

実行結果

辞書の登録を行います。
登録が終了した場合は"exit"を入力してください。


キーを入力してください : りんご

値を入力してください : apple


キーを入力してください : さくらんぼ

値を入力してください : cherry


キーを入力してください : exit

値を入力してください : a


登録終了

---END---


ファイルを辞書として読み込み


{'りんご': 'apple', 'さくらんぼ': 'cherry'}

以上

※改行コードが入った場合は諦める仕様になっている。(諦めたくない人は.strip()を使用する)

関数

組み込み関数

 pythonのインタプリタを開いてdir()を実行すると組み込み関数が確認できる。
※pythonの組み込み関数は全部で69個ある。

pythonのインタプリタで以下を実行

dir(__builtins__)

実行結果

['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '_', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']

関数の作り方

test_func.py

def test_func():
    print("test1")
    return "test2"

if __name__ == '__main__':
    test_func()
    print(test_func())

実行結果

test1
test1
test2

docstringについて

 関数についての説明を記載しておく。他人はもちろん、1年後の自分にもわかるように記載しておく。

test_docstring.py

def test_func():
    """テスト用に作成した関数

    printとreturnの出力のされ方を確認するための関数
    """
    print("test1")
    return "test2"

if __name__ == '__main__':
    test_func()
    print(test_func())

実行結果

>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
>>> def test_func():
...     """テスト用に作成した関数
...
...     printとreturnの出力のされ方を確認するための関数
...     """
...     print("test1")
...     return "test2"
...
>>> dir
<built-in function dir>
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'test_func']
>>> help(test_func)
Help on function test_func in module __main__:

test_func()
    テスト用に作成した関数

    printとreturnの出力のされ方を確認するための関数

>>>   

という感じでhelp()で関数の説明を確認することができる。

モジュールの使用

pythonには標準ライブラリがある。

import random

print(random.randint(0,10))

実行結果

3

もしくは

from random import randint
 
print(randint(0,10))

実行結果

3

別名をつけることもできる

from random import randint as rint
 
print(rint(0,10))

実行結果

3
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?