当我尝试将整数乘以字典值(也是整数)时,它给出的答案毫无意义

时间:2017-03-12 03:27:55

标签: python variables dictionary operations

当我运行程序并输入值3,1,1所以将一个杯子换成汤匙时,它使用底部的TOtbsp功能。出于故障排除的目的,我已经在最终结果之前打印出四个变量。这些变量都打印出正确的结果,

System.ComponentModel

^那是TOtbsp功能,出来的是:

将杯子转换为:汤匙

def TOtbsp ():
    os.system('cls')
    print ('Convert ' + convFROMconv + ' to: tablespoons')
    dictEnt = dCallOne['tbsp']
    print (dCallOne['tbsp'])
    print (dCallOne)
    print (dictEnt)
    print (convFactor)
    calc = convFactor * dictEnt
    print(calc)

除最后一个16 {'tbsp': 16, 'tsp': 48, 'quart': 0.25, 'floz': 8.32674, 'pint':0.5,'gal':0.0625, 'ml': 236.588, 'liter': 0.236588} 16 1 1111111111111111 外,这些都是正确的。我尝试过几种不同的方式:

calc

据我所知,由于calc = convFactor * dictEnt calc = (convFactor * dictEnt) calc = (convFactor * dCallOne['tbsp']) calc = (convFactor * (dCallOne['tbsp']) (convFactor * dictEnt) = calc (convFactor * (dCallOne['tbsp']) = calc convFactor * dictEnt = calc (convFactor * dCallOne['tbsp']) = calc convFactordictEnt都得到整数,因此所有这些都可能会得到正确的答案。 p>

完整的代码如下。

dCallOne

2 个答案:

答案 0 :(得分:2)

在Python 3中,input()返回一个字符串(即使用户输入了一个数字),因此convFactor = input('How many?: ')会将convFactor的值设置为字符串。将一个字符串乘以一个数字(如calc = convFactor * dictEnt中所示)只需重复多次重复该字符串,因此您最终得到十六1个字符串。要解决此问题,请使用int()convFactor转换为数字,最好是在调用input()之后:

convFactor = int(input('How many?: '))

答案 1 :(得分:1)

jwodder回答了你的问题:如果你想用它们进行算术运算,你需要将输入字符串转换为数字。您可以使用int()进行转化,但最好使用float():这样可以让用户输入小数。

但是,您的程序有批次重复。这是好的设计。它使程序比它需要的时间更长,并且使得它更难以阅读和维护。读者必须弄清楚哪些位应该是相同的,哪些位应该是不同的。当你想进行修改时,你必须将修改复制到多个地方,这是繁琐且容易出错的。请参阅维基百科文章Don't repeat yourself

这是您程序的更紧凑版本。我做的主要改变是将所有单独的转换率字典放入字典词典中。我使用循环显示单位菜单,而不是单独打印每个单位。我还使用循环来确保我们获得有效的FROM单位,有效的转换金额和有效的TO单位。

此代码将在所有主要操作系统上运行。它是为Python3设计的,但它很容易为Python 2修改。

#!/usr/bin/env python3

''' Volumes conversion calculator 
    See http://stackoverflow.com/q/42743397/4014959

    Written by Ari Madian
    Modified by PM 2Ring 2017.03.12
'''

import os

# Clear the terminal. Works on Windows, Mac, and Linux
def clear(clear_cmd='cls' if os.name == 'nt' else 'clear'):
    os.system(clear_cmd)

# Various conversion ratios, in alphabetical order.
conversion_factors = {
    'cup': {'cup': 1, 'floz': 8.32674, 'gal': 0.0625, 'liter': 0.236588,
        'ml': 236.588, 'pint': 0.5, 'quart': 0.25, 'tbsp': 16, 'tsp': 48},
    'floz': {'cup': 0.125, 'floz': 1, 'gal': 0.0078125, 'liter': 0.0295735,
        'ml': 29.5735, 'pint': 0.0625, 'quart': 0.03125, 'tbsp': 2, 'tsp': 6},
    'gal': {'cup': 16, 'floz': 128, 'gal': 1, 'liter': 3.78541,
        'ml': 3785.41, 'pint': 8, 'quart': 4, 'tbsp': 256, 'tsp': 768},
    'liter': {'cup': 4.226757063, 'floz': 33.814, 'gal': 0.264172, 'liter': 1,
        'ml': 1000, 'pint': 2.11338, 'quart': 1.05669, 'tbsp': 67.628, 'tsp': 202.884},
    'ml': {'cup': 0.0042267571, 'floz': 0.033814, 'gal': 0.000264172, 'liter': 0.001,
        'ml': 1, 'pint': 0.00211338, 'quart': 0.00105669, 'tbsp': 0.067628, 'tsp': 0.202884},
    'pint': {'cup': 2, 'floz': 16, 'gal': 0.125, 'liter': 0.473176,
        'ml': 473.176, 'pint': 1, 'quart': 0.5, 'tbsp': 32, 'tsp': 96},
    'quart': {'cup': 4, 'floz': 32, 'gal': 0.25, 'liter': 0.946353,
        'ml': 946.353, 'pint': 2, 'quart': 1, 'tbsp': 64, 'tsp': 192},
    'tbsp': {'cup': 0.0625, 'floz': 0.5, 'gal': 0.00390625, 'liter': 0.0147868,
        'ml': 14.7868, 'pint': 0.03125, 'quart': 0.015625, 'tbsp': 1, 'tsp': 3},
    'tsp': {'cup': 0.0208333, 'floz': 0.1666666667, 'gal': 0.00130208323, 'liter': 0.00492892, 
        'ml': 4.92892, 'pint': 0.0104166667, 'quart': 0.0052083333, 'tbsp': 0.333333, 'tsp': 1},
}

# Valid menu selections are single digits
menu_numbers = '123456789'

#This is used to check if what the user entered is one of the nine acceptable units
acceptable_inputs = set(menu_numbers)

# Convert menu number to conversion ratio key
units = {
    '1': 'tbsp', '2': 'tsp', '3': 'cup', '4': 'quart', '5': 'floz',
    '6': 'gal', '7': 'ml', '8': 'liter', '9': 'pint',
}

# Short & long unit names, in menu order
unit_names = {
    'tbsp': ('Tbsp', 'Tablespoons'),
    'tsp': ('Tsp', 'Teaspoons'),
    'cup': ('C', 'Cups'),
    'quart': ('qt.', 'Quarts'),
    'floz': ('fl. oz.', 'Fluid Ounces'),
    'gal': ('gal.', 'Gallons'),
    'ml': ('ml', 'Milliliters'),
    'liter': ('L', 'Liters'),
    'pint': ('P', 'Pints'),
}

def get_unit():
    # Display the units menu
    for i in menu_numbers:
        key = units[i]
        short_name, long_name = unit_names[key]
        print('{0} {1} - {2}'.format(i, short_name, long_name))

    # Loop until we get an acceptable input
    while True:
        unit_num = input('Unit: ')
        if unit_num in acceptable_inputs:
            break
        print('Please select a unit by its number')
    return units[unit_num]

# Perform the conversion
def convert(from_key, amount, to_key):
    clear()
    from_name = unit_names[from_key][1]
    to_name = unit_names[to_key][1]
    print('Converting {0} to: {1}'.format(from_name, to_name))

    conv_factor = conversion_factors[from_key][to_key]
    calc = amount * conv_factor
    print(calc)

def main():
    print('Unit Converter\n\n')
    print('Select the unit you want to convert FROM\n')
    from_key = get_unit()

    # Get number to convert. Loop until we get a valid number.
    while True:
        try:
            amount = float(input('How many?: '))
            break
        except ValueError:
            print('Bad number. Please try again.')

    print('Select the unit you want to convert TO\n')
    to_key = get_unit()

    convert(from_key, amount, to_key)


if __name__ == '__main__':
    main()