開発環境
- OS X Lion - Apple(OS)
- TextWrangler(Text Editor) (BBEditの無料機能制限版、light版)
- Script言語: Python
『初めてのPython 第3版』(Mark Lutz 著、夏目 大 訳、オライリー・ジャパン、2009年、ISBN978-4-87311-393-7) のIII部(ステートメント)11章(代入ステートメント、式ステートメント、printステートメント)の練習問題を解いてみる。
1.
実際に3つの変数に同じ値をいくつかの方法で代入。
入出力結果(Terminal)
$ python Python 2.7.2 (default, Feb 12 2012, 23:50:38) [GCC 4.2.1 Compatible Apple Clang 3.0 (tags/Apple/clang-211.12)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> a=b=c=10 >>> a,b,c (10, 10, 10) >>> a=20 >>> b=20 >>> c=20 >>> a,b,c (20, 20, 20) >>> a=30;b=30;c=30 >>> a,b,c (30, 30, 30) >>> (a,b,c)=(40,40,40) >>> a,b,c (40, 40, 40) >>> a 40 >>> quit() $
可変性オブジェクトを3つの変数に同時に代入した場合、どの変数も参照先は同じなので1つの変数を変更したら他の変数にも影響がある点に注意すべき。
実例
入出力結果(Terminal)
$ python Python 2.7.2 (default, Feb 12 2012, 23:50:38) [GCC 4.2.1 Compatible Apple Clang 3.0 (tags/Apple/clang-211.12)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> l=m=n=[1,2,3,4,5] >>> l,m,n ([1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]) >>> l[1]=0 >>> l,m,n ([1, 0, 3, 4, 5], [1, 0, 3, 4, 5], [1, 0, 3, 4, 5]) >>> quit() $
3.
リストのsortメソッドはリストそのものを上書きするメソッドで、戻り値はNoneになるのでコードではLにNoneを代入することになる。
入出力結果(Terminal)
$ python Python 2.7.2 (default, Feb 12 2012, 23:50:38) [GCC 4.2.1 Compatible Apple Clang 3.0 (tags/Apple/clang-211.12)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> l=[5,1,4,2,3] >>> l.sort() >>> l [1, 2, 3, 4, 5] >>> l=l.sort() >>> l >>> print l None >>> quit() $
4.
printステートメントを使用して、テキストをファイルに書き込むにはファイルを開いてからprint >> ファイル, 書き込む内容、とすればいい。入出力結果(Terminal)
$ python Python 2.7.2 (default, Feb 12 2012, 23:50:38) [GCC 4.2.1 Compatible Apple Clang 3.0 (tags/Apple/clang-211.12)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> name='sample.txt' >>> f=open(name,'w') >>> f.write('Hello, World!\n') >>> f.close() >>> f=open(name,'r') >>> f.read() 'Hello, World!\n' >>> f.close() >>> f=open(name,'a') >>> print >> f,'Hello, Python!' >>> f.close() >>> f=open(name,'r') >>> f.read() 'Hello, World!\nHello, Python!\n' >>> quit() $
0 コメント:
コメントを投稿