RDS
Posts: 776
Joined: Tue Oct 06, 2015 8:17 am
Location: Lancashire, UK

Error message after introducing a Procedure

Sat Jul 02, 2016 2:37 pm

My program runs well but I decided to try to tidy it up a little by creating some procedures for the repeatedly used aspects of the code.
I have some code that displays it's output on a 4 line LCD. I have created a procedure using def prepare_output_for_LCD():
All I have done is add the def prepare_output_for_LCD(): line to the start of the code and to move the code from it's original position in my program to the end of my other procedures (that all work very well)

Introducing the procedure is preventing my program from running and causing the following error:

UnboundLocalError: local variable 'lpulse' referenced before assignment.

At the start of the program, I have a line that says lpulse="" and then just before calling it I recalculate 'lpulse'.
I would appreciate help with this because the procedure is only being called from the position where it previously ran perfectly, so I cannot understand why it would be reported as being referenced before assignment.

User avatar
PeterO
Posts: 5951
Joined: Sun Jul 22, 2012 4:14 pm

Re: Error message after introducing a Procedure

Sat Jul 02, 2016 3:00 pm

Do you understand the python variable scoping rules ?

PeterO
Discoverer of the PI2 XENON DEATH FLASH!
Interests: C,Python,PIC,Electronics,Ham Radio (G0DZB),1960s British Computers.
"The primary requirement (as we've always seen in your examples) is that the code is readable. " Dougie Lawson

RDS
Posts: 776
Joined: Tue Oct 06, 2015 8:17 am
Location: Lancashire, UK

Re: Error message after introducing a Procedure

Sat Jul 02, 2016 3:26 pm

PeterO wrote:Do you understand the python variable scoping rules ?
Thanks for your reply, I am just 'Googling' that phrase but I had thought that by just moving the code into a procedure and calling the procedure from where it was originally placed in my program, that I had ensured that variables would be OK.

RDS
Posts: 776
Joined: Tue Oct 06, 2015 8:17 am
Location: Lancashire, UK

Re: Error message after introducing a Procedure

Sat Jul 02, 2016 4:38 pm

@PeterO
Thank you for pointing me in the right direction. I have got it working after reference to my Python programming book!

I can't say I really understand why though. I have had to specify the Variables that are calculated in the Procedure and then used in another Procedure, within the first Procedure itself. As they are 'Global', I would have thought that they should be defined as 'Global' at the start of the Program, rather than within a Procedure, so although it works, I would have preferred it if it had been more logical (to me).

Return to “Python”