需要帮助:Python 2.7.13单位转换

时间:2017-04-18 03:33:26

标签: python python-2.7

下表包含一些以英尺为单位的长度。

1英寸= .083333英尺; 1根杆= 16. 5英尺; 1码= 3.28155英尺; 1 furlong = 660英尺; 1米= 3.28155英尺; 1公里= 3281.5英尺; 1 fathom = 6英尺; 1英里= 5280英尺。

编写一个显示九种不同测量单位的程序;请求单位转换,转换单位和转换数量;然后显示转换后的数量。

使用文件Units.txt创建一个字典,提供给定长度单位的英尺数。

conversions.txt文件显示为:

英寸,.083333;弗隆,660;码,3; f,6;脚,1;公里,3281.5;米,3.2815;英里,5280;棒,16.5

print 'UNITS OF LENGTH'
print 'Inches',     'furlongs',     'yards'
print 'rods',       'miles',        'fathoms'
print 'meters',     'kilometers',   'feet'

conversions = {}
with open('Units.txt') as fname:
    for line in fname:
        (keys, values) = line.split(',')
        conversions[keys] = float(values)
def convert(from_unit, to_unit, values):
    from__unit1 = conversions[from_unit1]
    to__unit2 = conversions[to_unit2]

new_values = values * (from__unit1 / to__unit2)

return str(new_value) + to__unit2

unit1 = raw_input('Units to convert from: ')
unit2 = raw_input('Units to convert to: ')
num1 = raw_input('Enter your value: ')

print(convert(unit1, unit2, (num1)))

1 个答案:

答案 0 :(得分:1)

只看上面的评论。其谚语" NameError:全球名称' from_unit1'"是因为还没有定义from_unit1变量。

我假设您打算访问convert()方法参数,from_unit和to_unit?所以它可能看起来像这样:

def convert(from_unit, to_unit, values):
    from__unit1 = conversions[from_unit]
    from__unit2 = conversions[to_unit]

函数内部使用的变量必须与传入的参数匹配,或者必须在文件中的某处声明。如果在函数外部的文件中声明,对于Python 2x,则需要将" global variable_name"在函数开头没有引号

编辑:

我接下来要做的就是将这两行放在convert()中:

new_values = values * (from__unit1 / to__unit2)
return str(new_value) + to__unit2

原因是无法在函数外部访问from_unit1和to__unit2这两个变量。它们是在函数内部创建的,一旦函数完成所有步骤,变量就会消失。

所以函数看起来应该是这样的:

def convert(from_unit, to_unit, values):
    from__unit1 = conversions[from_unit]
    from__unit2 = conversions[to_unit]
    new_values = values * (from__unit1 / to__unit2)
    return str(new_value) + to__unit2

我认为应该打印出所需的结果。让我们知道:))