我正在创建一个可供用户使用的财务建模工具。我希望用户能够通过键入变量名来输入他们想要使用的方法。然而,使用我的代码,raw_input 只是给出了他们输入的字符串,而不是变量名本身
loose = 5
accurate = 10
extreme = 15
method = raw_input('Would you like the calculation to be loose, accurate, or extreme in its precision?: ") #the user would either type loose, accurate, or extreme
calculation = x*y*method #x and y is just a generic calculation and method should be equal to either 5, 10, or 15 based on whether the user chose loose, accurate, or extreme
我收到一条错误消息,指出 method is not an int。我该怎么做才能使它等于上面的松散值、准确值或极值?
请您参考如下方法:
将你的变量变成一个字典,然后根据用户的输入用它来查找相应的整数:
values = {'loose': 5,
'accurate': 10,
'extreme': 15}
method = raw_input('Would you like the calculation to be loose, accurate, or extreme in its precision?: ') #the user would either type loose, accurate, or extreme
calculation = x*y*values[method] #x and y is just a generic calculation and method should be equal to either 5, 10, or 15
您还可以使用 values.get(method, 0) 代替 values[method],如果用户输入的内容不在您的字典中,则 0 将被使用。
