開発環境
- OS X Lion - Apple(OS)
- BBEdit - Bare Bones Software, Inc., Emacs(Text Editor)
- プログラミング言語: Python
『初めてのPython 第3版』(Mark Lutz 著、夏目 大 訳、オライリー・ジャパン、2009年、ISBN978-4-87311-393-7)のIII部(ステートメント)、11章(代入ステートメント、式ステートメント)の練習問題を解いてみる。
その他参考書籍
1, 2, 3, 4.
コード(BBEdit)
sample.py
#!/usr/bin/env python3.3 #-*- coding: utf-8 -*- a = b = c = "spam" print(a, b, c) # 可変性オブジェクトの代入は参照の代入(1つのオブジェクトの変更が他のオブジェクトにも影響する) # ことに注意する必要がある a = b = c = [1,2,3,4,5] print(a, b, c) a[0] = "spam" # b, cにも影響 print(a, b, c) # リストのsortメソッドはリストを上書きするメソッドで、戻り値はNone L = [5,1,4,2,3] L = L.sort() print(L) L = [5,1,4,2,3] L.sort() print(L) # 戻り値としてソート済のメソッドを得たかったらビルトインメソッドのsortedを使えばいい # このメソッドはオブジェクトを上書きしない L = [5,1,4,2,3] sorted_L = sorted(L) print(L) print(sorted_L) # print関数でテキストファイルに書き込み import sys tmp = sys.stdout with open('sample.txt', 'w') as f: sys.stdout = f print("Hello, world!") sys.stdout.close() sys.stdout = tmp with open('sample.txt') as f: print(f.read(), end="")
入出力結果(Terminal)
$ ./sample.py spam spam spam [1, 2, 3, 4, 5] [1, 2, 3, 4, 5] [1, 2, 3, 4, 5] ['spam', 2, 3, 4, 5] ['spam', 2, 3, 4, 5] ['spam', 2, 3, 4, 5] None [1, 2, 3, 4, 5] [5, 1, 4, 2, 3] [1, 2, 3, 4, 5] Hello, world! $ cat sample.txt Hello, world! $
0 コメント:
コメントを投稿