从Python读取输入,并在循环时打印出来

Reading input from Python and print out in while loop

本文关键字:循环 打印 Python 读取 输入      更新时间:2023-10-16

我想知道如何将以下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等于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