Yes, it can be simpler.
For example, you convert the raio
for float
several times: first to see if it is even number, then to see if it is less than 1, and then to calculate the area. Instead, why not just convert once?
from math import pi
try:
# lê e já tenta converter para número
raio = float(input('Informe o raio: '))
# se chegou aqui, é porque a conversão deu certo
if raio < 1:
print('Raio precisa ser maior que 0!') # veja no final considerações sobre esta mensagem
else:
print(f'Área do círculo = {pi * raio ** 2}')
except ValueError: # se não digitou número, cai aqui no except
print('Digite apenas números!')
That is, when reading the number, already try to convert to float
. If it works, you go on. If it goes wrong, it goes on except
and you print the error message.
I didn’t put the area in a variable either, because if you just want to print the value and you won’t do anything else with it, or you don’t need a variable (just print the account result directly).
In a simple code like this, creating this lot of functions is only complicating for nothing. But of course, if you really want to use functions for everything, just call them in their places. I would only remove the function that checks if it is number, because it seems unnecessary to me (the conversion attempt itself will already indicate whether it has worked or not):
from math import pi
def area_circulo(raio):
return pi * raio ** 2
def nao_numerico(): # se o raio não é usado, não passe ele como parâmetro
print('Digite apenas números!')
def maior_que_zero():
print('Raio precisa ser maior que 0!')
try:
raio = float(input('Informe o raio: '))
if raio < 1:
maior_que_zero()
else:
print(f'Área do círculo = {area_circulo(raio)}')
except ValueError:
nao_numerico()
See that function nao_numerico
is not using the radius for anything, so there is no reason to pass it as parameter.
And there’s another strange thing: you say the radius should be greater than zero, but you test if the value is less than 1. It shouldn’t be if raio <= 0
?
This analysis I needed, thank you friend.
– f6l6p6