python - 如何关联成对的值并在给定第一个的情况下查找第二个?
问题描述
我刚开始使用 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"
但这太冗长了。
解决方案
您可以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])
推荐阅读
- c - 使用 CreateThread() 在 Windows 中创建线程的时间很荒谬
- bash - /bin/sh:设置 docker-compose 入口点时没有这样的文件或目录
- jsf - 如何在 JSF 中 @WebFilter 重定向后修复空白页?
- reactjs - React 包包含哪些方法和对象?
- javascript - 试图从没有正确“允许”属性的帧中调用 enumerateDevices
- xamarin.forms - 从 Android 设置中清除 Xamarin.forms 应用程序的数据使应用程序无响应
- xcode - 如何使用 opendiff 和 git diff 而无需安装整个 Xcode 应用程序?
- python - Python 需要一个缩进的块 kkk
- c# - A* 是否能够处理多个层次(例如:多层建筑)?
- python - 使用 plt.show() -> MemoryError 显示图像时:无法分配形状为 (3600, 7200, 4) 且数据类型为 float32 的数组