2015-07-10 126 views
3

由于下面的文档字符串状态,我试图编写一个需要3个参数(浮点数)并返回一个值的Python代码。例如,输入低1.0,高9.0和0.25。这返回3.0,这是1.0和9.0之间的数字的25%。这是我想要的,下面的“回归”方程是正确的。我可以在python shell中运行它,它给了我正确的答案。蟒蛇如何运行与三个输入功能

但是,当我运行此代码,试图提示用户输入时,口口声声说:

“NameError:名字为‘低’没有定义”

我只是想运行它,并获得提示:“Enter low,hi,fraction:”然后用户输入例如“1.0,9.0,0.25”,然后返回“3.0”。

如何定义这些变量?我如何构建打印语句?我如何得到这个运行?

def interp(low,hi,fraction): #function with 3 arguments 


""" takes in three numbers, low, hi, fraction 
    and should return the floating-point value that is 
    fraction of the way between low and hi. 
""" 
    low = float(low) #low variable not defined? 
    hi = float(hi)  #hi variable not defined? 
    fraction = float(fraction) #fraction variable not defined? 

    return ((hi-low)*fraction) +low #Equation is correct, but can't get 
            #it to run after I compile it. 

#the below print statement is where the error occurs. It looks a little 
#clunky, but this format worked when I only had one variable. 

print (interp(low,hi,fraction = raw_input('Enter low,hi,fraction: '))) 
+0

'low,hi,fraction = map(float,raw_input('Enter low,hi,fraction:').split(“,”))' –

+0

谢谢,我也可以使用它!非常感激! – Tyler

回答

6

raw_input()回报只是一个字符串。您需要三次使用raw_input(),或者您需要接受以逗号分隔的值并将其分开。

问3个问题要容易得多:

low = raw_input('Enter low: ') 
high = raw_input('Enter high: ') 
fraction = raw_input('Enter fraction: ') 

print interp(low, high, fraction) 

但拆分可以工作了:

inputs = raw_input('Enter low,hi,fraction: ') 
low, high, fraction = inputs.split(',') 

如果用户不与逗号之间究竟给予3的值。这会失败。

你自己的企图被视为通过Python作为传递两个位置参数(在值通过从变量lowhi),并用来自raw_input()来电的价值关键字参数(参数命名为fraction)。由于没有变量lowhi,在执行raw_input()调用之前,您会得到NameError

+1

你可以解释一下,为什么他的代码*不工作,除了只提供一个输入?查看我对 – WorldSEnder

+0

@WorldSEnder的问题的评论:已添加。 –

+0

嘿,非常感谢您对此的回应。我得到它的工作! – Tyler