[英]Using two separate loops for one variable - python
我正在為學校開發一個程序,我應該獲取用戶輸入並在兩個單獨的循環中使用它。
n = int(input("Please enter a number! "))
print("Output from for loop:")
for i in range (n, 101):
print(n)
n += 1
print("Output with while loop:")
while n <= 100:
print(n)
n += 1
在第一個循環運行后,我假設變量更改為 100 並且第二個循環沒有運行,我應該如何解決這個問題? 從提示中可以清楚地看出只使用一個輸入。
類示例:
Please input an integer value to start counting to 100: 92
Output from For loop:
92
93
94
95
96
97
98
99
100
Output from While loop:
92
93
94
95
96
97
98
99
100
問題是你在第一個循環中改變了n
的值,所以當你進入第二個循環時,它已經 > 100。所以第二個循環沒有做任何事情。 這是修復它的簡單方法:
n = int(input("Please enter a number! "))
print("Output from for loop:")
for i in range (n, 101):
print(i)
print("Output with while loop:")
while n <= 100:
print(n)
n += 1
結果:
Please enter a number! 92
Output from for loop:
92
93
94
95
96
97
98
99
100
Output with while loop:
92
93
94
95
96
97
98
99
100
在第一個循環中, i
已經是您要打印的值。 無需增加 'n' 並將其弄亂。 如果你真的有需要增加的值等n
分離開i
,你可以復制n
說nn
,然后增量和打印。 但在這種情況下,為什么不直接使用i
。
您可以將另一個變量 (n2) 設置為 n。 然后你可以在while循環中使用
像這樣:
n = int(input("Please enter a number! "))
n2 = n
print("Output from for loop:")
for i in range (n, 101):
print(n)
n += 1
print("Output with while loop:")
while n2 <= 100:
print(n2)
n2 += 1
輸出:
Please enter a number! 92
Output from for loop:
92
93
94
95
96
97
98
99
100
Output with while loop:
92
93
94
95
96
97
98
99
100
n = int(input("Please enter a number! "))
print("Output from for loop:")
for i in range (n, 101):
print(i)
print("Output with while loop:")
while n <= 100:
print(n)
n += 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.