Search code examples
python-3.xsystemphysicscs50metric

How to multiply input given by user for metric system calculator


I am working on a metric system converter for class using python3 in cs50 but I am having some troubles. Basically, I want the user to input a number(value) and then he'd choose the prefix of measurement(ex: kilo, milli, micro, etc) and when the person does this it multiplies or divides the value by a number to convert it into the requested unit of measurement. For example, if they wanted to convert centimeters to kilometers i want the user to input for example 200 centimeters and then for a function to divide that by 1000 to get 0.002km and to print it to the user. But I have no idea how to go about this. Any help would be appreciated.


Solution

  • I'm not trying to do your homework, but this should give you a first idea:

    factor = {'km': 3,
              'm': 0,
              'dm': -1,
              'cm': -2,
              'mm': -3}  # dictionary with powers, e.g. 1 km = 10**3 m
    # For your example of 200 cm = 0.002 km, you type...
    number = float(input('numerical value: '))  # 200
    unit = input('unit: ')  # cm
    target_unit = input('target unit: ')  # km
    
    print(number * 10**factor[unit] / 10**factor[target_unit], target_unit)