python如何使用三个输入运行函数
正如下面的doc字符串所述,我正在尝试编写一个python代码,它接受3个参数(浮点数)并返回一个值。例如,输入下限为1.0,上限为9.0,分数为0.25。这将返回3.0,即1.0和9.0之间25%的数值。这就是我想要的,下面的“回报”等式是正确的。我可以在python shell中运行它,它给出了正确的答案 但是,当我运行此代码试图提示用户输入时,它一直在说: “名称错误:未定义名称“低” 我只想运行它并得到提示:“输入low,hi,fraction:”然后用户会输入,例如,“1.0,9.0,0.25”,然后返回“3.0” 如何定义这些变量?如何构造print语句?我如何让它运行python如何使用三个输入运行函数,python,function,arguments,Python,Function,Arguments,正如下面的doc字符串所述,我正在尝试编写一个python代码,它接受3个参数(浮点数)并返回一个值。例如,输入下限为1.0,上限为9.0,分数为0.25。这将返回3.0,即1.0和9.0之间25%的数值。这就是我想要的,下面的“回报”等式是正确的。我可以在python shell中运行它,它给出了正确的答案 但是,当我运行此代码试图提示用户输入时,它一直在说: “名称错误:未定义名称“低” 我只想运行它并得到提示:“输入low,hi,fraction:”然后用户会输入,例如,“1.0,9.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: ')))
raw\u input()
只返回一个字符串。您需要使用raw\u 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将您自己的尝试视为传入两个位置参数(传入变量
low
和hi
)的值,以及一个关键字参数,其值取自raw\u input()
调用(一个名为fraction
的参数)。由于没有变量low
和hi
在执行raw\u input()
调用之前,您会得到一个namererror
。除了只给出一个输入之外,您能解释一下为什么他的代码不起作用吗?看我对这个问题的评论嘿,非常感谢你对这个问题的回答。我让它工作了low,hi,fraction=map(float,raw_输入('Enter low,hi,fraction:')。split(“,”)
谢谢,我也可以用这个!非常感谢!