从Python读取输入,并在循环时打印出来
Reading input from Python and print out in 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.
这是不起作用的,因为:
-
n
未定义 - 在任何情况下,要测试平等,您通常应该使用
==
,尽管在这种情况下不是,因为这基本上意味着n
等于empty string( '' )
示例:
>>> raw_input() == ''
True
那是因为Python中的n = raw_input()
不返回一个值,而C 中的cin >> n
则返回。(这使程序员免于用=
替换==
的最常见错误)
您可以尝试类似的东西。
n = raw_input("Enter Something: ")
while n:
print n
n = raw_input("Enter Something: ")
测试运行:
>>>
Enter Something: Monty
Monty
Enter Something: Python
Python
Enter Something: Empty Line Next
Empty Line Next
Enter Something:
p.s - 在这种情况下,import sys
不需要(如果您在代码中的其他任何地方都不使用)。另外,print
语句会自动将光标移至下一行,因此在这种情况下,您无需添加n
。
相关文章:
- 如何循环打印顶点结构
- 了解嵌套循环打印星号图案
- C++ 无法在字符数组中使用 for 循环打印字母模式
- 如何在c++中仅使用for循环打印此代码的垂直直方图
- 使用 for 循环打印字符串数组无法正常工作 (C++)
- C++服务器程序循环打印
- 循环打印垃圾 c++ 的链表
- 使用用户输入(无矢量)从 For 循环打印图表
- 我想反转地图的值并使用基于范围的 for 循环打印它
- c++While循环打印couts两次
- 用于中断后的循环打印
- 使用 while 循环打印一系列偶数和奇数
- 我需要使用嵌套的 while 循环打印一个正方形。我想我已经用正确的逻辑对其进行了编码,但它没有给我所需的输出
- C/C++ 拼图:使用单个 for 循环打印 1.15 15.1 的值
- 我可以用cout而不是迭代器循环打印STL映射吗?
- 循环打印时出现分段故障
- 在我的程序中使用for循环打印矩阵的错误
- c++帮助循环打印星号
- C++ 对于每个循环打印一个数组
- 使用 while 循环打印两个用户输入值范围内的数字