为什么 VScode python 终端和 VScode 之间的输出不同?互动窗口?
我在 VScode 上运行此代码:
a = input("a : ")
b = int(a) + 2
print(f"a:{a},b:{b}")
Python 终端上的输出:
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
输入 12 的交互式窗口上的输出:
a:12,b:14
这里有什么问题?
PS 类似的终端问题在此线程中,但仍然没有任何解决方案。 为什么这里有不同的输出?
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.
Why there are different outputs here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将完整代码添加到文件中并保存。按 fe F5 调试/运行程序。
您可能需要选择
运行它。它将在“终端”中执行:
输入一个数字:
按 Enter:
如果您将所有代码放入复制/粘贴缓冲区并且“将其粘贴到交互式控制台中它将逐行执行。
本质上,您粘贴
然后它会将您的下一行
作为您的输入并将其存储在
a
中。然后它执行
并抱怨
b
因为您的行b = int(a) + 2
被用作input()
并且现在存储为a
内的字符串。Add your full code in a file, save it. Hit f.e. F5 to debug/run program.
You may need to select
to run it. It will be executed in the "TERMINAL":
input a number:
hit enter:
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
then it takes your next line
as your input and stores it inside
a
.Then it executes
and complains about
b
because your lineb = int(a) + 2
was used asinput()
and is now stored as string insidea
.感谢大家的帮助。我从答案中发现的是 Terminal &交互窗口的行为各不相同。
终端:逐行执行代码。因此,立即给出一个代码块并在该代码块的第一行输入,在这里效果不佳。
交互式窗口:可以采用代码块和正如您在问题的输出中看到的那样,行动/执行比终端更智能。
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.
这很简单,
如果你在 python 终端中编写
a = input("a : ")
,它就会执行,请参阅此另外,如果我复制您的代码并将其粘贴到终端中那么它看起来像这样
->如果您在此图中看到 b = int(a) + 2 则将其作为 a 的输入。因此你会得到错误
结论
当您编写
a = input("a : ")
时,您需要在此处给出输入 example(12)然后写
b = int(a) + 2
然后,
print(f"a:{a}:b{b}")
it is simple
if you write
a = input("a : ")
in python terminal it get execute see thisAlso If I copy your code and paste it into the terminal then it looks like this
-> If you see in this image here b = int(a) + 2 take as the input of a. Therefore you get error
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}")