-1

I am trying to make a simple calculator with Python Tkinter. Below you can see a piece of code and a variable "sign" in it. I want the variable to serve as a way to tell the program that addition button of my calculator was pressed.

def addition():
    sign = "+"
    first_number = e.get()
    global first_converted
    first_converted = int(first_number)
    e.delete(0, END)

Further in the code, I want to make a function that will contain "if" statements for all of the scenarios of pressed buttons e.g. addition, division, multiplication, etc. However, Python does not see variable "sign".

def count():
    if sign == "+":
        pass
    e.delete(0, END)
    pass

I have tried declaring variable as global in the beginning of the code, but it did not help.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • 1
    Can you share a [mre] –  Aug 02 '21 at 09:37
  • 1
    Variables are specific to some *scope*. The ``sign`` in ``addition`` is not the same as the ``sign`` in ``count``. You should pass the *values* referred to by variables as *arguments* to other functions that need them. While you can also "pass" values as ``global``, this is problematic when values need to be modified. – MisterMiyagi Aug 02 '21 at 09:37
  • How about defining sign as a global variable? – Josmy Aug 02 '21 at 09:37
  • 3
    I'd strongly recommend re-structuring the program so that there's no need to use global variables, but if you have to, `sign` has to be declared global in any function that assigns to it. – bereal Aug 02 '21 at 09:38
  • Does this answer your question? [Python function global variables?](https://stackoverflow.com/questions/10588317/python-function-global-variables) – Tomerikoo Aug 02 '21 at 09:45
  • Does this answer your question? [How can I share a variable between functions in Python?](https://stackoverflow.com/q/41636867/6045800) – Tomerikoo Aug 02 '21 at 09:46

1 Answers1

0

I would just pass on the sign argument as @MisterMiyagi descripes a bit:

def addition():
    sign = "+"
    first_number = e.get()
    global first_converted
    first_converted = int(first_number)
    e.delete(0, END)
    return sign #Returns sign

sign = addition()

def count(sign): #Takes sign as input
    if sign == "+":
        pass
    e.delete(0, END)
    pass

count(sign)

or make it global

sign = "+" #Or, by convention SIGN = "+"
def addition():
    first_number = e.get()
    global first_converted
    first_converted = int(first_number)
    e.delete(0, END)



def count(): #Takes sign as input
    if sign == "+":
        pass
    e.delete(0, END)
    pass
CutePoison
  • 4,679
  • 5
  • 28
  • 63