[Tutor] counting function calls

Alan Gauld alan.gauld at yahoo.co.uk
Mon Apr 10 06:15:14 EDT 2017


On 10/04/17 08:55, 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

> UnboundLocalError: local variable 'count' referenced before assignment
> ^CPIR deaktiviert


You are trying to modify a variable defined in the module or
global scope. To do that you must tell Python that it is
the global variable you mean. You do that by adding

global count

at the top of your function:

def mein_callback(pin):
    global count   # use the global variable
    count += 1
    print('PIR 1 aktiviert', count)
    return

You don;t need the return since Python returns None automatically
at the end of a function. But it doesn't do any harm either...

HTH

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list