2017-03-01 50 views
-4

我用for回路输入nPython 3里输入回路

n = int(input("")) 
for i in range(n): 
    a = input("") 
    print(a) 

当我输入:

3 
1 
1 
1 
2 

这让我输入n+1

而且n+1字不能输出

我只是想输出n个字,然后用语法等于在C

int a = 0; 
for(int i=0; i<n; i++) 
    scanf("%d",&a); 

[更新]

其实这是Pycharm问题。我不知道为什么。

在终端中,代码可以工作。

因此,PLZ没有downvote ....

+1

该代码适用于我。你如何运行它?你是在终端还是在IDE中运行它?将一个提示字符串传递给'input',例如'input(“>”)'来验证它实际上是接受第n + 1个字的输入。 –

+1

您的C代码不会向输出写入任何内容。 – Goyo

回答

0

它跑了3次,当我尝试它。 如果你想让它更明确你在做什么,你可以将它设置为for i in range(0,n):但这并不会改变任何事情。

循环for i in range(n):将从0运行到n-1。 所以,如果你在3所说的那样,它会产生运行3次,用i为0,1的值,2

n = int(input("Enter the number of runs: ")) 
for item in range(0, n): 
    a = input("\tPlease Input value for index %d: "%item) 
    print(a) 

它生成的输出:

Enter the number of runs: 3 
    Please Input value for index 0: 1 
1 
    Please Input value for index 1: 1 
1 
    Please Input value for index 2: 1 
1 
0

我不明白为什么这不适合你。试试这个修改后的版本,使得它更清楚发生了什么:

n = int(input("Enter number of values: ")) 
for i in range(n): 
    a = input("Enter value {} ".format(i+1)) 
    print("Value {0} was {1}".format(i+1, a)) 

从这里输出继电器是:

输入值的数量:3 输入值1 值1 1 输入值2 1 值2是1 输入值3 2 值3是2

0

我认为你对循环打印的输出感到困惑。

如果在第一个n = int(input(""))"中输入3,则循环将从0变为2(含)。

在每个循环中,您都要求输入一个新的值a并打印出来。因此,在第一个循环之后,您输入1并输出1(因为它会打印它)。在第二个循环中,输入另一个1并打印出来。最后你输入一个2,它也打印出来。

第一个循环:

input: 1 
output: 1 

第二环:

input: 1 
output: 1 

三环路:

input: 2 
output: 2 

这就是为什么如果我运行下面的

>>> n = int(input("")) 
3 
>>> for i in range(n): 
...  a = input("") 
...  print a 
... 
1 
1 
2 
2 
3 
3 

我得到6个数字(输入和输出)。您可以通过以下示例更清楚地看到这一点:

>>> n = int(input("Input: ")) 
Input: 3 
>>> for i in range(n): 
...  a = input("Input: ") 
...  print "Output: " + str(a) 
... 
Input: 1 
Output: 1 
Input: 2 
Output: 2 
Input: 3 
Output: 3