Pass a variable from one function to another

Asked

Viewed 1,165 times

2

Hi guys, okay? Next, how could I send the variablemts_quadrados of def prog( ) to be calculated in def prog_main( )?

def prog():
    print("Informe o valor: ")
    cli()
    mts_quadrados = int(input(":"))
    clr()

def prog_main():
    qtd_lata = int(mts_quadrados / 6)
    vlr_lata = float(qtd_lata * 80)
  • You want to send the variable "square mts_squares"?

3 answers

7

Pass as parameter

You can put the variable "mts_squares" as parameter in the function "prog_main" and then pass the function "Prog" as parameter to "prog_main" and put the return of "Prog" to the variable "mts_squares", as in the example below:

def prog():
    print("Informe o valor: ")
    cli()
    mts_quadrados = int(input(":"))
    clr()
    return mts_quadrados # retorna o valor 

def prog_main(mts_quadrados):
    qtd_lata = int(mts_quadrados / 6)
    vlr_lata = float(qtd_lata * 80)

prog_main(prog()) # o retorno de "prog" e passado como parâmetro para "prog_main"

Using the global reserved word

Using the word reserved global at the beginning of the function Python understands that that variable is global in scope.

mts_quadrados = 0

def prog():
    global mts_quadrados
    print("Informe o valor: ")
    cli()
    mts_quadrados = int(input(":"))
    clr()

def prog_main():
    global mts_quadrados
    qtd_lata = int(mts_quadrados / 6)
    vlr_lata = float(qtd_lata * 80)

How to use a global variable in a function other than the one that created it?

0

Put a Re-turn with the mts_quadrados within the prog()

def prog():
    print("Informe o valor: ")

    mts_quadrados = int(input(":"))

    return mts_quadrados

and in the prog_main() you say right away that the qtd_lata is the same as what comes from prog() divided by 6

def prog_main():
    qtd_lata = int(prog() / 6)
    vlr_lata = float(qtd_lata * 80)

-3

Like everything in python is an object, ñ functions could be different

def envia(arg):
    recebe.valor = arg

def recebe():
   print(recebe.valor)

>>> envia(2)
>>> recebe()
2
  • 1

    this suggestion is one of the worst possible ways of doing what the question asks. The correct way to pass values between functions is by passing parameters and return values.

  • We can do all things with Python, but not all things are lawful ... Come and agree, take a look at the DOCS section on the Python website for more information friend. Follow link: https://www.python.org/doc/

Browser other questions tagged

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