Python local and global variables

Asked

Viewed 6,433 times

1

I have a software that treats dates, written as follows:

def EscolheDataInicio():
    controle1 = None
    controle2 = None
    if controle1 == None:
        teste = easygui.ccbox(msg="Escolher data início?", title="Escolher data de início", choices=('[O]k', '[C]ancel'))
        if teste == False:
            controle1 = 1
        else:
            while controle1 == None:
                controle1 = easygui.enterbox(msg="Insira data início", title="Definir data início")
                ValidaDataInicio() #Testa se a entrada corresponde a uma data em formato válido...
                EscolheDataFim() #Chama função correlata para inserção de data final do intervalo.

The idea is to set a date range (controle1 and controle2) OR set a default reference date determined by the system (if the user cancels the CCBOX, the program will assume that it does not intend insert a date range, and set controle1 as 1, coming out of the loop.

The question is: how to KEEP this 1, so that the program DOES NOT ENTER the function again, since I declare controle1 as None as a PLACE variable for each call? I have tried declaring controle1 as None OUT of function, and insert a global controle1 in the function, but then it returns the error "NameError: name 'controle1' is not defined".

I want him to ask this interval once.

In vdd the whole code is much more extensive, but basically that’s it:

controle1 = None
controle2 = None
def EscolheDataInicio():
    global controle1
    global controle2
    if controle1 == None:
        teste = easygui.ccbox(msg="Escolher data início?", title="Escolher data de início", choices=('[O]k', '[C]ancel'))
        if teste == False:
            controle1 = 1
        else:
            while controle1 == None:
                controle1 = easygui.enterbox(msg="Insira data início", title="Definir data início")
                ValidaDataInicio()
                EscolheDataFim()
  • And you are sure that the undefined variable error occurred in this function?

  • Error in line 4 in Choosestart...

  • 1

    See: https://ideone.com/2TRiD9. Works as expected. The error must be elsewhere in the code.

  • I was declaring in the main library. I didn’t know that Python made this differentiation. I have a library that "starts" the program, and another just for the treatment of dates. I put the from TrataAsDatas import *, but really didn’t know it. Grateful.

1 answer

0


How about:

import datetime
import easygui

# Declara lista global contendo o intervalo de datas e um flag indicador
g_intervalo_data = [ False, None, None ]

def ValidaData( data ):
    try:
        datetime.datetime.strptime( data, '%d/%m/%Y')
    except ValueError:
        return False
    return True

def EscolheDatas():

    # Faz com que a variavel global seja acessivel dentro do escopo da função
    global g_intervalo_data;

    dataInicio = None
    dataFim = None

    # Verifica se a pergunta já foi feita anteriormente verificando o flag indicador
    if( g_intervalo_data[0] == True ):
        return g_intervalo_data[1:3];

    opt = easygui.ccbox(msg="Escolher data inicio ?", title="Escolher data de inicio", choices=('[O]K', '[C]ancelar'))

    if opt == True:

        while True:
            dataInicio = easygui.enterbox(msg="Insira data inicio:", title="Definir data inicio" )
            if (dataInicio == None) or (ValidaData( dataInicio ) == True): break
            easygui.msgbox("Data Inicio Invalida!")

        while True:
            dataFim = easygui.enterbox(msg="Insira data final:", title="Definir data final" )
            if (dataFim == None) or (ValidaData( dataFim ) == True): break
            easygui.msgbox("Data Final Invalida!")

    # Preenche variavel global com o intervalo de data e um flag indicador
    g_intervalo_data = [ True, dataInicio, dataFim ]

    return g_intervalo_data[1:3];


print(EscolheDatas());
print(EscolheDatas());
print(EscolheDatas());

Browser other questions tagged

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