gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 13:40:56 24 4
gpt4 key购买 nike

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

但是,当我运行这段代码来尝试提示用户输入时,它一直在说:

“名称错误:未定义名称‘低’”

我只想运行它并得到提示:“输入低、高、分数:”然后用户输入,例如“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: ')))

最佳答案

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 甚至是执行。

关于python如何使用三个输入运行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31351171/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com