[Tutor] counting function calls

marcus lütolf marcus.luetolf at bluewin.ch
Thu Apr 13 12:10:45 EDT 2017


Dear experts, Mats
I have found the solution, I put the counting variable at the wrong place: 

> #!/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:
       count = 0
>     gpio.add_event_detect(23, gpio.RISING, callback = mein_callback)
>     while True:
>         time.sleep(2)
           count += 1
> except KeyboardInterrupt:
>     print('PIR deaktiviert')

Marcus.
----------------------------------------------------------------------------
--------------------
-----Ursprüngliche Nachricht-----
Von: Mats Wichmann [mailto:mats at wichmann.us] 
Gesendet: Montag, 10. April 2017 15:15
An: marcus lütolf <marcus.luetolf at bluewin.ch>; tutor at python.org
Betreff: Re: [Tutor] counting function calls

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



---
Diese E-Mail wurde von Avast Antivirus-Software auf Viren geprüft.
https://www.avast.com/antivirus



More information about the Tutor mailing list