问题描述
我想修改此代码,以便它反复询问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'
来创建中断,但似乎无法使其正常工作。
1楼
从print y
行看,您好像正在使用Python 2.7或更早版本,因此input("x = ")
很有可能会响应您输入stop
的情况,但出现NameError: name 'stop' is not defined
异常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...