我想修改此代码,以便它反复询问x的不同值,并输出y的相应值。
x1 = input("x1 = ")
x2 = input("x2 = ")
y1 = input("y1 = ")
y2 = input("y2 = ")
x = input("x = ")
y = y1 * ((x-x2)/(x1-x2)) + y2 * ((x-x1)/(x2-x1))
print y
我知道我需要围绕x
输入和函数本身创建一个无限循环,然后您可以通过键入单词来创建中断,例如'Stop'
,但似乎无法使其正常运作。
答案 0 :(得分:0)
从print y
行看起来您使用的是Python 2.7或更早版本,因此input("x = ")
很可能会回复您
使用例外stop
输入NameError: name 'stop' is not defined
。我建议使用raw_input
,它会返回用户的输入
作为一个字符串;你可以检查字符串是否等于字符串
在尝试将其变为浮动之前"stop"
。
强制输入为浮点数也意味着您不必担心整数除法令人困惑(Google from __future__ import division
了解更多信息)。
以下是一个例子:
x1 = float(raw_input("x1 = "))
x2 = float(raw_input("x2 = "))
y1 = float(raw_input("y1 = "))
y2 = float(raw_input("y2 = "))
print 'enter "stop" to end'
while True:
rawx = raw_input("x = ")
if 'stop' == rawx:
print "stopping..."
break
x = float(rawx)
y = y1 * ((x-x2)/(x1-x2)) + y2 * ((x-x1)/(x2-x1))
print y
在我的Ubuntu 14.04系统上使用Python 2.7运行,我得到了这个:
$ python q33264238.py
x1 = 1
x2 = 2
y1 = -1
y2 = 1
enter "stop" to end
x = 1
-1.0
x = 2
1.0
x = 1.5
0.0
x = stop
stopping...