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

Mik*_*keT 3 python arguments function

正如下面的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".

我如何定义这些变量?如何构造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: '))) 
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 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) 
Run Code Online (Sandbox Code Playgroud)

但分裂也可以起作用:

inputs = raw_input('Enter low,hi,fraction: ')
low, high, fraction = inputs.split(',')
Run Code Online (Sandbox Code Playgroud)

如果用户之间没有准确地给出3个逗号值,那么这将失败.

Python会将您自己的尝试视为传递两个位置参数(传递变量low和值中的值hi),以及一个带有从raw_input()调用中获取的值的关键字参数(一个名为的参数fraction).由于没有变量low,hi你甚至在执行NameError之前就得到了一个变量raw_input().