2012年9月20日木曜日

開発環境

『初めてのPython 第3版』(Mark Lutz 著、夏目 大 訳、オライリー・ジャパン、2009年、ISBN978-4-87311-393-7) のVII部(例外)の27章(例外の基礎知識)練習問題4を解いてみる。

その他参考書籍

4.

assertステートメントは特定の条件が満たされなかった場合にのみraiseステートメントが実行されるというコードを短くするためのもの。ifステートメントとraiseステートメントでも同様のことが出来る。

コード(TextWrangler)

sample.py

#!/usr/bin/env python
#-*- coding: utf-8 -*-

def f(n):
 assert n > 0, 'n must be positive'
 return "|" + str(n) + "| = " + str(n)

def g(n):
 if __debug__:
  if not n > 0:
   raise AssertionError('n must be positive')
 return "|" + str(n) + "| = " + str(n)
  

入出力結果(Terminal)

$ python
Python 3.2.3 (default, Apr 18 2012, 20:17:30) 
[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 sample import f,g
>>> n=10
>>> f(n)
'|10| = 10'
>>> g(n)
'|10| = 10'
>>> n=-10
>>> f(n)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "sample.py", line 5, in f
    assert n > 0, 'n must be positive'
AssertionError: n must be positive
>>> g(n)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "sample.py", line 11, in g
    raise AssertionError('n must be positive')
AssertionError: n must be positive
>>> quit()
$

0 コメント:

コメントを投稿