[Tutor] counting function calls

Mats Wichmann mats at wichmann.us
Mon Apr 10 09:15:07 EDT 2017


On 04/10/2017 01:55 AM, marcus lütolf wrote:
> Dear experts,
> I have written the following code for motion detection with a PIR sensor
> with a function and
> I need to count how many times the funtion is called, but I get a traceback:
> 
> #!/usr/bin/python3
> import sys, time
> import RPi.GPIO as gpio
> 
> gpio.setmode(gpio.BOARD)
> gpio.setup(23, gpio.IN)
> count = 0
> def mein_callback(pin):
>     count += 1
>     print('PIR 1 aktiviert', count)
>     return
> 
> try:
>     gpio.add_event_detect(23, gpio.RISING, callback = mein_callback)
>     while True:
>         time.sleep(2)
> except KeyboardInterrupt:
>     print('PIR deaktiviert')
> 
> PIR 1 aktiviert
> Traceback (most recent call last):
>   File "./PIRex.py", line 9, in mein_callback
>     count += 1
> UnboundLocalError: local variable 'count' referenced before assignment
> ^CPIR deaktiviert
> 
> Tanks for help, marcus.

Yes, what Python does here may be surprising at first: if you only
read-access a global variable in a local (function in this case) scope,
it gives you the value just fine.  If you however try to save something
to a global variable what happens is it creates a local variable,
*unless* you have previously informed Python you mean the global one, by
using the global statement as Alan listed. The specific error you see is
because in order to increment 'count' (which Python has already figured
out has to be local because it will be assigned to) you have to read the
existing value first, but there is no existing value in the local scope.

The Python programming FAQ has a short explanation of why this might be so:

https://docs.python.org/2/faq/programming.html#what-are-the-rules-for-local-and-global-variables-in-python



More information about the Tutor mailing list