while True:
reply = raw_input("Enter text, (type [stop] to quit): ")
print reply.lower()
if reply == 'stop':
break
x = min(reply)
y = max(reply)
print("Min is " + x)
print("Max is " + y)
我试图创建一个包含while语句的语句,在该语句中它会询问一系列输入语句并将它们全部取出并找到所有输入数字的最小值和最大值。有人有任何解决方案?我一直试图解决这个问题一段时间没有运气。谢谢大家!
答案 0 :(得分:0)
缩进在Python中很重要。对于min
和max
,您可以使用两个变量来跟踪这些数字并继续请求数字直到停止条件。
min = max = userInput = raw_input()
while userInput != "stop":
if int(userInput) < int(min):
min = int(userInput)
elif int(userInput) > int(max):
max = int(userInput)
userInput = raw_input()
print "Min is "+str(min)
print "Max is "+str(max)
此处,第一个输入被视为min
和max
值。请注意,如果用户输入stop
作为第一个值,min
和max
也将是stop
。如果您澄清了更多用户输入约束,那就更好了。
答案 1 :(得分:0)
这是另一种方法。
while True:
reply = raw_input("Enter numbers separated by commas. (type [stop] to quit): ")
user_input = reply.split(',')
if reply == 'stop':
break
x = map(float, user_input)
y = map(float, user_input)
values = (x, y)
print("Min is " + str(min(x)))
print("Max is " + str(max(y)))
输入:
5, 10, 5000
输出:
Enter numbers separated by commas. (type [stop] to quit): 5, 10, 5000
Min is 5.0
Max is 5000.0
Enter numbers separated by commas. (type [stop] to quit):
答案 2 :(得分:0)
正如他们所提到的,您需要跟踪list
以获取min
和max
。遵循您的代码结构:
l = []
while True:
reply = raw_input("Enter text, (type [stop] to quit): ")
print reply.lower()
if reply == 'stop':
break
l.append(int(reply)) #store the values
x = min(l)
y = max(l)
print "Min is ", x
print "Max is ", y
IMP:不要忘记int
转化
您可以尝试的另一种space conservative
方法是在获得输入时计算最小值和最大值。
import sys
#placeholders
maximum = -(sys.maxint) - 1 #highest negative value
minimum = sys.maxint #highest positive value
while True:
reply = raw_input("Enter text, (type [stop] to quit): ")
print reply.lower()
if reply == 'stop':
break
reply=int(reply)
if reply<minimum :
minimum = reply
if reply>maximum :
maximum = reply
print "Min is ", minimum
print "Max is ", maximum
答案 3 :(得分:0)
你的想法是正确的。你还没有使用min max作为变量名,这也很棒。如果你使用python 3,请在下面的代码中用 raw_input 替换输入关键字。
希望它有效! :)
minn=5000;
maxx=0;
while True:
reply = input("Enter text, (type [stop] to quit): ")
if int(reply) < int(minn):
minn = int(reply)
if int(reply) > int(maxx):
maxx = int(reply)
if reply == 'stop':
break
print("Min is " + str(minn))
print("Max is " + str(maxx))