Undefined function error

i’m confused why my “SaveLog” function works in all IF statements, but gives me a “SaveLog was not defined” error in the first IF statement “if firstBoot”.? if i comment out the SaveLog, the rest of the if statement works fine.

import serial
import time
from datetime import datetime
import RPi.GPIO as GPIO

GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP)
SP2 = serial.Serial( "/dev/ttyS0", baudrate=115200)#PC


S1Timer= 0
Save =""

while True:
    now = datetime.now()
    CT = now.strftime("%H:%M %m/%d")
    Mili =time.perf_counter()

    if  firstBoot:
        Save="boot log,"
        print("first boot")

    #GPIO input S1

    if not GPIO.input(23) and Mili  > S1Timer + 5:
        S1Timer= Mili
        print("S1 Triggered...")

    #in from PC
    if (SP2.inWaiting() > 0):

        PcIN = SP2.readline().decode()
        print(PcIN, end='')
        pcout= PcIN.strip()

        if pcout=="log":


    def SaveLog():
        LOG = open("LOG.txt" , "a",buffering=1 )

    def Sender():

        with open('LOG.txt', 'r') as file:
            LogFile = file.read()
            #LogOut= LogFile.strip()

        SP2.write(str.encode(LogFile +"\n"))

Move SaveLog to the start of your code, before the while loop. Functions have to be defined before you can call them:

import serial

def SaveLog():

while True:

Thank you, any idea why the If statement under it DOES work without moving the function?

Because it is under the function definition.

Python executes code from the top of the file down to the end, and that includes function definitions:

# No functions exist yet (except built-in functions).

# This defines the first function.
def first():
    return "This is first"

print(first())   # Okay, because first exists.
print(second())  # NOT OKAY, because second doesn't exist **yet**.

# This defines the second function.
def second():
    return "And this is second"

If you copy that code and run it, you will see that “This is first” is printed and then you will get a NameError that second doesn’t exist.

But if you move the second print to the very end, after the second function definition, it will be fine.

(Note: if you do copy the code, be careful because the Discuss software may change quotation marks to curly quotes, and you will need to change them back.)