Help with code -> global declaration | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Help with code -> global declaration

Hi, I have the following piece of code: #Create a function that intakes a simple arithmetic calculation and produces the answer import operator ops={'+':operator.add,'-':operator.sub,'*':operator.mul,'/':operator.truediv} q_calc=str(input()) def calculator(calculation): l_calc=list(calculation) for num in range(0,len(calculation)-1): if l_calc[num]=='+' or l_calc[num]=='-' or l_calc[num]=='/' or l_calc[num]=='*': num1=l_calc[:num-1] num2=l_calc[num+1:] num1=''.join(num1) num2=''.join(num2) num1=int(num1) num2=int(num2) change=l_calc[num] change=str(''.join(change)) else: print() global change print(ops[change](num1,num2)) calculator(q_calc) This creates a calculator that can do simple operations. However, when it comes to running the code, the following message appears: 'SyntaxWarning: name 'change' is assigned to before global declaration'. This is referencing the line before the penultimate line of code. Please can I have some help in how to fix this and what has gone wrong.

5th Sep 2021, 10:07 AM
Kamil Hamid
Kamil Hamid - avatar
5 Answers
+ 2
You could just put change = None before the for loop without the global and this should take care of the UnboundLocalError that you shouldn't be getting anyway, unless there is more to your code that we aren't privy to.
5th Sep 2021, 10:53 AM
ChaoticDawg
ChaoticDawg - avatar
+ 1
You don't need the global change line. change is in the same scope. You're getting the error because you're assigning change in the if statement prior to making it global within the same scope. I don't see any need to make change global. Remove the line and your code will run. You may still have some other issues (logic) with your code, but it will run.
5th Sep 2021, 10:30 AM
ChaoticDawg
ChaoticDawg - avatar
+ 1
It runs in the playground ok with the line commented out. https://code.sololearn.com/c3esPxpuDObQ/?ref=app
5th Sep 2021, 10:46 AM
ChaoticDawg
ChaoticDawg - avatar
0
I was getting UnboundLocalError without the global however, so it is needed, unless there is another way to prevent the error
5th Sep 2021, 10:37 AM
Kamil Hamid
Kamil Hamid - avatar
0
Make your Declaration here: def calculator(calculation): global change change = "" l_calc=list(calculation) .... But you should NOT use global variables.
5th Sep 2021, 10:48 AM
Coding Cat
Coding Cat - avatar