総和を計算する

以下のpythonソースコードを

  • テキストエディタを使って
  • 拡張子 .py をつけて
  • 文字符号化UTF-8で
  • 保存する。

    [注意]

    1. 記号 # 以下の文字列は行末までpython処理系においては『無視され』、結果「comment]として扱われる。
    2. スクリプト内の文字列において日本語を正確に表示するた、えには、ファイル行頭で「#encoding: utf8」の記述が必要である(utf8は文字コード)。

    ファイル名 hello.py のsum0.pyスクリプトをMacOSで動作させるためには

    $ python sum0.py
    

    とする(プロンプト $ はユーザ環境に併せて理解する)。

    総和スクリプト(sum0.py)

    #encoding: utf8
    # 仮に合計を 0 とする
    
    total = 0
    for i in range(1, 10):# i は 1 から 10未満(つまり9)を動く
        total += i
        print i, total
    
    print total
    

    総和スクリプト(sum1.py)

    #encoding: utf8
    import random # 乱数モジュールを使う
    # random.random()        0.0~1.0までのfloat値
    # random.uniform(a,b)    a~bまでのfloat値
    # random.randint(a,b)    a~bまでのint値
    
    a = []# リスト a を用意する
    
    for i in range(0, 1000000):
        rnd = random.random()
    #    print rnd
        a.append(rnd)# 乱数をリスト要素として追加する
    
    #	print a
    
    # リスト a 内の値を合計する
    total = 0
    for i in range(0, len(a)):
        total += a[i]
    #    print i, "番目の値 = ", a[i], "を加えた暫定合計 = ", total
    
    print "合計 =", total