開発環境
- OS X Lion - Apple(OS)
- TextWrangler(Text Editor) (BBEditの無料機能制限版、light版)
- Script言語: Python
『初めてのPython 第3版』(Mark Lutz 著、夏目 大 訳、オライリー・ジャパン、2009年、ISBN978-4-87311-393-7) のIV部(関数)まとめ演習4(キーワード引数)を解いてみる。
4.
コード(TextWrangler)
#!/usr/bin/env python #encoding: utf-8 def adder(good=10,bad=20,ugly=30): return good + bad + ugly
入出力結果(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. >>> from python_program import adder >>> print adder(5) 55 >>> print adder(5,6) 41 >>> print adder(5,6,7) 18 >>> print adder(5,6,7,8) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: adder() takes at most 3 arguments (4 given) >>> print adder('a') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "python_program.py", line 5, in adder return good + bad + ugly TypeError: cannot concatenate 'str' and 'int' objects >>> 'a'+1 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: cannot concatenate 'str' and 'int' objects >>> 1+'a' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for +: 'int' and 'str' >>> print adder(ugly=1,good=2) 23 >>> quit() $
adder関数をさらに改良
コード(TextWrangler)
#!/usr/bin/env python #encoding: utf-8 def adder(**args): L = [] for key in args.keys(): L.append(args[key]) result = L[0] for x in L[1:]: result += x return result print adder(a=1,b=2,c=3,d=4,e=5)
入出力結果(Terminal)
$ python python_program.py 15 $
0 コメント:
コメントを投稿