【问题标题】:How can I associate pairs of values and look up the second given the first?如何关联成对的值并在给定第一个的情况下查找第二个?
【发布时间】:2021-09-11 16:02:58
【问题描述】:

我刚开始使用 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"

但这太冗长了。

【问题讨论】:

  • 你为什么要一个数字而不是单位本身?
  • 使用字典。

标签: python calculator


【解决方案1】:

您可以像下面这样创建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])

【讨论】:

    【解决方案2】:

    我能想到的获得所需输出的最简单方法是创建一个字典并将数字映射到正确的单位。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-01
      • 1970-01-01
      • 2017-02-07
      • 1970-01-01
      • 2023-02-09
      • 1970-01-01
      相关资源
      最近更新 更多