2016年12月31日土曜日

開発環境

Python Crash Course (Eric Matthes (著)、No Starch Press)のPART1(BASICS)、Chapter 10.(FILES AND EXCEPTIONS)のTRY IT YOURSELF 10-6、7、8、9、10(No.5828)を取り組んでみる。

TRY IT YOURSELF 10-6、7、8、9、10(No.5828)

コード(Emacs)

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

print('10-6, 7')

while True:
    a = input('a: ')
    b = input('b: ')
    try:
        a = int(a)
        b = int(b)
    except Exception as err:
        print(err)
    else:
        print('a + b = {}'.format(a + b))
        break

print('10-8, 9')

for filename in ['cats.txt', 'dogs.txt', 'other']:
    print(filename)
    try:
        with open(filename) as f:
            for cat in f:
                cat = cat.strip()
                print(cat)
    except Exception as err:
        print(err)

print('10-10')

total = 0
with open('book.txt') as f:
    for line in f:
        total += line.lower().count('the')
print(total)

入出力結果(Terminal, IPython)

$ ./sample6.py
10-6, 7
a: a
b: 2
invalid literal for int() with base 10: 'a'
a: 1
b: b
invalid literal for int() with base 10: 'b'
a: a
b: b
invalid literal for int() with base 10: 'a'
a: 1
b: 2
a + b = 3
10-8, 9
cats.txt
cat1
cat2
cat3
dogs.txt
dog1
dog2
dog3
other
[Errno 2] No such file or directory: 'other'
10-10
727
$

0 コメント:

コメントを投稿

Comments on Google+: