-5

I get "local variable 'answer' referenced before assignment" error with my code. How should I resolve this?

from Tkinter import *
import Tkinter


def proces():

  F=Entry.get(E1)
  m=Entry.get(E2)
  a=Entry.get(E3)
  if F ==0:
      answer=float(m)*float(a)
  if m ==0:       
      answer=float(F)/float(a)
  if a ==0:
      answer=float(F)/float(m)
  Entry.insert(E4,0,answer)
  print(answer)

#And the rest of the GUI coding goes here. 

top = Tkinter.Tk()
L1 = Label(top, text="My calculator",).grid(row=0,column=1)
L2 = Label(top, text="Force",).grid(row=1,column=0)
L3 = Label(top, text="Weight",).grid(row=2,column=0)
L4 = Label(top, text="Accelaration",).grid(row=3,column=0)
L4 = Label(top, text="Solution",).grid(row=4,column=0)
E1 = Entry(top, bd =5)
E1.grid(row=1,column=1)
E2 = Entry(top, bd =5)
E2.grid(row=2,column=1)
E3 = Entry(top, bd =5)
E3.grid(row=3,column=1)
E4 = Entry(top, bd =5)
E4.grid(row=4,column=1)
B=Button(top, text ="Solve",command = proces).grid(row=5,column=1,)

top.mainloop()
Nae
  • 14,209
  • 7
  • 52
  • 79
cee
  • 7
  • 2
  • 1
    just define `answer=0 or some vale` above `IF`, just think about if none of the condition satisfies what will be the value for answer ? – Vikas Periyadath Feb 06 '18 at 06:54
  • Welcome to [so]! Please provide a [mcve] for the question you're asking as opposed to your current code. – Nae Feb 06 '18 at 11:01

3 Answers3

0

Give like this :

answer = "the value which you can give as default"
if F ==0:
  answer=float(m)*float(a)
if m ==0:       
  answer=float(F)/float(a)
if a ==0:
  answer=float(F)/float(m)

or

if F ==0:
  answer=float(m)*float(a)
elif m ==0:       
  answer=float(F)/float(a)
elif a ==0:
  answer=float(F)/float(m)
else :
  answer = "the value which you can give as default"

If none of the conditions is matching which value you want to assign to answer? that value you can give in mentioned place in that above answers

Nae
  • 14,209
  • 7
  • 52
  • 79
Vikas Periyadath
  • 3,088
  • 1
  • 21
  • 33
0

You are assigning value to variable 'answer' inside the if statement so its scope is limited to those if statements, simply initialize your variable answer before if statement.

Usama Wajhi
  • 51
  • 1
  • 3
  • Can you please show me how to do this? , Cus when I assign 'answer=0' before is statements the solution(answer) prints out as 0 allways. – cee Feb 06 '18 at 07:13
  • After initializing answer=0 If you are getting '0' as your answer at the end, this means none of the if conditions are being executed, so you've to check the values you are passing to F, m, a. – Usama Wajhi Feb 07 '18 at 06:26
0

Thank You very much for your quick replies.

I finally solved it .

All I had to do is make if (variable)==0: to if len(variable)==0:

I hope anyone who get this problem in the future will find this helpful.

cee
  • 7
  • 2