How can I associate pairs of values and look up the second given the first?

Viewed 58

I am just starting with python coding and I wanted to start with something really easy. Just a calculator that can calculate the area of a circle with a radius from input. Also I wanted to involve units into it and here comes the problem.

As you can see in the 4th row my code asks for the unit which the user wants to use. If the user wants to choose centimeters he writes 1 (also I want to make the user to choose from the listed units) but at the end the result comes with 1 behind the number because he only writed 1 (not centimeters).

import math

r = float(input("What is the radius of your circle?"))
unit = str(input("Choose the unit of measurement" '\n' "1) centimeters" '\n' "2) meters" '\n' "3) inches"))
result = (math.pi * r ** 2)


print("The area of your circle with radius of " + str(r) + " is:" '\n' + str(result) + " " + unit)

How can I make the code write the result with the shorten version of the units - cm, m, in? I wanted to create something like this:

if unit == "1"
    unit == "cm"

But that is too verbose.

2 Answers

You can create dictionary like below:

dct_unit = {'1':'cm', '2':'m'}

Whole code:

import math

r = float(input("What is the radius of your circle?"))
unit = str(input("Choose the unit of measurement" '\n' "1) centimeters" '\n' "2) meters" '\n' "3) inches"))
result = (math.pi * r ** 2)

dct_unit = {'1':'cm', '2':'m'}

print("The area of your circle with radius of " + str(r) + " is:" '\n' + str(result) + " " + dct_unit[unit])

The easiest way I can think of to get the desired output would be to create a dictionary and map the number with the correct units.

import math

r = float(input("What is the radius of your circle?"))
unit = int(input("Choose the unit of measurement" '\n' "1) centimeters" '\n' "2) meters" '\n' "3) inches"))
result = (math.pi * r ** 2)

UNIT_OPTION_TO_TEXT_MAP = {
1:'centimeters squared',
2:'meters squared',
3:'inches squared',
}

print("The area of your circle with radius of " + str(r) + " is:" '\n' + str(result) + " " + UNIT_OPTION_TO_TEXT_MAP.get(unit,'centimeters squared'))
Related