将约定与数字分开,以便我可以运行将毫米转换为英寸的公式



我正在学习python,我很难使用练习表,我试图将毫米转换为英寸,反之亦然。我正在基于类似的脚本构建它,该脚本将华氏度转换为摄氏度(反之亦然(。

下面是将 F 转换为 F <-> C 的脚本:

temp = input("Input the  temperature you like to convert? (e.g., 45F, 102C etc.) : ")
degree = int(temp[:-1])
i_convention = temp[-1]
if i_convention.upper() == "C":
result = int(round((9 * degree) / 5 + 32))
o_convention = "Fahrenheit"
elif i_convention.upper() == "F":
result = int(round((degree - 32) * 5 / 9))
o_convention = "Celsius"
else:
print("Input proper convention.")
quit()
print("The temperature in", o_convention, "is", result, "degrees.")

我根据上面的一个写了这个:

meas = input("Convert mm to in and vice versa, enter a value (e.g. 10mm, 2in): n")
num = int(meas[:-2])
i_measType = meas[-2]
if i_measType.upper() == "MM":
result = int((num * (1/25.4)))
o_measType = "in"
elif i_measType.upper() == "IN":
result = int((num * 25.4))
o_measType = "mm"
else:
print("Input proper convention.")
quit()
print(meas, " = ", result, o_measType)

我认为问题出在[:-2][-2]上,因为根据我所理解的,这部分可能用于从数字中提取约定?我想如果有人输入 44mm,meas[:-2]用于将其转换为 44,而meas[-2]的意思是称呼 mm。但我显然错了...

任何帮助和可能的解释将不胜感激。

错误是:

ValueError: invalid literal for int() with base 10:

meas[-2] 是输入字符串 meas 中倒数第二个字符,在您的情况下,它可以是"m"或"i"。这是一个单一的角色。

您可以将 if/else 条件更改为 如果 i_measType.upper(( == "M" ...

或更改i_measType = [-2:] 来解决问题。

相关内容

最新更新