当我尝试从英制单位转换为公制时出错,反之亦然地使用类似的代码?



我是python3中的菜鸟。我的问题是以下代码: 它说"无 m",例如,当我尝试从 ft 转换为 m 时,所有其他转换都可以正常工作。

我尝试用字典解决它,就像公制到公制转换一样,但我不能,因为那样我将无法获得英制到英制转换的正确结果。

# def distance_converterv2():
metric = ["km", "m", "dm", "cm", "mm"]
imperial = ["ft", "in", "mi"]

def convert_v2(val, unit_in, unit_out):
final = 0.0
m = 0.0
si = {'mm': 0.001, 'cm': 0.01, 'dm': 0.1, 'm': 1.0, 'km': 1000.0}
if (unit_in and unit_out) in metric:
final = val*(si[unit_in]/si[unit_out])
if unit_in and unit_out in imperial:
if unit_in in ['ft'] and unit_out in ['in']:
final = val * 12
if unit_in in ['in'] and unit_out in ['ft']:
final = val / 12
if unit_in in ['ft'] and unit_out in ['mi']:
final = val / 5280
if unit_in in ['mi'] and unit_out in ['ft']:
final = val * 5280
if unit_in in metric and unit_out in imperial:
if unit_out in ['ft']:
m = val*3.28084
if unit_out in ['in']:
m = val*39.37008
if unit_out in ['mi']:
m = val/1609.34
final = m * si[unit_in]
if unit_in in imperial and unit_out in metric:
si = {'mm': 0.001, 'cm': 0.01, 'dm': 0.1, 'm': 1.0, 'km': 1000.0}
if unit_in in ['ft']:
m = val / 3.28084
if unit_in in ['in']:
m = val / 39.37008
if unit_in in ['mi']:
m = val * 1609.34
final = m / si[unit_out]
return final

def isfloat(string):
try:
float(string)
return True
except ValueError:
return False

print("""
Welcome to Saguaro's unit converter!
First, enter the unit you want to convert from, then the unit you want to convert to
The options are: 
mm, cm, dm, m, km
ft, inch, mile
Whenever You want to go back press B and enter
""")
value = 0
unit_in = ""
unit_out = ""

while True:
unit_in = input("Unit you want to convert from: ")
if unit_in in ["B", "b", "Back", "back"]:
break
unit_out = input("Unit you want to convert to: ")
if unit_out in ["B", "b", "Back", "back"]:
break
value = input("Value to convert: ")
if value in ["B", "b", "Back", "back"]:
break
elif isfloat(value):
value = float(value)
result = convert_v2(value, unit_in, unit_out)
print(result, unit_out)
else:
print("You have entered a wrong value")

我要做的是不使用单位列表,检查单位是否等于字符串。

#do this:
if unit_in == 'm' and unit_out == 'ft':
#do the conversion here.
#instead of this:
if unit_in in ['m'] and unit_out in ['ft']
#do the conversion here.

注释。 习惯上提到这是家庭作业还是学校项目。 我认为安德森@G指出了实际问题——你对"和"的误用/误解。 虽然python很好,逻辑表达式听起来像英语句子,但你确实需要考虑表达式的每个部分的作用。

本着为刚接触python和编程的人提供指导的精神,我建议其他一些事情。 我不喜欢分散在我的代码中的字符串常量。 如果你在一个地方错误地输入'mm''mn',这可能是一个很难发现的错误,因为解释器没有看到任何错误。 但是像MN这样拼写错误的变量是一个错误。

我还添加了一些验证例程,因为还有一些问题,即您静默地允许像fr一样输入无效单元 - 我没有查看代码在这种情况下的作用。

我也认为你应该一致地使用引号(所有'"),除非有某种原因。 大多数(?)人标准化为"但我喜欢'因为它避免了shift键... :-)

最后,我认为如果你稍微考虑一下这个问题,你会发现很多条件逻辑都是不需要的。ft转换为in实际上与ft转换为cmft转换为mi相同。 我认为当你考虑使用字典时,你走在正确的轨道上。想想如果换算表告诉您(例如)公里中有多少(单位),它会是什么样子。

# def distance_converterv2():
# Use "constants" to prevent errors like a typo somewhere 'mn'
#  that can be hard to see.  Undefined var MN will be detected by interpreter
METRIC = KM, M, DM, CM, MM = ('km', 'm', 'dm', 'cm', 'mm')
IMPERIAL = FT, IN, MI = ('ft', 'in', 'mi')
VALID_UNITS = METRIC + IMPERIAL

def valid(unit):
if unit not in VALID_UNITS:
print('Invalid: ' + unit + ', must be in ' + ' '.join(VALID_UNITS))
return False
return True
def convert_v2(val, unit_in, unit_out):
final = 0.0
m = 0.0
si = {MM: 0.001, CM: 0.01, DM: 0.1, M: 1.0, KM: 1000.0}
if unit_in in METRIC and unit_out in METRIC:   # Per @ G. Anderson
final = val*(si[unit_in]/si[unit_out])
if unit_in in IMPERIAL and unit_out in IMPERIAL:   # Per @ G. Anderson
if unit_in in [FT] and unit_out in [IN]:
final = val * 12
if unit_in in [IN] and unit_out in [FT]:
final = val / 12
if unit_in in [FT] and unit_out in [MI]:
final = val / 5280
if unit_in in [MI] and unit_out in [FT]:
final = val * 5280
if unit_in in METRIC and unit_out in IMPERIAL:
if unit_out in [FT]:
m = val*3.28084
if unit_out in [IN]:
m = val*39.37008
if unit_out in [MI]:
m = val/1609.34
final = m * si[unit_in]
if unit_in in IMPERIAL and unit_out in METRIC:
si = {MM: 0.001, CM: 0.01, DM: 0.1, M: 1.0, KM: 1000.0}
if unit_in in [FT]:
m = val / 3.28084
if unit_in in [IN]:
m = val / 39.37008
if unit_in in [MI]:
m = val * 1609.34
final = m / si[unit_out]
return final

def isfloat(string):
try:
float(string)
return True
except ValueError:
return False

print('''
Welcome to Saguaro's unit converter!
First, enter the unit you want to convert from, then the unit you want to convert to
The options are: 
mm, cm, dm, m, km
ft, inch, mile
Whenever You want to go back press B and enter
''')
value = 0
unit_in = ''
unit_out = ''

while True:
unit_in = input('Unit you want to convert from: ')
if unit_in in ['B', 'b', 'Back', 'back']:
break
if not valid(unit_in):
continue
unit_out = input('Unit you want to convert to: ')
if unit_out in ['B', 'b', 'Back', 'back']:
break
if not valid(unit_out):
continue
value = input('Value to convert: ')
if value in ['B', 'b', 'Back', 'back']:
break
elif isfloat(value):
value = float(value)
result = convert_v2(value, unit_in, unit_out)
print(result, unit_out)
else:
print('You have entered a wrong value')

相关内容

最新更新