As suggested in the comments, you can use a generator to avoid the usage of a global variable. You need this, because as you pointed out, the counter variable is set to 0 every time you call dinner_completed()
. Here is an example of using generators:
def dinner_completed():
yield False
while True:
yield True
check = dinner_completed()
while not next(check):
print('1')
As you asked, the dinner_completed()
function returns False only the first time and True all the other times. If you want to set a different threshold you can use the following code:
def dinner_completed():
n = 0
threshold = 1
while n < threshold:
yield False
n += 1
while True:
yield True
check = dinner_completed()
while not next(check):
print('1')
Last solution, as stated by in the duplicated answer, you can declare a static variable. I've used the if __name__ == '__main__
to prove that this is not a global variable:
def dinner_completed():
if dinner_completed.counter==0:
k=False
if dinner_completed.counter==1:
k=True
dinner_completed.counter+=1
print('counter',dinner_completed.counter)
return k
if __name__ == '__main__':
dinner_completed.counter = 0
while not dinner_completed():
print('1')