What is the problem with this code that takes the highest and lowest value?

1

I want to display the sum of the numbers entered as well as the largest and the smallest number entered, only with while , if and else :

contador = 1
maior = 0
menor = 0
S = 0  # 1º NÚMERO A SER SOMADO

while contador <= 5:
    num = int(input("Digite o " + str(contador) + "º valor:"))
    if num >= maior:
        maior = num
    if maior < num:
        menor = num
    S += num
    contador += 1
print("A soma de todos os valore é igual a", S)
print("O maior valor digitado foi", maior)
print("O menor valor digitado foi", menor)

The program shows the sum and the highest value, but does not show the smallest value.

    
asked by anonymous 14.01.2017 / 22:36

1 answer

2

There are two problems. You need to initialize the smallest number with a number that is the largest number to ensure that it will not be picked up unless the smallest number entered is itself. This can be done with sys.maxsize . There are also two errors in the check condition of the lowest maior < num : it needs to compare with the smaller one and not the largest one, and you need to check that the num is less than menor , not the other way around.

import sys

contador = 1
maior = 0
menor = sys.maxsize
S = 0

while contador <= 5:
    num = int(input("Digite o " + str(contador) + "º valor:"))
    if num > maior:
        maior = num
    if num < menor:
        menor = num
    S += num
    contador += 1
print("A soma de todos os valore é igual a", S)
print("O maior valor digitado foi", maior)
print("O menor valor digitado foi", menor)

See running on ideone . Also put it on Github for future reference .

    
14.01.2017 / 23:08