block Try and except

0

I need to run this program:

Rewrite your payment program using try and except for the program to handle non-numeric inputs amicably by printing a message and exiting the program. The following shows two program implementations:

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

O 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")

It only gives this error:

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

How can I solve this problem?

    
asked by anonymous 20.06.2018 / 11:04

2 answers

1

The input returns string. That being the case, before you account for 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-numeric input the program, besides presenting the error message, is interrupted ( sys.exit ). / p>

As the same treatment is given for two inputs, it is better to create a function ( int_or_exit ) to avoid repetition of 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)
    
20.06.2018 / 13:14
1

The problem is that you are setting variables like INT after multiplication, this error means that you are multiplying strings , so the problem.

try this 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")
    
20.06.2018 / 12:47