python - 从 Python 读取输入并在 while 循环中打印出来

标签 python c++ input while-loop

我想知道如何将以下 C++ 代码转换为 Python 代码。

int n;
while (cin >> n)
cout << n <<endl;

我猜应该是这样的

import sys

while n = raw_input():
   print n + "\n"

但它不起作用...请帮助我。谢谢。

最佳答案

也许是这样的:

import sys # why?

n = "string"

while n:
    n = raw_input()
    print n + '\n'

不过

while n = raw_input(): # incorrect.

这行不通,因为:

  1. n 未定义
  2. 在任何情况下,要测试相等性,您通常应该使用 ==,但在这种特殊情况下不是这样,因为它基本上意味着,而 n 等于 空字符串( '' )

例子:

>>> raw_input() == ''
True

关于python - 从 Python 读取输入并在 while 循环中打印出来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21354885/

相关文章:

python - 在 SQLAlchemy 中使用非数据库支持的模型

c++ - 更喜欢 std::variant<bool, std::string> 中的 std::string for const char *

c++ - 使用 async 的并行函数调用

javascript - 防止未经允许的粘贴到文本输入中

python - lxml XPathposition() 不起作用

python - 中给出的大多数数字的意外输出。(Python)

python - 如何使用 3to2

c++ - 引用 std::atomic<bool> 的已删除函数错误

css - 更改占位符的字体系列

javascript - 在日期时间本地输入中隐藏年、月和日