2015-07-10 81 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