Home > Software design >  Why outputs differ between VScode python terminal & Interactive window?
Why outputs differ between VScode python terminal & Interactive window?

Time:02-27

I was runing this code on VScode :

a = input("a : ")
b = int(a)   2
print(f"a:{a},b:{b}")

The output on Python terminal:

a : b = int(a)   2
>>> print(f"a:{a},b:{b}")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'b' is not defined 

The Output on Interactive window for input 12 :

 a:12,b:14

What's the problem here ?

P.S. A similar terminal problem is in this thread but still without any solution. enter image description here

to run it. It will be executed in the "TERMINAL":

input prompt

input a number:

42 inputted

hit enter:

result


If you take all your code into the copy/paste buffer and "paste" it into the interactive console it will be executed line by line.

Essentially you paste

a = input("a: ")

then it takes your next line

b = int(a)   2

as your input and stores it inside a.

Then it executes

print(f"a:{a},b:{b}")

and complains about b because your line b = int(a) 2 was used as input() and is now stored as string inside a.

CodePudding user response:

Thanks to everyone for the help. What I found out from the answers is that Terminal & Interactive window behave different from each other.

Terminal : Executes line by line of code. So giving a block of code at once with input at first line of the block doesn't work well here.

Interactive window : Can take blocks of code & act/execute smarter than the Terminal as you can see in the output of the question.

CodePudding user response:

it is simple

if you write a = input("a : ") in python terminal it get execute see this enter image description here

Also If I copy your code and paste it into the terminal then it looks like this

Image

-> If you see in this image here b = int(a) 2 take as the input of a. Therefore you get error

b is not defined

Conclusion

As you write a = input("a : ") you need to give the input here example(12) then write b = int(a) 2 And, Then print(f"a:{a}:b{b}")

  • Related