Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: how to increment number and store in variable every time function runs

(I'm a beginner in Python, just so you know)

What I'm trying to do: I want to keep count of how many times a user choose a wrong option and if it exceeds a number of times, he fails.

My approach was to store the count in a variable within a function and check with if/else statement if the number of times is exceeded.

Part of the code:

    choice = int(input("> "))

if choice == 1:
    print("This is the wrong hall.")
    increment()
elif choice == 2:
    print("This is the wrong hall.")
    increment()
elif choice == 3:
    hall_passage()
else:
    end("You failed")

COUNT = 0
def increment():
    global COUNT
    COUNT += 1

increment()

print(COUNT)

The increment part is from this thread and read using global scope is not a good practice.

The part I don't really understand is how you store count in a variable and it remembers the last value every time the function runs.

What is the best way to do this?

like image 264
user1607016 Avatar asked Jun 28 '26 01:06

user1607016


1 Answers

maybe something like this...

class Counter():
    def __init__(self):
        self.counter = 0

    def increment(self):
        self.counter += 1

    def reset(self):
        self.counter = 0

    def get_value(self):
        return self.counter


mc = Counter()

while mc.get_value() < 3:
    v = int(input('a number: '))
    if v == 1:
        print('You won!')
        mc.counter = 3
    else:
        print('Wrong guess, guess again...')
        if mc.counter == 2:
            print('Last guess...')
        mc.increment()  
like image 162
ahed87 Avatar answered Jun 30 '26 18:06

ahed87



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!