###### tags: `Python勉強会` # Python勉強会 第4回 課題解説 :::info **<第4回Web会議日程>** 2023年02月21日(水) 19:00から **<第4回の自習範囲>** **【Pythonチュートリアル】**  https://docs.python.org/ja/3/tutorial/index.html [6. モジュール](https://docs.python.org/ja/3/tutorial/modules.html)  [6.1. モジュールについてもうすこし](https://docs.python.org/ja/3/tutorial/modules.html#more-on-modules)   [6.1.1. モジュールをスクリプトとして実行する](https://docs.python.org/ja/3/tutorial/modules.html#executing-modules-as-scripts)   [6.1.2. モジュール検索パス](https://docs.python.org/ja/3/tutorial/modules.html#the-module-search-path)   [6.1.3. "コンパイル" された Python ファイル](https://docs.python.org/ja/3/tutorial/modules.html#compiled-python-files)  [6.2. 標準モジュール](https://docs.python.org/ja/3/tutorial/modules.html#standard-modules)  [6.3. dir() 関数](https://docs.python.org/ja/3/tutorial/modules.html#the-dir-function)  [6.4. パッケージ](https://docs.python.org/ja/3/tutorial/modules.html#packages)   [6.4.1. パッケージから * を import する](https://docs.python.org/ja/3/tutorial/modules.html#importing-from-a-package)   [6.4.2. パッケージ内参照](https://docs.python.org/ja/3/tutorial/modules.html#intra-package-references)   [6.4.3. 複数ディレクトリ中のパッケージ](https://docs.python.org/ja/3/tutorial/modules.html#packages-in-multiple-directories) [7. 入力と出力](https://docs.python.org/ja/3/tutorial/inputoutput.html#input-and-output)  [7.1. 出力を見やすくフォーマットする](https://docs.python.org/ja/3/tutorial/inputoutput.html#fancier-output-formatting)   [7.1.1. フォーマット済み文字列リテラル](https://docs.python.org/ja/3/tutorial/inputoutput.html#formatted-string-literals)   [7.1.2. 文字列の format() メソッド](https://docs.python.org/ja/3/tutorial/inputoutput.html#the-string-format-method)   [7.1.3. 文字列の手作業でのフォーマット](https://docs.python.org/ja/3/tutorial/inputoutput.html#manual-string-formatting)   [7.1.4. 古い文字列書式設定方法](https://docs.python.org/ja/3/tutorial/inputoutput.html#old-string-formatting)  [7.2. ファイルを読み書きする](https://docs.python.org/ja/3/tutorial/inputoutput.html#reading-and-writing-files)   [7.2.1. ファイルオブジェクトのメソッド](https://docs.python.org/ja/3/tutorial/inputoutput.html#methods-of-file-objects)   [7.2.2. json による構造化されたデータの保存](https://docs.python.org/ja/3/tutorial/inputoutput.html#saving-structured-data-with-json) [10. 標準ライブラリミニツアー](https://docs.python.org/ja/3/tutorial/stdlib.html)  [10.1. OSへのインターフェース](https://docs.python.org/ja/3/tutorial/stdlib.html#operating-system-interface)  [10.2. ファイルのワイルドカード表記](https://docs.python.org/ja/3/tutorial/stdlib.html#file-wildcards)  [10.3. コマンドライン引数](https://docs.python.org/ja/3/tutorial/stdlib.html#command-line-arguments)  [10.4. エラー出力のリダイレクトとプログラムの終了](https://docs.python.org/ja/3/tutorial/stdlib.html#error-output-redirection-and-program-termination)  [10.5. 文字列のパターンマッチング](https://docs.python.org/ja/3/tutorial/stdlib.html#string-pattern-matching)  [10.6. 数学](https://docs.python.org/ja/3/tutorial/stdlib.html#mathematics)  [10.7. インターネットへのアクセス](https://docs.python.org/ja/3/tutorial/stdlib.html#internet-access)  [10.8. 日付と時刻](https://docs.python.org/ja/3/tutorial/stdlib.html#dates-and-times)  [10.9. データ圧縮](https://docs.python.org/ja/3/tutorial/stdlib.html#data-compression)  [10.10. パフォーマンスの計測](https://docs.python.org/ja/3/tutorial/stdlib.html#performance-measurement)  [10.11. 品質管理](https://docs.python.org/ja/3/tutorial/stdlib.html#quality-control)  [10.12. バッテリー同梱](https://docs.python.org/ja/3/tutorial/stdlib.html#batteries-included) [11. 標準ライブラリミニツアー --- その 2](https://docs.python.org/ja/3/tutorial/stdlib2.html)  [11.1. 出力のフォーマット](https://docs.python.org/ja/3/tutorial/stdlib2.html#output-formatting)  [11.2. 文字列テンプレート](https://docs.python.org/ja/3/tutorial/stdlib2.html#templating)  [11.3. バイナリデータレコードの操作](https://docs.python.org/ja/3/tutorial/stdlib2.html#working-with-binary-data-record-layouts)  [11.4. マルチスレッディング](https://docs.python.org/ja/3/tutorial/stdlib2.html#multi-threading)  [11.5. ログ記録](https://docs.python.org/ja/3/tutorial/stdlib2.html#logging)  [11.6. 弱参照](https://docs.python.org/ja/3/tutorial/stdlib2.html#weak-references)  [11.7. リスト操作のためのツール](https://docs.python.org/ja/3/tutorial/stdlib2.html#tools-for-working-with-lists)  [11.8. 10 進浮動小数演算](https://docs.python.org/ja/3/tutorial/stdlib2.html#decimal-floating-point-arithmetic) ::: *** ## モジュール一覧表 | モジュール名 | 用途 | | -------- | -------- | | mathモジュール| 数学計算に関連する処理 | | randomモジュール | 乱数に関する処理 | | statisticsモジュール | 統計の計算に関する処理 | | datetimeモジュール | 日付・時刻の取得や操作に関する処理 | | reモジュール | 文字列のパターンマッチング(正規表現)関する処理 | | sysモジュール | インタプリタや実行環境に関連した情報の操作に関する処理 | | emailモジュール | 電子メールに関する処理 | **※もっと詳しく見たい方は以下を参照してみてください** [Python 標準ライブラリ](https://docs.python.org/ja/3.9/library/index.html) *** ## 課題① ### 次のファイル「`script.py`」を作成し、コマンドライン上で「`python3 script.py one two three four five`」を実行したときの結果として正しいものはA~Dのどれでしょうか? [<span style="color:blue">script.py</span>] ``` import sys print(sys.argv[0:4]) ``` **A**  [`'script.py', 'one', 'two', 'three'`] **B**  [`'script.py', 'one', 'two', 'three', 'four'`] **C**  [`'python3', 'script.py', 'one', 'two'`] **D**  [`'python3', 'script.py', 'one', 'two', 'three'`] ``` [ script.py ] import sys print(sys.argv[0:4]) ``` 「<span style="color:blue">script.py</span>」ファイルを作成する :::info 「<span style="color:blue">script.py</span>」の解説 ``` import sys ``` ライブラリであるsysモジュールをインポートする ``` print(sys.argv[0:4]) ``` インデックス 0 の位置 (sys.argv[0]) には、pythonコマンドで指定したスクリプト自身の名前が格納されるので、今回の問題では「script. py」 インデックスは「開始値は常に含まれ、終了値は常に含まれない」 となるので、「0 1 2 3」が表示される ::: 上記のことから、「`python3 script.py one two three four five`」を実行すると、`script.py one two three`が求められる *** ## 課題① 解答 :::spoiler 解答 <br> **A**  [`'script.py', 'one', 'two', 'three'`] ::: *** ## 課題② ### モジュールに関する次の記述のうち誤っているものはどれか。 **A**  mathモジュールを使うと、コード処理の実行時間を計測できる。 **B**  smtplibモジュールを使うと、任意のインターネット上のホストにメールを送ることができる。 **C**  randomモジュールを使うと、疑似乱数を生成することができる。 **D**  statisticsモジュールを使うと、数値データの基本統計量(平均、中央値、分散など)を取得することができる。 *** **B**  smtplibモジュールを使うと、任意のインターネット上のホストにメールを送ることができる。 :::warning **<smtplibモジュール>**  PythonでSMTPまたはESMTPのリスナーデーモンを備えた**任意の  インターネット上のホストにメールを送る**ために使用することが  できる SMTPクライアント・セッション・オブジェクトを定義    ※[smtplibモジュール](https://docs.python.org/ja/3.9/library/smtplib.html#module-smtplib) ::: smtplibモジュールの記述に当てはまるため、**B**は正解 **smtplibモジュール使用例(メール送信)** ``` import smtplib smtp_host = 'smtp.gmail.com' smtp_port = 465 username = 'mouvyet4kagmak@gmail.com' password = '********' from_address = 'mouvyet4kagmak@gmail.com' to_address = 'mouvyet4kagmak@gmail.com' subject = 'test subject' body = 'test body' message = ("From: %srnTo: %srnSubject: %srnrn%s" % (from_address, to_address, subject, body)) smtp = smtplib.SMTP_SSL(smtp_host, smtp_port) smtp.login(username, password) result = smtp.sendmail(from_address, to_address, message) print(result) ``` *** C  randomモジュールを使うと、疑似乱数を生成することができる。 :::warning **<randomモジュール>**  様々な分布をもつ**疑似乱数生成**器を実装している。ランダムな  要素や乱数を使う操作などにはとても便利    ※[randomモジュール](https://docs.python.org/ja/3/library/random.html#module-random) ::: randomモジュールの記述に当てはまるため、**C**は正解 **randomモジュール使用例(パスワード作成)** ``` import random characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' #一時的なパスワード temporarypassword = '' #15文字のランダムな文字列を生成します。 for i in range(0, 15): temporarypassword += random.choice(characters) print(temporarypassword) ``` *** **D**  statisticsモジュールを使うと、数値データの基本統計量(平均、中央値、分散など)を取得することができる。 :::warning **<statisticsモジュール>**  数値 (Real 型) データを数学的に統計計算するための関数を  提供し、簡単に**平均値、中央値、分散、標準偏差**を求められる    ※[statisticsモジュール](https://docs.python.org/ja/3.10/library/statistics.html#module-statistics) ::: statisticsモジュールの記述に当てはまるため、**D**は正解 **statisticsモジュール使用例(平均値・中央値)** ``` 【平均値】 import statistics data = [13, 15, 25, 37, 40, 50, 57, 61, 90, 99] result = statistics.mean(data) print(result) >>> 48.7 【中央値】 import statistics data = [13, 15, 25, 37, 40, 50, 57, 61, 90, 99] result = statistics.median(data) print(result) >>> 45.0 ``` *** **A**  mathモジュールを使うと、コード処理の実行時間を計測できる。 コード処理の実行時間を計測できるのは、**timeitモジュール**の説明のため、**A**が誤り :::warning **<timeitモジュール>**  小さいPython**コードの時間を計測する**シンプルな手段を提供。  なるべく正確な時間を算出するためにプロットフォーム特有の  time関数を使用    ※[timeitモジュール](https://docs.python.org/ja/3/library/timeit.html#module-timeit) ::: **timeitモジュール使用例(基本例)** ``` import timeit timeit.timeit(lambda: "-".join(map(str, range(100))), number=10000) >>>0.19665591977536678 ``` :::warning **<mathモジュール>**  **数学的な計算をする**のに役立つ標準モジュール。円周率、  切り上げ、切り捨て、指数、対数、三角関数など様々な数学関連  の処理が可能    [mathモジュール](https://docs.python.org/ja/3/library/math.html#module-math) ::: **mathモジュール使用例(円周率)** ``` import math math.pi >>>3.141592653589793 ``` *** ## 課題② 解答 :::spoiler 解答 <br> **A**  mathモジュールを使うと、コード処理の実行時間を計測できる。 ::: *** ## 課題③ ### 「<span style="color:blue">fibo.py</span>」を作成し、コマンドラインで「コード」を実行したときの結果として正しいものはA~Dのどれでしょうか? [<span style="color:blue">fibo.py</span>] ``` def fib(n): a, b = 0, 1 while a < n: print(a, end=' ') a, b = b, a+b print() def fib2(n): a, b = 0, 1 while a < n: print(a, sep=',') a, b = b, a+b print() ``` [コード] ``` import fibo fibo.fib(100) ``` **A**  0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 **B**  [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] **C**  0 1 1 2 3 5 8 13 21 34 55 89 **D**  0,1,1,2,3,5,8,13,21,34,55,89 *** 「<span style="color:blue">fibo.py</span>」を作成する ``` import fibo ``` fiboという名称でモジュールをインポートする ``` fibo.fib(100) ``` fib(100)を呼び出すので、「<span style="color:blue">fibo.py</span>」のfib(n)を呼び出す ``` def fib(n): a, b = 0, 1 while a < n: print(a, end=' ') a, b = b, a+b print() ``` :::info **fib(n)の解説** ``` def fib(n): ``` fib(n)を呼び出す ``` a, b = 0, 1 ``` a=0、b=1を代入する ``` while a < n: ``` 今回の問題ではn=100だから、aが100を超えるまで繰り返す ``` print(a, end=' ') ``` aの値を出力し、end=''により、末尾に空白を指定する ``` a, b = b, a+b ``` a=b、b=a+bを代入する ``` print() ``` 最終的に文字列を出力する ::: 上記により、fib(100)を求めて出力する *** ## 課題③ 解答  :::spoiler 解答 <br> **C**  0 1 1 2 3 5 8 13 21 34 55 89 ::: *** ## 課題④ ### 以下のコードの実行結果として正しいものはA~Dのどれでしょうか? ``` import math print('{1:.3f}, {0:.5f}'.format(math.pi, math.e)) ``` **A**  1:3.141f, 0:2.71828f **B**  3.141, 2.71828 **C**  2.718, 3.14159 **D**  2.71828 3.141 ※今回のチュートリアルに記載がないため以下を参考にして下さい ヒント:[math](https://docs.python.org/ja/3/library/math.html#math.pi) *** ``` import math ``` ライブラリであるmathモジュールをインポートする ``` print('{1:.3f}, {0:.5f}'.format(math.pi, math.e)) ``` >print('{1:.3f}, {0:.5f} {1:.3f}の**1**はインデックス番号、**.3**は小数点以下の桁数で下3桁、**f**は小数点を表す >format(math.pi, math.e) ==math.pi : π=3.141592... (円周率)== ==math.e : e = 2.718281... (自然対数の底)== 最初のインデックスは**0**となるので、math.piは**0**、math.eは**1**となる ## 課題④ 解答 :::spoiler 解答 <br> **C**  2.718, 3.14159 ::: ***