導入
Python には、すぐ使える機能の集まり(標準ライブラリ)が付属しています。import で読み込んで使います。ここでは math と random を触ります。
説明
import モジュール名 で読み込み、モジュール名.機能 の形で使います。math は数学の関数を集めたモジュールです。
import math
print(math.sqrt(16)) # 4.0(平方根)
print(math.pi) # 3.141592653589793(円周率)
print(math.floor(3.7)) # 3(切り捨て)
print(math.ceil(3.2)) # 4(切り上げ)
random は乱数(ランダムな値)のモジュールです。サイコロやくじ引きのような処理に使います。
import random
dice = random.randint(1, 6) # 1〜6 のどれか
print("サイコロ:", dice)
fruits = ["りんご", "みかん", "ぶどう"]
print("今日の果物:", random.choice(fruits)) # リストから1つ選ぶ
必要な機能だけを取り出す from モジュール import 名前 という書き方もあります。
from math import sqrt
print(sqrt(25)) # 5.0(math. を付けずに使える)
やってみよう
math の関数にいろいろな数を渡したり、random を何度も実行して結果が変わることを確かめましょう。
演習
math を import して、math.sqrt(81) の結果を表示してください(結果は 9.0)。
ヒント1を見る
import math のあと print(math.sqrt(81))。