将数字与惯例分开,以便我可以运行将mm转换为英寸的公式

问题描述 投票:0回答:1

我正在学习python,在练习表上遇到了麻烦,我试图将毫米转换为英寸,反之亦然。我正在使用将华氏温度转换为摄氏温度的类似脚本进行构建(反之亦然)。

这里是转换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:

我正在学习python,在练习表上遇到了麻烦,我试图将毫米转换为英寸,反之亦然。我正在使用类似的脚本来转换华氏温度...

python python-3.x literals valueerror
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.