Local and global variables Python [closed]
want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 3 years ago .
improve this questionI 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 reference date default determined by the system (if the user cancels the CCBOX, the program will assume that he does not intend to enter a date range, and will set controle1
to 1
, exiting 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 LOCAL variable every call? I've tried declaring controle1
as None
outside the function, and inserting a global controle1
into the function, but then it returns the error "NameError: name 'controle1' is not defined"
.
I want let him ask this interval once .
In vdd the whole code is much more extensive, but basically this is 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()
1 answers
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());