使用raw_input获取用户输入变量名称并使用其值

时间:2015-03-24 19:21:44

标签: python raw-input

我正在创建一个用户可以使用的财务建模工具。我希望用户能够通过键入变量名来输入他们想要使用的方法。但是,使用我的代码,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

我收到错误,说方法不是int。我能做些什么来使它等于上面的松散,准确或极端值?

3 个答案:

答案 0 :(得分:6)

将变量更改为字典,然后根据用户的输入使用它来查找相应的整数:

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

答案 1 :(得分:1)

最好的一种方式是:

loose = 5
accurate = 10
extreme = 15

method_selection = raw_input('Would you like the calculation to be loose, accurate, or extreme in its precision?: ')

if method_selection == "loose":
    method = loose
elif method_selection == "accurate":
    method = accurate
else:
    method = extreme

calculation = x*y*method

调整if语句的顺序,为你提供正确的“默认”(即某人放入的方法不符合你的一个)。

答案 2 :(得分:0)

直接解决方案是使用eval

method = eval(raw_input(...))

请注意,建议不要使用eval,因为它可以让用户自由地执行他/她想要的任何内容。

相关问题