首页 > 解决方案 > 如何关联成对的值并在给定第一个的情况下查找第二个?

问题描述

我刚开始使用 python 编码,我想从一些非常简单的东西开始。只是一个计算器,可以根据输入计算半径为圆的面积。我也想让单位参与其中,问题就来了。

正如您在第 4 行中看到的那样,我的代码询问用户想要使用的单位。如果用户想选择厘米,他会写 1(我也想让用户从列出的单位中选择),但最后结果会在数字后面加上 1,因为他只写了 1(不是厘米)。

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)

如何使代码使用单位的缩短版本 - cm、m、in 编写结果?我想创建这样的东西:

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

但这太冗长了。

标签: pythoncalculator

解决方案


您可以dictionary像下面这样创建:

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

整个代码:

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])

推荐阅读