Try and except block

Asked

Viewed 116 times

0

I need to carry out this program:

Rewrite your payment program using Try and except for that the program treats non-numeric entries amicably by printing a message and exiting program. The following shows two program executions:

Digite as Horas: 20
Digite a Taxa: nove
Erro, por favor, informe entrada numérica
Digite as Horas: quarenta
Erro, por favor, informe entrada numérica

The my code is as follows:

numero_horas=input("Digite o numero de horas:")
valor_hora=input("Digite o valor hora:")
print("Erro, digite numeros")
valor_total=int(numero_horas*valor_hora)
print("Valor total", valor_total)
try:
    valor=int(valor_total)
    print("Valor de Pagamento é:", valor)
except:
    print("Inicie programa novamente")

Only there’s this mistake :

valor_total=int(numero_horas*valor_hora)
TypeError: can't multiply sequence by non-int of type 'str'

how can I solve this problem?

2 answers

1

Sergio the problem is that Voce is setting the variables as INT after multiplication, this error means that you are multiplying strings, therefore the problem.

try that way:

numero_horas=input("Digite o numero de horas:")
valor_hora=input("Digite o valor hora:")
try:
    #print("Erro, digite numeros")
    valor_total=int(numero_horas)*int(valor_hora)
    print("Valor total", valor_total)
    valor=int(valor_total)
    print("Valor de Pagamento é:", valor)
except ValueError:
    print("Inicie programa novamente")
  • Thanks for the help, solved what you wanted,

1


The input returns string. So, before making accounts with the returns you should convert them.

In addition, you say that the example is two executions of the program, so it is understood that when receiving a non-numerical input the program, in addition to displaying the error message, is interrupted (sys.exit).

Since the same treatment is given for two inputs, it is best to create a function (int_or_exit) to avoid repeating code.

import sys


def int_or_exit(int_string):
    try:
        int_valor = int(int_string)
    except ValueError:
        print("Erro, por favor, informe entrada numérica")
        sys.exit(1)
    return int_valor


input_numero_horas = input("Digite as Horas: ")
numero_horas = int_or_exit(input_numero_horas)

input_valor_hora = input("Digite a Taxa: ")
valor_hora = int_or_exit(input_valor_hora)

valor_total = numero_horas * valor_hora
print("Valor de Pagamento é:", valor_total)
  • Thanks for the help, solved what you wanted,

Browser other questions tagged

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