Satyanshu
Satyanshu

Reputation: 13

variable not defined but I had already defind the variable

It's a simple program of adding two numbers :

1 print("Testing again")
2 print(a)
3 a = input()
4 print(a)
5 b = input()
6 c = int(a) + int(b)

I am a beginner in using vscode. So I am trying to resolve the problem. code error

>>> print(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined

Upvotes: 0

Views: 94

Answers (3)

Ryhan Ahmed
Ryhan Ahmed

Reputation: 73

Python is called an interpreted language. Python runs code like line-1, line-2, and so on.

So if you define a variable in line-2 and print it line-1 python does not recognize it as defined variable.

So your should be like this

1 print("Testing again") 2 a = input() 3 print(a) 4 b = input() 5 print(b) 6 c = int(a) + int(b) 7 print(c)

Upvotes: 0

Adharsh M
Adharsh M

Reputation: 3832

a = input()  <--  Definition

print(a) <--  Calling

if you do

print(a)

before defining

a = something

a is never defined at that point and will give you error.

Upvotes: 2

paxdiablo
paxdiablo

Reputation: 882606

You use a in line 2 before assigning to it in line 3:

1 print("Testing again")
2 print(a)
3 a = input()
4 print(a)
5 b = input()
6 c = int(a) + int(b)

You can probably just get rid of line 2 since you print a on line 4 (after it's set). Or, if you wanted to print both variables, make sure you do it after setting them:

1 print("Testing again")
2 a = input()
3 print(a)
4 b = input()
5 print(b)
6 c = int(a) + int(b)
7 print(c)

Upvotes: 1

Related Questions