How to use global variables in a function in Python?

I am working on a Python project where I need to use a global variable inside a function. I declared the global variable outside the function, but when I try to access it inside the function, it throws an error. Can anyone guide me on how to use global variables correctly in a function?

Here’s my code:

When I try to run this code, I get the following error:

UnboundLocalError: local variable ‘count’ referenced before assignment

I want to be able to use the global variable count inside the function increment_count() and increment its value. Can someone explain what I am doing wrong and how I can fix it?

Any help or guidance on this topic would be greatly appreciated. Thank you in advance!

1 Like