最大,最小和总数

时间:2013-11-15 15:56:50

标签: python

使用python的最大,最小和总数。例如:

>>>maxmin()
Enter integers, one per line, terminated by -10 :
2    
1    
3    
7    
8    
-10


Output : total =5, minimum=1, maximum = 8

这是我的代码。我需要一些帮助。

def maxmin():
    minimum = None
    maximum = None

    while (num != -10):
    num = input('Please enter a number, or -10 to stop: ' )
        if num == -10:
            break

        if (minimum) is None or (num < minimum):
            minimum = num
        if (maximum) is None or (num > maximum):
            maximum = num
    print ("Maximum: ", maximum)
    print ("Minimum: ", minimum)

4 个答案:

答案 0 :(得分:3)

def maxmintotal():
    num = 0
    numbers = []
    while True:
         num = int(input('Please enter a number, or -10 to stop: ' ))
         if num == -10:
             break
         numbers.append(num)
    print('Numbers:', len(numbers))
    print('Maximum:', max(numbers))
    print('Minumum:', min(numbers))

答案 1 :(得分:2)

我会这样做:

def maxmin():
  minimum = None
  maximum = None

  while True:
    num = input('Please enter a number, or -10 to stop: ')
    if num == -10:
      break

    if (minimum) is None or (num < minimum):
      minimum = num
    if (maximum) is None or (num > maximum):
      maximum = num
  print ("Maximum: ", maximum)
  print ("Minimum: ", minimum)

maxmin()

请注意,你并没有真正调整你的while循环数字!= -10,因为你在循环中检查它并突破它。那么,在循环开始时永远不会有num = -10的时间,有意义吗?

所以,你只需要永远循环(while True),直到有人输入-10

答案 2 :(得分:0)

num中使用while之前,您必须定义if,您的嵌套if也应该在另一个def maxmin(): minimum = None maximum = None num = None while True: num = input('Please enter a number, or -10 to stop: ') if num == -10: break if (minimum) is None or (num < minimum): minimum = num if (maximum) is None or (num > maximum): maximum = num print ("Maximum: ", maximum) print ("Minimum: ", minimum) maxmin() 之外:

{{1}}

答案 3 :(得分:0)

此函数应该为您提供所需的输出:

def maxmin():
    minimum, maximum, total = None, None, 0
    while(True):
        number = input('Please enter a number, or -10 to stop: ')
        num = int(number)
        if num == -10:
            break
        if total == 0:
            minimum, maximum, total = num, num, 1
            continue
        total += 1
        if num < minimum:
            minimum = num
        elif num > maximum:
            maximum = num
    print("Output : total ={}, minimum={}, maximum ={}".format(total, minimum, maximum))