问题
I am a beginner and I am stuck on this problem, "Write a python code that uses a while loop to print even numbers from 2 through 100. Hint ConsecutiveEven differ by 2."
Here is what I came up with so far:
while num in range(22,101,2):
print(num)
回答1:
Use either for
with range()
, or use while
and explicitly increment the number. For example:
>>> i = 2
>>> while i <=10: # Using while
... print(i)
... i += 2
...
2
4
6
8
10
>>> for i in range(2, 11, 2): # Using for
... print(i)
...
2
4
6
8
10
回答2:
Your code has several problems:
- Substituting
while
for a statement withfor
syntax.while
takes a bool, not an iterable. - Using incorrect values for
range
: you will start at 22.
With minimal changes, this should work:
for num in range(2, 101, 2):
print(num)
Note that I used 101
for the upper limit of range
because it is exclusive. If I put 100
it would stop at 98
.
If you need to use a while
loop:
n = 2
while n <= 100:
print (n)
n += 2
回答3:
Here is how to use the while loop
while [condition]:
logic here
using while in range is incorrect.
num = 0
while num <=100:
if num % 2 == 0:
print(num)
num += 1
回答4:
This is what I'd try:
i=2
while i <= 100:
if ( i % 2==0):
print (i, end=', ')
i+=1
来源:https://stackoverflow.com/questions/40094424/how-is-it-possible-to-use-a-while-loop-to-print-even-numbers-2-through-100