開発環境
- OS X Mavericks - Apple(OS)
- Emacs (CUI)、BBEdit - Bare Bones Software, Inc. (GUI) (Text Editor)
- Python 3.4 (プログラミング言語)
Learning Python (Mark Lutz (著)、Oreilly & Associates Inc)のPART Ⅱ.(Types and Operations)、Test Your Knowledge: Part II Exercises 7.(Generic operations)を解いてみる。
その他参考書籍
- Pythonチュートリアル 第2版
- Python クックブック 第2版 (原書(最新版))
- Programming Python
- Python Pocket Reference (Pocket Reference (O'Reilly))
7.(Generic operations)
コード(BBEdit)
sample7.py
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
print('a.')
# TypeError
try:
a = 'k' + [1]
except Exception as err:
print(type(err), err)
try:
a = [1] + (1,)
except Exception as err:
print(type(err), err)
print('b.')
# doesn't work
# TypeError
try:
d = {'a':1} + {'b':2}
except Exception as err:
print(type(err), err)
print('c.')
# does't work
# work for lists
l = ['a']
print(l)
l.append(1)
print(l)
# does't work for strings
# AttributeError
try:
s = 'a'
s.append('b')
except Exception as err:
print(type(err), err)
print('d.')
# two lists, get list
# two strings, get strings
l1 = ['a']
l2 = ['b']
l3 = l1 + l2
l4 = l3[:]
print(l3, type(l3))
print(l4, type(l4))
s1 = 'a'
s2 = 'b'
s3 = s1 + s2
s4 = s3[:]
print(s3, type(s3))
print(s4, type(s4))
入出力結果(Terminal, IPython)
$ ./sample7.py a. <class 'TypeError'> Can't convert 'list' object to str implicitly <class 'TypeError'> can only concatenate list (not "tuple") to list b. <class 'TypeError'> unsupported operand type(s) for +: 'dict' and 'dict' c. ['a'] ['a', 1] <class 'AttributeError'> 'str' object has no attribute 'append' d. ['a', 'b'] <class 'list'> ['a', 'b'] <class 'list'> ab <class 'str'> ab <class 'str'> $
0 コメント:
コメントを投稿