Can I do better code than this in Python? I’m a beginner in the language and would like to know if I’m on the right track

Asked

Viewed 68 times

0

Objective of this program is to receive the radius of the user and calculate the area of the circle.

I’m a beginner in Pyhton, so I’d like to know if this is the most efficient code I could do to solve the problem, or if there’s another simpler way (as long as it’s not a ready-made Python function to calculate the rs circle area). I ask this question because I would know if I am on the right path or if I can improve it, make it simpler.

from math import pi


def area_circulo(raio):
     return pi * float(raio) ** 2


def nao_numerico(raio):
    print('Digite apenas números!')


def maior_que_zero():
    print('Raio precisa ser maior que 0!')


def se_numero(n):
    try:
        float(n)
    except ValueError:
        return False
return True


if __name__ == '__main__':
    raio = input('Informe o raio: ')

if se_numero(raio):
    if float(raio) < 1:
        maior_que_zero()
    else:
        area = area_circulo(raio)
        print('Area do circulo =', area)
else:
    nao_numerico(raio)

1 answer

0


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.

Browser other questions tagged

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