Ask coding questions

← Back to all posts
Undefined Variable
Axrevyn (289)

This is a very strange problem that I have no idea how to solve. How is this variable undefined?

Comments
hotnewtop
Coder100 (18143)

Hi fren!

send repl please :)

The thing is, answer is not defined because it is declared in the if statement, after you unindent, answer gets 'deleted', here's the fixed code:

  answer = 0
  if op[1] == "+"
    answer = int(op[0]) + int(op[2])
  print(answer)
Axrevyn (289)

@Coder100 That's not it. I forgot to put .split() on the end of line 5, I'm dumb.

Coder100 (18143)

@Axrevyn

last = "None"

while True:
  op = input("Ans:"+str(last)+"\n\n [>>>>] ")
  answer = 0 # use this so python knows which answer to define
  if op[1] == "+":
    answer = int(op[0]) + int(op[2]) # if python defined the answer in here, it wouldn't be able to be used outside of the if statement
  print(answer)
  last=answer
Coder100 (18143)

well you get what I'm saying right @Axrevyn

Coder100 (18143)

yay mark as correct answer? lol @Axrevyn

Axrevyn (289)

@Coder100 Oh. I was just missing the .split(), nothing more was needed.

Coder100 (18143)

FIXED

last = "None"

while True:
  op = input("Ans:"+str(last)+"\n\n [>>>>] ")
  answer = 0 # use this so python knows which answer to define
  if op[1] == "+":
    answer = int(op[0]) + int(op[2]) # if python defined the answer in here, it wouldn't be able to be used outside of the if statement
  print(answer)
  last=answer