開発環境
- macOS High Sierra - Apple
- Emacs (Text Editor)
- Python 3.6 (プログラミング言語)
Pythonからはじめる数学入門 (Amit Saha (著)、黒川 利明 (翻訳)、オライリージャパン)の1章(数を扱う)、1.7(プログラミングチャレンジ)、問題1-4(分数電卓)を取り組んでみる。
コード(Emacs)
Python 3
#!/usr/bin/env python3
from fractions import Fraction
def add(a, b):
print(f'Result of Addition: {a + b}')
def sub(a, b):
print(f'Result of Subtraction: {a - b}')
def mul(a, b):
print(f'Result of Multiplication: {a * b}')
def div(a, b):
print(f'Result of Division({a} ÷ {b}): {a / b}')
ops = {'Add': add, 'Subtract': sub, 'Divide': div, 'Multiply': mul}
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: ')
op0 = ops.get(op)
if op0:
op0(a, b)
else:
print(f'Invalid operation: {op}')
except TypeError as err:
print(type(err), err)
except Exception as err:
print(type(err), err)
入出力結果(Terminal, Jupyter(IPython))
$ ./sample4.py Enter first fraction: 3/4 Enter second fraction: 1/4 Operation to perform - Add, Subtract, Divide, Multiply: Add Result of Addition: 1 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 ÷ 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: -1.2 Enter second fraction: 3.4 Operation to perform - Add, Subtract, Divide, Multiply: Divide Result of Division(-6/5 ÷ 17/5): -6/17 Enter first fraction: 1.2 Enter second fraction: -3.4 Operation to perform - Add, Subtract, Divide, Multiply: Divide Result of Division(6/5 ÷ -17/5): -6/17 Enter first fraction: 1.2 Enter second fraction: 3.4 Operation to perform - Add, Subtract, Divide, Multiply: a Invalid operation: a Enter first fraction: 1.2 Enter second fraction: a <class 'ValueError'> Invalid literal for Fraction: 'a' Enter first fraction: q $
0 コメント:
コメントを投稿