0

Please make me clear that when i have made 'b' a global variable on line 1. Then also it is showing an error

Error: UnboundLocalError: local variable 'b' referenced before assignment

Note This code is a part of a larger code*

global b

b = 0

def solve(operation):

    global a
    a = display.get()

    global ex
    if operation == "-":
        if b == 0:
            ex = int(a)
        else:
            ex = int(b) - int(a)
    if operation == "+":
        ex = int(a) + b

    b = int(a)
    a = ex
    global ans
    ans = ex

    display.delete(0, tkinter.END)
ForceBru
  • 43,482
  • 10
  • 63
  • 98
  • 4
    You need to put `global b` in your `solve` function in order to access the global `b`. It won't do anything at the module level. There are a huge number of results you can find through the search for exactly this issue, or you can read one of the many tutorials on global variables such as [this one](https://www.w3schools.com/python/python_variables_global.asp). – Kemp Jun 25 '21 at 15:35

1 Answers1

0

Variables outside a function are global by default, so you don't need to declare it that way. As @Kemp indicated in the comment, you need to put global b inside your function. Or, of course, pass b as an argument to the function itself.

smp55
  • 403
  • 3
  • 8
  • Bro if i will assign the value of 'b' as 0 inside the function then as i will run the function, b will again and again be 0. This is not i want. I want be to be 0 at the starting of my code. Because when i click a button, Then the function will run. *Tkinter Code – ImLearningToProgram Jun 26 '21 at 01:13