对一个变量使用两个单独的循环-python

对一个变量使用两个单独的循环-python,python,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 = 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
n=int(输入(“请输入一个数字!”)
打印(“for循环的输出:”)
对于范围(n,101)内的i:
印刷品(一)
打印(“带while循环的输出:”)

当n时,问题是您正在第一个循环中更改
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

在第一个循环中,
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

请在你的答案中添加一些解释,以便其他人可以从中学习
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
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