-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 beFalse
and he will try to convert tofloat
and will give aValueError
, interrupting the execution of the program, see: https://ideone.com/HgM9I9 - Also, the variablevalido
, besides having a wrong name (because I just want to continue case nay is a valid value), is unnecessary as thereturn
already exits the function and stops the loop.– hkotsubo
The right is to try to convert to
float
and already return the value. What if the conversion tofloat
error, capture theValueError
with a blocktry
/except
, thus: https://ideone.com/supvn1 - inclusive, this form is the most recommended by documentation (in this example he usesbreak
to interrupt the loop, but since you are inside a function, it is best to usereturn
to return the value at once).– hkotsubo