python如何用三个输入运行函数

时间:2015-07-10 22:16:38

标签: python function arguments

正如下面的doc字符串所述,我正在尝试编写一个带有3个参数(浮点数)并返回一个值的python代码。例如,输入低1.0,hi为9.0,分数为0.25。这将返回3.0,这是1.0和9.0之间的数字的25%。这就是我想要的,下面的“返回”等式是正确的。我可以在python shell中运行它,它给了我正确的答案。

但是,当我运行此代码以尝试提示用户输入时,它会一直说:

“NameError:名称'低'未定义”

我只想运行它并得到提示:“输入low,hi,fraction:”然后用户输入例如“1.0,9.0,0.25”然后它将返回“3.0”。< / p>

如何定义这些变量?如何构造print语句?我如何让它运行?

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: '))) 

1 个答案:

答案 0 :(得分: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中的值),以及一个关键字参数,其值来自{{1调用(名为raw_input()的参数)。由于没有变量fractionlow,因此在执行hi调用之前您将获得NameError

相关问题