I can’t get the variables I created recognized when using Def

Asked

Viewed 66 times

0

I wrote the code below which is a rectangle triangle calculator using def to define my custom functions.

def pedir_base():
    while True:
        try:
            base = float(input('Digite o valor da base do triângulo retângulo: '))
            if base <= 0:
                print(' ')
                print('A base precisa ser um número maior que zero.')
                continue
        except:
            print(' ')
            print('A base precisa ser um número.')
            continue
        break
def pedir_angulo():
        while True:
            try:
                angulo = float(input('Digite o valor do ângulo da base com a hipotenusa: '))
                if angulo < 0 or angulo == 0 or angulo == 90 or angulo > 90:
                    print(' ')
                    print('O ângulo precisa estar entre 0 e 90.')
                    continue
            except:
                print(' ')
                print('O ângulo precisa ser um número.')
                continue
            break
def cálculos(a, b):
        import math
        reto = float(90)
        hipotenusa = base/ math.cos(math.radians(angulo))
        lado = hipotenusa * math.sin(math.radians(angulo))
        LxH = 90 - angulo


        perímetro = hipotenusa + lado + base
        altura = (lado * base)/ hipotenusa
        área = (base * lado)/ 2
        r_insc = (lado + base - hipotenusa)/ 2
        r_circ =  hipotenusa/ 2
def print_dos_valores():

        print(' ')
        print('O valor da base do triângulo é:', round(base, 2), '.')
        print('O valor da hipotenusa do triângulo é:', round(hipotenusa, 2), '.')
        print('O valor do lado perpendicular à base do triângulo é:', round(lado, 2), '.')
        print('Os valores dos ângulos são:', round(reto, 2), ',', round(angulo, 2), ',', round(LxH, 2), '.')
        print(' ')
        print('EXTRA:')
        print('O valor do perímetro é:', round(perímetro, 2), '.')
        print('O valor da altura é:', round(altura, 2), '.')
        print('O valor da área é:', round(área, 2), '.')
        print('O valor do raio do círculo inscrito é:', round(r_insc, 2), '.')
        print('O valor do círculo circunscrito é:', round(r_circ, 2), '.')
        print(' ')
        print(' ')
def final():
        if input('Pressione S caso deseje calcular outro triângulo. Caso deseje fechar a aplicação, pressione qualquer outra tecla.') in ('S', 's'):
            print(' ')
            print(' ')
        if not x:
            print('Fechando a aplicação.')
        return x


while True:
    b = pedir_base()
    a = pedir_angulo()
    c = cálculos(a, b)
    print_dos_valores()
    if not final():
        break

The problem is that, when arriving at the part of the calculations, it does not recognize the variable angulo created earlier and says that it is of type Nonetype, which will probably also happen with the variable base when I get to her. I wonder why this is happening and if I’ve given some other nonsense in this code.

def cálculos(a, b):
        import math
        reto = float(90)
        hipotenusa = base/ math.cos(math.radians(angulo))  #Aqui ele não faz a conta e diz que é NoneType
        lado = hipotenusa * math.sin(math.radians(angulo))
        LxH = 90 - angulo


        perímetro = hipotenusa + lado + base
        altura = (lado * base)/ hipotenusa
        área = (base * lado)/ 2
        r_insc = (lado + base - hipotenusa)/ 2
        r_circ =  hipotenusa/ 2
  • 2

    Its function calculos has 2 parameters a and b. Should you or shouldn’t you change a for angulo and b for base or otherwise exchange references angulo and base for a and b? I have at least one more problem: your motivation final uses a variable x without defining it. Study on the scope of variables.

  • I tried to change the names of the variables, but nothing works, I’m already without ideas of how to get around the problem. About x, I just realized what you said and I’ve fixed it, thank you.

  • 1

    Local Scope: A local variable (created within a function) exists only within the function where it was declared. Local variables are initialized with each new function call. Thus, it is not possible to access its value outside the function where it was declared. So that we can interact with local variables, we pass parameters and return values in functions.

  • 1

    Global Scope: A global variable is declared (created) outside functions and can be accessed by all functions present in the module where it is defined. Global variables can also be accessed by other modules if they import the module where the variable was defined.

  • 1

    See for example your variable hipotenusa, she is local to the function calculosand therefore not known within the function print_dos_valores.

  • do not use accents for variables, change cálculos for calculos perímetro for petrimetros, etc.

  • To see if the angle is valid, you can do if 0 <= angulo <= 90 (if the angle is between 0 and 90)

Show 2 more comments

1 answer

2


Its biggest problem is the functions. Take a look at some content on the internet about python functions. The point is that you need to have the function return something in order to use the value elsewhere. Follow the example, note that the angle is being returned at the end of the function:

def pedir_angulo():
    while True:
        try:
            angulo = float(input('Digite o valor do ângulo da base com a hipotenusa: '))
            if angulo < 0 or angulo == 0 or angulo == 90 or angulo > 90:
                print(' ')
                print('O ângulo precisa estar entre 0 e 90.')
                continue
        except:
            print(' ')
            print('O ângulo precisa ser um número.')
            continue
        break
    return angulo

Functions have local scope, variables created within functions are only accessible within the function itself, unless you return them.

A simple example of the sum of two numbers:

def valor_1():
    num_1 = int(input("Digite um número a ser somado: "))
    return num_1

def valor_2():
    num_2 = int(input("Digite outro número a ser somado: "))
    return num_2


def soma(numero_1, numero_2):
     resultado = numero_1 + numero_2
     print("O resultado da soma é {}".format(resultado))


valor_1 = valor_1()
valor_2 = valor_2()
soma(valor_1, valor_2)

I hope it helped.

Contents

Python documentation

Video talking about python functions

Browser other questions tagged

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