Program restarts alone and only closes after 2 valid entries

Asked

Viewed 93 times

-2

Guys, I was doing some exercises of Gustavo Guanabara and I came across an intriguing situation: my code restarts and his does not!!! It’s Python World 3 Class 22 Exercise 112. I used a 3 file structure as schema below:

test/
....cursoEmVideo/
........coin/
............____init____py.
........____init____py.
........data py.

Follow the contents of the coin/____init____.py:

def metade(num, boleano):
    if boleano:
        return moeda(num/2)
    return num/2

def dobro(num, boleano):
    if boleano:
        return moeda(num*2)
    return num*2

def aumentar(num, acrescimo, boleano):
    result = num + (num * acrescimo / 100)
    if boleano:
        return moeda(result)
    return result

def diminuir(num, reducao, boleano):
    result = num - (num*reducao/100)
    if boleano:
        return moeda(result)
    return result

def moeda(num):
    conversor = str(num).split('.')
    saida = "RS" + conversor[0] + ',' + conversor[1]
    return saida

def resumo(num, acrescimo, reducao):
    saida = 20*'-' + '\n' + 'RESUMO DO VALOR' + '\n' + 20*'-' + '\nPreço analisado: ' + moeda(num) + '\nDobro do preço: ' + dobro(num, True) + '\nMetade do preço: ' + metade(num, True) + '\n' + str(acrescimo) + '% de aumento: ' + aumentar(num, acrescimo, True) + '\n' + str(reducao) + '% de redução: ' + diminuir(num, reducao, True)
    print(saida)

Data content.py:

def leiaDinheiro(entrada):
    valido = True
    while valido:
        num = input(entrada)
        if num.isalpha():
            print(f'ERRO: "{num}´" é um preço inválido!')
        else:
            valido = False
            return float(num)

And the courseEmVideo/____init____.py:

from teste.cursoEmVideo import dado
from teste.cursoEmVideo import moeda

p = dado.leiaDinheiro('Digite o preço: R$')
moeda.resumo(p, 80, 35)

Can anyone see why the program restarts after reading a valid data, in this case, a numerical data? Even, as I mentioned in the title, the program actually ends, but only after two readings of valid data (not necessarily consecutive).

  • I don’t know the course of this guy, but the function leiaDinheiro is not very good. isalpha checks if the string only has letters, but what if the user enters spaces or @#$? In that case, isalpha() will be False and he will try to convert to float and will give a ValueError, interrupting the execution of the program, see: https://ideone.com/HgM9I9 - Also, the variable valido, besides having a wrong name (because I just want to continue case nay is a valid value), is unnecessary as the return already exits the function and stops the loop.

  • The right is to try to convert to float and already return the value. What if the conversion to float error, capture the ValueError with a block try/except, thus: https://ideone.com/supvn1 - inclusive, this form is the most recommended by documentation (in this example he uses break to interrupt the loop, but since you are inside a function, it is best to use return to return the value at once).

1 answer

0

I made some small changes to your code, I hope you don’t mind. It was like this:

test/

....cursoEmVideo/

........coin/

............____init____py.

............abstract.py

........____init____py.

........data py.

cursoEmVideo/currency/____init____.py now it’s an empty file, and what was inside was moved to abstract.py which is in the same directory

data py. was like this:

def leiaDinheiro(entrada):
valido = True
while valido:
    num = input(entrada)
    if num.isalpha():
        print(f'ERRO: "{num}" é um preço inválido!')
    else:
        valido = False
        num = float(num.replace(',' , '.'))
        return float(num)

And the cursoEmVideo/____init____.py:

import dado
from moeda import resumo

p = dado.leiaDinheiro('Digite o preço: R$')
resumo.resumo(p, 80, 35)

These were the entrances/exits:

inserir a descrição da imagem aqui

Realize that now both can enter a comma number as to a dot, and responsible for this is line 9 in data py.

Browser other questions tagged

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