2018年3月30日金曜日

開発環境

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 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: ')
            if op == 'Add':
                add(a, b)
            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)

入出力結果(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 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
Operation to perform - Add, Subtract, Divide, Multiply: Add
Result of Addition: 19/4
Enter first fraction: 3.4
Enter second fraction: 4
Operation to perform - Add, Subtract, Divide, Multiply: Add
Result of Addition: 37/5
Enter first fraction: a
Invalid literal for Fraction: 'a'
Enter first fraction: q
$

0 コメント:

コメントを投稿

関連コンテンツ