Python,公制转换程序,没有字典

时间:2017-10-15 13:44:54

标签: python

我制作了一个将一个测量值转换为另一个测量值的代码。 (我不允许使用字典) 我一直收到一条错误消息:NameError:名称'num2'未定义,这意味着第二个循环中的if语句永远不会变为真我猜。不过,我不知道出了什么问题。

任何想法将不胜感激。谢谢!

# Metric conversion program

def displayWelcome():
    print('This program converts convert one length unit into another unit')
    print('Following are the available units: (mm), (cm), (m), (km), (inches), (ft), (yds), (miles)')

def getConvertfrom():
    which1 = input('Which unit would you like to convert from: ')

def getConvertto():    
    which2 = input ('Which unit would you like to convert to: ')


num1 = float(input('Enter a value: '))

available_units = ('mm', 'cm', 'm', 'km', 'inches', 'ft', 'yds', 'miles')
conversions = (1, 10, 1000, 1e6, 25.4, 304.8, 914.4, 1.609344e6)

# Display program welcome
displayWelcome()

# Get which conversion
which1 = getConvertfrom()
which2 = getConvertto()



index = 0
for i in range (0, len(available_units)):
    if available_units[i] == str(which1):
        num_in_mm = num1 * conversions[i]

for j in range (0, len(available_units)):
    if available_units[j] == str(which2):
        num2 = num_in_mm / conversions[j]

print(num1, which1, "is equal to", num2, which2)

1 个答案:

答案 0 :(得分:0)

这是您的代码,在获取用户输入方面做了一些小的更改(使用raw_input)。此外,返回您的输入,在您的情况下which1which2None(因为您尝试在函数范围内设置变量):

# Metric conversion program

def displayWelcome():
    print('This program converts convert one length unit into another unit')
    print('Following are the available units: (mm), (cm), (m), (km), (inches), (ft), (yds), (miles)')

def getConvertfrom():
    return raw_input('Which unit would you like to convert from: ')

def getConvertto():
    return raw_input('Which unit would you like to convert to: ')


num1 = float(raw_input('Enter a value: '))

available_units = ('mm', 'cm', 'm', 'km', 'inches', 'ft', 'yds', 'miles')
conversions = (1, 10, 1000, 1e6, 25.4, 304.8, 914.4, 1.609344e6)

# Display program welcome
displayWelcome()

# Get which conversion
which1 = getConvertfrom()
which2 = getConvertto()

index = 0
for i in range (0, len(available_units)):
    print available_units[i], '==', str(which1)
    if available_units[i] == str(which1):
        num_in_mm = num1 * conversions[i]

for j in range (0, len(available_units)):
    if available_units[j] == str(which2):
        num2 = num_in_mm / conversions[j]

print(num1, which1, "is equal to", num2, which2)

这是将mm值转换为cm的脚本示例输出:

$ python testtest.py
Enter a value: 1000
This program converts convert one length unit into another unit
Following are the available units: (mm), (cm), (m), (km), (inches), (ft), (yds), (miles)
Which unit would you like to convert from: mm
Which unit would you like to convert to: cm
given params: which1: mm, which2: cm
mm == mm
cm == mm
m == mm
km == mm
inches == mm
ft == mm
yds == mm
miles == mm
(1000.0, 'mm', 'is equal to', 100.0, 'cm')

NB: input等于eval(raw_input(prompt)),您不需要这样做,因为它有其他用例,您必须在引号中体现您的输入字符串!只需使用raw_input。