我没有这个简单的循环练习

时间:2018-09-23 18:21:45

标签: python loops for-loop max min

我必须编写一个程序来计算并显示te用户输入的最高和第二最高值。该程序还必须使用输入的零或一值。

以下是一些示例运行:

enter a value or 'stop' -3.2
enter a value or 'stop' -5.6
enter a value or 'stop' 0.5
enter a value or 'stop' 0.3
enter a value or 'stop' stop
the highest value = 0.5
the second highest value = 0.3

enter a value or 'stop' stop
the highest value could not be calculated
the second highest value could not be calculated

所以我得到了一个代码,但是它只给了我最小和最大。 到目前为止,我所得到的只是这个:

minimum = None
maximum = None
a = int(input("Enter a value or 'stop': "))
while True:
    a = input("Enter a value or stop: ")
    if a == 'stop':
        break
    try:
        number = int(a)
    except:
        print("Invalid input")
        continue
    if minimum is None or number < minimum:
        minimum = number
    if maximum is None or number > maximum:
        maximum = number
print('Maximum= ', maximum)
print('Minimum= ', minimum)

如果有人可以帮助我,那将很棒!

3 个答案:

答案 0 :(得分:1)

value_list = list()
while True:
    a = input("Enter a value or stop: ")
    if a == 'stop':
        break
    else:
        try:
            value_list.append(float(a))
        except:
            print("Invalid input")
            continue
sorted_list = sorted(value_list)
if len(sorted_list) > 0:
    print('the highest value = ', sorted_list[-1])
else:
    print('the highest value could not be calculated')
if len(sorted_list) > 1:
    print('the second highest value = ', sorted_list[-2])
else:
    print('the second highest value could not be calculated')

这应该有效。您可能要处理float / int情况

因此,代码实际上使用Python列表以float形式存储输入值。一旦用户进入停止位置,我们就会按升序对列表中的值进行排序,最后仅显示前两个值,即索引-1和-2。享受吧!

答案 1 :(得分:0)

正如@rkta所说,您不需要第3行(因为该程序在启动时会询问相同的问题两次)。

您只需要稍微更改代码即可获得所需的程序。代替使用此块:

undefined
0
1
2
3
4
5
6
7
8
9
10
11
12
length
item
namedItem

使用此块:

Undefined

很显然,您需要在程序的开头将“ highest”和“ second_highest”设置为“ None”,并在结尾处更改打印语句。

答案 2 :(得分:0)

我加两分钱:

# declare a list
inputs = []

while True:
    a = input("Enter a value or stop: ")
    if a == 'stop':
        break
    try:
        # check if input is float or integer
        if isinstance(a, int) or isinstance(a, float):
            # append number to the list
            inputs.append(a)
    except:
        print("Invalid input")
        continue

# sort list  
inputs = sorted(inputs)

# print result if list has at least two values
if len(inputs) >= 2:
    # cut the list to the last two items
    maxs = inputs[-2:]
    print 'Max 1 = ',  maxs[1]
    print 'Max 2 =',  maxs[0]
else:
    print 'not enough numbers'