简体   繁体   中英

python how run function with three inputs

As the doc string below states, I'm trying to write a python code that takes 3 arguments (float numbers) and returns one value. For example, input low of 1.0, hi of 9.0 and a fraction of 0.25. This returns 3.0 which is the number 25% of the way between 1.0 and 9.0. This is what I want, the "return" equation below is correct. I can run it in an python shell and it gives me the correct answer.

But, when I run this code to try to prompt user inputs, it keeps saying:

"NameError: name 'low' is not defined"

I just want to run it and get the prompt: "Enter low, hi, fraction: " and then the user would enter, for example, "1.0, 9.0, 0.25" and then it would return "3.0".

How do I define these variables? How do I construct the print statement? How do I get this to run?

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_input() returns just one string. You'll either need to use raw_input() three times, or you need to accept comma-separated values and split those out.

Asking 3 questions is much easier:

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

print interp(low, high, fraction) 

but splitting can work too:

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

This'll fail if the user doesn't give exactly 3 values with commas in between.

Your own attempt was seen by Python as passing in two positional arguments (passing in the values from the variables low and hi ), and a keyword argument with the value taken from a raw_input() call (an argument named fraction ). Since there are no variables low and hi you'd get a NameError before the raw_input() call even is executed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM