開発環境
- OS X El Capitan - Apple (OS)
 - Emacs (Text Editor)
 - Python 3.5 (プログラミング言語)
 
Doing Math with Python: Use Programming to Explore Algebra, Statistics, Calculus, and More! (Amit Saha (著)、No Starch Press)のChapter 1.(Working with Numbers)、Programming Challenges #3: Enhanced Unit Converter(No. 777)を解いてみる。
#3: Enhanced Unit Converter(No. 777)
コード(Emacs)
  #!/usr/bin/env python3
#-*- coding: utf-8 -*-
K = 0.453592                    # kg/p
def print_menu():
    print('1. Kilogram to Pound')
    print('2. Pound to Kilogram')
    print('3. Celsius to Fahrenheit')
    print('4. Fahrenheit to Celsius')
    
def kg2pound():
    kg = float(input('Enter kg: '))
    p = kg / K
    print('{0}p.'.format(p))
def pound2kg():
    p = float(input('Enter p: '))
    kg = p * K
    print('{0}kg.'.format(kg))
    
def celsius2fahrenheit():
    c = float(input('Enter celsius: '))
    f = c * 9 / 5 + 32
    print('{0} fahrenheit.'.format(f))
def fahrenheit2celsius():
    f = float(input('Enter fahrenheit: '))
    c = (f - 32) * 5 / 9
    print('{0} celsius.'.format(c))
if __name__ == '__main__':
    while True:
        print_menu()
        choice = input('which conversion would you like to do?: ')
        if choice == 'q':
            break
        elif choice == '1':
            kg2pound()
        elif choice == '2':
            pound2kg()
        elif choice == '3':
            celsius2fahrenheit()
        elif choice == '4':
            fahrenheit2celsius()
        else:
            print('Invalid choice: {0}'.format(choice))
入出力結果(Terminal, IPython)
$ ./sample3.py 1. Kilogram to Pound 2. Pound to Kilogram 3. Celsius to Fahrenheit 4. Fahrenheit to Celsius which conversion would you like to do?: 1 Enter kg: 10 22.046244201837776p. 1. Kilogram to Pound 2. Pound to Kilogram 3. Celsius to Fahrenheit 4. Fahrenheit to Celsius which conversion would you like to do?: 2 Enter p: 22.046244201837776 10.0kg. 1. Kilogram to Pound 2. Pound to Kilogram 3. Celsius to Fahrenheit 4. Fahrenheit to Celsius which conversion would you like to do?: 3 Enter celsius: 20 68.0 fahrenheit. 1. Kilogram to Pound 2. Pound to Kilogram 3. Celsius to Fahrenheit 4. Fahrenheit to Celsius which conversion would you like to do?: 4 Enter fahrenheit: 68 20.0 celsius. 1. Kilogram to Pound 2. Pound to Kilogram 3. Celsius to Fahrenheit 4. Fahrenheit to Celsius which conversion would you like to do?: q $
0 コメント:
コメントを投稿