How can I reference variables defined within if/elif statements further on in the parent Python (3.6) function?
The below is a mock-up of my code - I am trying to 'print' or 'work with' variables defined in each 'if' and 'elif' block below, at the end of the function which contains the if/elif statements that the variables are defined within, however I get an unresolved reference error in Pycharm and the following Python error when I run the code:
UnboundLocalError: local variable 'a1_summary' referenced before assignment
I am relatively new to Python and coding and don't understand where I am going wrong as I expect that as the variables are defined within the same function then they should be 'visible' to the print statement at the end of the function...
Is this a case where global variables should be used?
def Process_Data(incoming_data):
if incoming_data.count(',') == 2:
data_summary = incoming_data.split(',')
a1_summary, b1_summary = data_summary[0], data_summary[1]
elif incoming_body.count(',') == 3:
data_summary = incoming_data.split(',')
a2_summary, b2_summary, c2_summary = data_summary[0], data_summary[1], data_summary[2]
print(a1_summary, b1_summary, a2_summary, b2_summary, c2_summary )
else:
pass
Update
I was trying to keep the question simple but may have confused things as I am trying to use the if/elif statements within a function that process messages from a RabbitMQ message queue - I need to process messages based on the number of commas in the respective message and assign the parts of the message to variables and then aggregate the parts from each message received and processed by the if/elif statements into one array so that I can then pass this to another function later on in my program.
I may be going wrong in thinking that each time the function receives incoming_data which matches either the if or elif statement - any previous or new data that matches the other condition will still be held as a variable within the function e.g. I am thinking that the function holds variables from both the if/elif blocks and only updates any new data processed by the corresponding logic statement...