Inserting error message to user

Asked

Viewed 46 times

2

Make a program that receives two numbers. Calculate and show: The sum of the even numbers of that range, including the numbers typed. The multiplication of odd numbers in this range, including those typed.

I decided as follows:

x = int(input('Digite um número: '))
y = int(input('Digite um número: '))


par = 0
impar = 1

for i in range(x-1, y+1):
    if i % 2 == 0:
        par = par + i
    elif i % 2 != 0:
        impar = impar * i


print('A soma dos números pares entre', x, 'e', y, 'é', par, '.')
print('A multiplicação dos números impares entre', x, 'e', y, 'é', impar, '.')

But if the user reports the first number greater than the second, or the two equal numbers, the returned result is wrong.

I decided as follows.

while True:
    x = int(input('Digite um número: '))
    y = int(input('Digite um número: '))
    if x < y:
        break
    else:
        continue

    if x == y:
        break
    else:
        continue


par = 0
impar = 1

for i in range(x-1, y+1):
    if i % 2 == 0:
        par = par + i
    elif i % 2 != 0:
        impar = impar * i


print('A soma dos números pares entre', x, 'e', y, 'é', par, '.')
print('A multiplicação dos números impares entre', x, 'e', y, 'é', impar, '.')

However, I would like to put an error message, so that the user knows what to do.

while True:
    x = int(input('Digite um número: '))
    y = int(input('Digite um número: '))
    if x < y:
        "Acredito que aqui deveria estar a mensagem de erro, porem colocando o print com erro aqui não da certo."
        break
    else:
        continue

    if x == y:
        break
    else:
        continue

2 answers

1

You don’t have to use continue. Just put the print in cases of error and only call the break if you do not enter into any of these cases:

while True:
    x = int(input('Digite um número: '))
    y = int(input('Digite um número: '))
    if x == y: # se forem iguais
        print('Números não podem ser iguais')
    elif x > y: # se x for maior que y
        print('x deve ser menor que y')
    else: # x é menor que y, sai do loop
        break

If they are equal, print the first message. If x is greater than y, prints the second message. Otherwise, it leaves the loop.

In this case, if you fall into one of the error cases, the while keeps running and it asks that the numbers be typed again. But if the idea is to quit the program, you can use sys.exit:

import sys
x = int(input('Digite um número: '))
y = int(input('Digite um número: '))
if x == y:
    print('Números não podem ser iguais')
    sys.exit(1)
elif x > y:
    print('x deve ser menor que y')
    sys.exit(2)

The number passed to sys.exit is optional (if none is passed, it will be zero), and is usually used to indicate the error code (I used different codes to indicate each situation).

And in that case, you don’t even need loop, since either the program is terminated, or it continues (there is no "try again").


Another detail is that if you want the numbers between x and y (with y included), so should use range(x, y + 1).

And his for doesn’t need the elif, can be exchanged for else:

soma_pares = 0
produto_impares = 1
for i in range(x, y + 1):
    if i % 2 == 0:
        soma_pares += i
    else:
        produto_impares *= i

That’s because if i % 2 for zero, get in the if. If you didn’t get into the if, that say it’s definitely not zero, so no else I don’t need to test if it’s non-zero (at that point do elif i % 2 != 0 is redundant and unnecessary).

I also used += (that already sums and assigns the result to the variable) and *= (that does the same with multiplication), and I gave better names to the variables. It may seem a silly detail, but give names better help when programming.


Finally, it is worth remembering that int gives error if a valid number is not entered. If you want to validate this, an alternative is:

def ler_numero(mensagem='Digite um número'):
    while True:
        try:
            return int(input(mensagem))
        except ValueError:
            print('Não foi digitado um número válido')

x = ler_numero()
y = ler_numero()

Thus, the function keeps trying to convert what was typed to number. If it doesn’t work, the ValueError and he asks you to type again.

-1

You can try using the "Try" and "except" function, in case "Try" goes wrong, the "except" function will come into play by printing whatever you want on the screen, except also has some arguments that it only activates if the error is for example "Valueerror", I advise you to give a search on. Would look like that:

while True:
    try:
        x = int(input('Digite um número: '))
        y = int(input('Digite um número: '))
        if x < y:
            exit()
        if x == y:
            exit()
    except:
        print("O valor de 'x' não pode ser menor ou igual a 'y', saindo...")

The function Exit() will automatically trigger what is inside the "except", thus printing the error for who is using

Browser other questions tagged

You are not signed in. Login or sign up in order to post.