2017-03-01 51 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