2017-10-16 34 views
0
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语句,它要求一系列的输入语句,并把它们全部,并找到所有输入数字的最小值和最大值。任何人都有解决方案?我一直试图解决这个问题一段时间,但没有任何运气。谢谢大家!虽然声明与最小和最大python

+2

如果你想计算出你的所有值的最小/最大跟踪值的(至少他们的最小和最大的),不知何故。 –

+0

我投票结束这个问题,因为这是一个工作要求。 –

+0

我已经到了将所有输入变量保留在输出中的位置,但每当我尝试获取最小值和最大值时,我都会收到来自“停止”的字母作为最小值和最大值。因为stop是while语句的中断。我必须为它找到一些类型的解决方案。 –

回答

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): 
0

缩进在Python中很重要。至于minmax,你可以有两个变量来跟踪这些数字,并继续请求数字直到停止条件。

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) 

这里,第一输入被取为minmax值。请注意,如果用户输入stop作为第一个值,则minmax也将为stop。如果你澄清了更多的用户输入约束条件会更好。

0

正如他们所说,你需要保持list的轨道,以获得minmax。下面的代码结构:

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 
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))