開発環境
- OS X Lion - Apple(OS)
- BBEdit - Bare Bones Software, Inc., Emacs(Text Editor)
- プログラミング言語: Python
『初めてのPython 第3版』(Mark Lutz 著、夏目 大 訳、オライリー・ジャパン、2009年、ISBN978-4-87311-393-7)のIV部(関数)のまとめ演習3.(引数の数を増やす (減らす))を解いてみる。
その他参考書籍
3.(引数の数を増やす (減らす))
コード(BBEdit)
sample.py
#!/usr/bin/env python3.3 #-*- coding: utf-8 -*- def adder1(*args): if type(args[0]) == type(10) or type(args[0]) == type(1.2): res = 0 else: res = args[0][:0] for arg in args: res += arg return res def adder2(*args): res = args[0] for arg in args[1:]: res += arg return res for func in [adder1, adder2]: print(func.__name__) print(func(1,2)) print(func(1,2,3,4,5)) print(func("spam", "egg")) print(func("spam", "egg", "python","javascript","scheme")) print(func([1,2], [3,4,5])) print(func([1,2], [3,4,5], [6,7], [8,9], [10])) print(func((1,2), (3,4,5))) print(func((1,2), (3,4,5), (6,7), (8,9),(10,))) try: print(func(1, "spam")) except Exception as err: print(type(err), err) try: print(func({'a':1,'b':2}, {'c':3,'d':4})) except Exception as err: print(type(err), err)
入出力結果(Terminal)
$ ./sample.py adder1 3 15 spamegg spameggpythonjavascriptscheme [1, 2, 3, 4, 5] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] (1, 2, 3, 4, 5) (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) <class 'TypeError'> unsupported operand type(s) for +=: 'int' and 'str' <class 'TypeError'> unhashable type: 'slice' adder2 3 15 spamegg spameggpythonjavascriptscheme [1, 2, 3, 4, 5] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] (1, 2, 3, 4, 5) (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) <class 'TypeError'> unsupported operand type(s) for +=: 'int' and 'str' <class 'TypeError'> unsupported operand type(s) for +=: 'dict' and 'dict' $
0 コメント:
コメントを投稿