## 2018年3月30日金曜日

### Python - 数学 - 数を扱う - 分数電卓(加法、減法、除法、乗法(和、差、商、積)、例外処理、if/elif/elseステートメント、try/exceptステートメント、標準ライブラリ(fractions module、Fraction))

Pythonからはじめる数学入門 (Amit Saha (著)、黒川 利明 (翻訳)、オライリージャパン)の1章(数を扱う)、1.7(プログラミングチャレンジ)、問題1-4(分数電卓)を取り組んでみる。

コード(Emacs)

Python 3

```#!/usr/bin/env python3

from fractions import Fraction

def sub(a, b):
print(f'Result of Subtraction: {a - b}')

def div(a, b):
print(f'Result of Division({a} by {b}): {a / b}')

def mul(a, b):
print(f'Result of Multiplication: {a * b}')

if __name__ == '__main__':
while True:
try:
a = input('Enter first fraction: ')
if a == 'q':
break
a = Fraction(a)
b = Fraction(input('Enter second fraction: '))
op = input(
'Operation to perform - Add, Subtract, Divide, Multiply: ')
elif op == 'Subtract':
sub(a, b)
elif op == 'Divide':
div(a, b)
elif op == 'Multiply':
mul(a, b)
else:
raise Exception(f'Invalid operation: {op}')
except Exception as err:
print(err)
```

```\$ ./sample4.py
Enter first fraction: 3/4
Enter second fraction: 1/4
Enter first fraction: 3/4
Enter second fraction: 1/4
Operation to perform - Add, Subtract, Divide, Multiply: Subtract
Result of Subtraction: 1/2
Enter first fraction: 3/4
Enter second fraction: 1/4
Operation to perform - Add, Subtract, Divide, Multiply: Divide
Result of Division(3/4 by 1/4): 3
Enter first fraction: 3/4
Enter second fraction: 1/4
Operation to perform - Add, Subtract, Divide, Multiply: Multiply
Result of Multiplication: 3/16
Enter first fraction: 3/4
Enter second fraction: 1/4
Operation to perform - Add, Subtract, Divide, Multiply: A
Invalid operation: A
Enter first fraction: 3/4
Enter second fraction: 4