Python はじめました:乱数

Python.use(better) # Python はじめました記事一覧
乱数

《著》小粒ちゃん+α《監修》小泉ひよ子とタマゴ倶楽部
第0版♪2001/03/02 ● 第1版♪2003/05/25 ● 第2版♪2004/06/01 ● 第3版♪2009/02/28

乱数〈Python 3.0 版〉

モジュール random は、乱数を扱うための機能を提供します。

from random import *
rand = Random()
def ex():
    s = "rand"
    print(">>>",s)
    print(eval(s))
    s = "[rand.randint(0, 9) for _ in range(10)]"
    for e in range(10):
        print(">>>",s)
        print(eval(s))

% python3.0 -i ex.py
>>> ex()
>>> rand

>>> [rand.randint(0, 9) for _ in range(10)]
[4, 4, 1, 7, 8, 6, 3, 7, 2, 6]
>>> [rand.randint(0, 9) for _ in range(10)]
[1, 3, 9, 1, 4, 3, 4, 6, 5, 5]
>>> [rand.randint(0, 9) for _ in range(10)]
[5, 9, 2, 2, 1, 8, 9, 2, 5, 2]
>>> [rand.randint(0, 9) for _ in range(10)]
[1, 3, 0, 5, 9, 4, 3, 6, 5, 2]
>>> [rand.randint(0, 9) for _ in range(10)]
[6, 1, 1, 9, 3, 5, 6, 9, 9, 8]
...

メソッド rand.randint を呼び出すたびに、指定した範囲 [0, 9] の整数が得られるのが分かります。

from random import *
def ex():
    rand = Random()
    s = "rand.random()"
    for e in range(10):
        print(">>>",s)
        print(eval(s))

% python3.0 -i ex.py
>>> ex()
>>> rand.random()
0.493059875794
>>> rand.random()
0.599367689097
>>> rand.random()
0.590587143415
>>> rand.random()
0.373116394107
>>> rand.random()
0.315192737233
...

メソッド rand.random を呼び出すたびに、任意の実数 [0.0, 1.0) が得られるのが分かります。

乱数〈Python 2.x 版〉

Python 3.0 版〉と同様です。


《Note》言語仕様の改訂に伴って、

def ex():
    from random import *        # --- SyntaxWarning ---
    rand = Random()
    ...

import 文は、モジュールレベルでしか利用できなくなります。そのため、

% python2.6 -i ex.py
ex.py:...: SyntaxWarning: import * only allowed at module level
  def ex():
    
Python 2.6 までは、例外 SyntaxWarning を生成して、警告メッセージを出力するだけですが、
% python3.0 -i ex.py
  File "ex.py", line ...
    def ex():
SyntaxError: import * only allowed at module level
>>> 
Python 3.0 以降は、例外 SyntaxError を生成して、エラーメッセージを出力します。■
Last updated♪09/03/05