How to repeat all the code at the end of the execution when "While" repeats only one part?

Asked

Viewed 43 times

-4

I’m doing a program that calculates a person’s pay based on the number of hours and overtime worked. The idea is that at the end of the execution the user decides whether to recalculate or terminate the program, but when selecting the option to retry only the last two lines of code are executed, not the complete code, as can be seen below:

#Título: Pagamento por Horas
#Contador de pagamento baseado em horas regulares e horas extras trabalhadas

horas = 0
base = 0
resposta = 'S'

while resposta == 'S' or resposta == 's':
    while horas == 0:
        try:
            horas = int(input('Digite as horas trabalhadas: '))
        except:
            print('Por favor, digite uma entrada numérica! :)')
    global base
    while base == 0:
        try:
            base = int(input('Digite a base para o cálculo: '))
        except:
            print('Por favor, digite uma entrada numérica! :)')
    if horas > 40:
        horas_extras = float((horas-40)*(base*1.5))
        pagamento = (40*base)+horas_extras
    else:
        pagamento = horas*base
    print('O valor do pagamento será: {:.2f}'.format(pagamento))
    resposta = str(input('Para calcular novamente digite [S]'))

I’ve tried to isolate the code within a function to see if everything would run, but I was unsuccessful. Does anyone know where I might have gone wrong or if there’s a way to make it work?

  • Place horas = 0 and base = 0 at the beginning of the first loop while.

1 answer

1


This is happening because at the end the variable hours will have the value you typed and the block while horas == 0 will only be executed if the variable hours is equal to 0, the same thing on the block while base == 0. Try:

    ...
    print('O valor do pagamento será: {:.2f}'.format(pagamento))
    resposta = str(input('Para calcular novamente digite [S]'))
    horas = 0
    base = 0
    ...
  • Now the code worked. I had even forgotten to return the values to zero for the block to work again. Thank you very much!

Browser other questions tagged

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