2017-10-16 37 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))